如何修复 android.os.NetworkOnMainThreadException?
androidapps/applicationsmobile development
当应用程序尝试在其主线程上执行网络操作时抛出的异常。
只有针对 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 运行该应用程序,请打开项目的某个活动文件,然后点击工具栏上的"运行"
图标。选择您的移动设备作为选项,然后检查您的移动设备是否显示您的默认屏幕 −


点击此处下载项目代码。

