当前位置: 首页 > 知识库问答 >
问题:

如何在Android中修复NetworkonMainThreadException?[副本]

严锐
2023-03-14
<uses-permission android:name="android.permission.INTERNET"/>

首选项:我的android首选项是

<uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
  1. API级别18
  2. Android 4.3

这就是我如何读取url

static InputStream is = null;

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
11-02 05:23:47.843: E/AndroidRuntime(2207): FATAL EXCEPTION: main
11-02 05:23:47.843: E/AndroidRuntime(2207): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.me.countrypedia/com.me.countrypedia.MainActivity}: android.os.NetworkOnMainThreadException
11-02 05:23:47.843: E/AndroidRuntime(2207):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-02 05:23:47.843: E/AndroidRuntime(2207):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-02 05:23:47.843: E/AndroidRuntime(2207):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-02 05:23:47.843: E/AndroidRuntime(2207):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)

共有1个答案

公孙智
2023-03-14

您的异常实际上准确地告诉您哪里做错了。您没有使用另一个线程来执行网络操作。相反,您在UI线程上执行网络操作,这在Android上不能(不)工作。

连接到url的代码应该在AsyncTasksdoinbackground()方法中执行,离开UI线程。

请看这个关于如何使用AsyncTask的问题:如何使用AsyncTask

 类似资料: