Computer >> Máy Tính >  >> Lập trình >> Android

Làm thế nào để sửa lỗi android.os.NetworkOnMainThreadException?


Ngoại lệ được đưa ra khi một ứng dụng cố gắng thực hiện thao tác kết nối mạng trên chuỗi chính của nó.

Điều này chỉ được áp dụng cho các ứng dụng nhắm mục tiêu Honeycomb SDK trở lên. Các ứng dụng nhắm mục tiêu các phiên bản SDK cũ hơn được phép thực hiện mạng trên các chuỗi vòng lặp sự kiện chính của chúng, nhưng điều này rất không được khuyến khích.

Vui lòng tham khảo chương trình ví dụ dưới đây để khắc phục ngoại lệ này -

Ví dụ này giải thích cách tôi sửa lỗi android.os.NetworkOnMainThreadException.

Bước 1 - Tạo một dự án mới trong Android Studio, đi tới Tệp ⇒ Dự án Mới và điền tất cả các chi tiết cần thiết để tạo một dự án mới.

Bước 2 - Thêm mã sau vào 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:textSize="12sp"
      android:textStyle="bold|italic"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>
   <TextView
      android:id="@+id/textMessage"
      android:textSize="16sp"
      android:textStyle="bold"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>
</LinearLayout>

Bước 3 - Thêm mã sau vào 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 strMessage = "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("Loading...");
      new MyTask().execute();
   }
   private class MyTask extends AsyncTask<Void, Void, Void>{
      String result;
      @Override
      protected Void doInBackground(Void... voids) {
         URL url;
         try {
            url = new URL(strMessage);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
            String stringBuffer;
            String string = "";
            while ((stringBuffer = bufferedReader.readLine()) != null){
               string = String.format("%s%s", string, stringBuffer);
            }
            bufferedReader.close();
            result = string;
         } catch (IOException e){
            e.printStackTrace();
            result = e.toString();
         }
         return null;
      }
      @Override
      protected void onPostExecute(Void aVoid) {
         textMessage.setText(result);
         textLoad.setText("Finished");
         super.onPostExecute(aVoid);
      }
   }
}

Bước 4 - Thêm mã sau vào 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>

Hãy thử chạy ứng dụng của bạn. Tôi giả sử bạn đã kết nối thiết bị Di động Android thực tế với máy tính của mình. Để chạy ứng dụng từ android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Chạy từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn, sau đó kiểm tra thiết bị di động sẽ hiển thị màn hình mặc định của bạn -

Làm thế nào để sửa lỗi android.os.NetworkOnMainThreadException?

Làm thế nào để sửa lỗi android.os.NetworkOnMainThreadException?