如何修復android.os.NetworkOnMainThreadException?
當應用程式嘗試在其主執行緒上執行網路操作時丟擲的異常。
此異常僅針對目標為 Honeycomb SDK 或更高版本的應用程式丟擲。針對早期 SDK 版本的應用程式允許在其主事件迴圈執行緒上進行網路操作,但這強烈不建議。
請參考下面的示例程式來修復此異常:
此示例演示如何修復android.os.NetworkOnMainThreadException。
步驟1 - 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立一個新專案。
步驟2 - 將以下程式碼新增到res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://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>
步驟3 - 將以下程式碼新增到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);
}
}
}步驟4 - 將以下程式碼新增到androidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://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>
讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟您的一個專案活動檔案,然後單擊執行
工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕:


點選這裡下載專案程式碼。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP