Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách khắc phục lỗi android.os.NetworkOnMainThreadException

Lỗi NetworkOnMainThreadException xảy ra khi ứng dụng thực hiện thao tác mạng (HTTP request, download...) trên **main thread (UI thread)**. Android 3.0+ (Honeycomb) cấm hành vi này để tránh treo giao diện.

✅ Giải pháp: Sử dụng AsyncTask (cũ) hoặc Coroutines/WorkManager (hiện đại)

Dưới đây là ví dụ dùng AsyncTask để tải nội dung từ URL trên background thread.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="8dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textLoad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:textStyle="bold|italic" />

    <TextView
        android:id="@+id/textMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>

Bước 3: Logic tải dữ liệu nền (src/MainActivity.java)

import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    TextView textLoad, textMessage;
    final String urlString = "https://sites.google.com/site/androidersite/text.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textLoad = findViewById(R.id.textLoad);
        textMessage = findViewById(R.id.textMessage);
        textLoad.setText("Đang tải...");
        new FetchDataTask().execute();
    }

    private class FetchDataTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL(urlString);
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                reader.close();
                return result.toString();
            } catch (IOException e) {
                e.printStackTrace();
                return "Lỗi: " + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            textMessage.setText(result);
            textLoad.setText("Hoàn tất");
        }
    }
}

Bước 4: Thêm quyền Internet (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

⚠️ Cảnh báo: AsyncTask đã deprecated (API 30+)

Nên dùng các giải pháp hiện đại:

  • Kotlin Coroutines + Retrofit/OkHttp — chuẩn hiện đại, dễ đọc, an toàn
  • WorkManager — cho tác vụ nền có lịch trình, đảm bảo chạy
  • RxJava / Flow — reactive programming
  • Volley / Retrofit (callback-based) — thư viện mạng phổ biến

Ví dụ nhanh với Coroutines (Kotlin):

lifecycleScope.launch(Dispatchers.IO) {
    try {
        val result = url.readText()
        withContext(Dispatchers.Main) {
            textMessage.text = result
            textLoad.text = "Hoàn tất"
        }
    } catch (e: Exception) {
        withContext(Dispatchers.Main) {
            textMessage.text = "Lỗi: ${e.message}"
        }
    }
}

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. App sẽ tải nội dung từ URL và hiển thị mà không bị crash.