在Jelly Bean中出现NetworkOnMainThreadException错误

10

我过去一周一直在尝试让它正常工作,但仍然不知道问题出在哪里。它可以在Android 2.1上运行,但在4.1上无法运行。我在我的应用程序中有一个检查更新的服务,其中包含这个字符串。

latestVersion = Integer.parseInt(getHttpString(urlLatestVersion));

它被称为checkForUpdate();,它在onStart(Intent intent, int startId);中被调用。

private String getHttpString(String urlString) throws IOException {
            InputStream in = null;
            int response = -1;

            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();

            if (!(conn instanceof HttpURLConnection))
                    throw new IOException("Not an HTTP connection");

            try {
                    HttpURLConnection httpConn = (HttpURLConnection) conn;
                    httpConn.setAllowUserInteraction(false);
                    httpConn.setInstanceFollowRedirects(true);
                    httpConn.setRequestMethod("GET");
                    httpConn.connect();

                    response = httpConn.getResponseCode();
                    if (response == HttpURLConnection.HTTP_OK) {
                            in = httpConn.getInputStream();
                    }
            } catch (Exception ex) {
                    ex.printStackTrace();
                    //
                    //main error currently lies here
                    // TODO fix errors that accures on android 4.0 and above.
                    //
            }
            if (in != null) {
                    StringBuilder sb = new StringBuilder();
                    String line;

                    try {
                            BufferedReader reader = new BufferedReader(
                                            new InputStreamReader(in, "UTF-8"));
                            while ((line = reader.readLine()) != null) {
                                    sb.append(line); // .append("\n");
                            }
                    } finally {
                            in.close();
                    }
                    return sb.toString();
            } else
                    return "";

    }

这是来自logcat的错误信息。
W/System.err( 7077): android.os.NetworkOnMainThreadException
W/System.err( 7077):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
W/System.err( 7077):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
W/System.err( 7077):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
W/System.err( 7077):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
W/System.err( 7077):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
W/System.err( 7077):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
W/System.err( 7077):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
W/System.err( 7077):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
W/System.err( 7077):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
W/System.err( 7077):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
W/System.err( 7077):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
W/System.err( 7077):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
W/System.err( 7077):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
W/System.err( 7077):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
W/System.err( 7077):    at com.lukemovement.roottoolbox.pro.Update.getHttpString(Update.java:166)
W/System.err( 7077):    at com.lukemovement.roottoolbox.pro.Update.checkForUpdate(Update.java:98)
W/System.err( 7077):    at com.lukemovement.roottoolbox.pro.Update.onStart(Update.java:75)
W/System.err( 7077):    at android.app.Service.onStartCommand(Service.java:450)
W/System.err( 7077):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2620)
W/System.err( 7077):    at android.app.ActivityThread.access$1900(ActivityThread.java:143)
W/System.err( 7077):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
W/System.err( 7077):    at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err( 7077):    at android.os.Looper.loop(Looper.java:137)
W/System.err( 7077):    at android.app.ActivityThread.main(ActivityThread.java:4935)
W/System.err( 7077):    at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err( 7077):    at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err( 7077):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
W/System.err( 7077):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
W/System.err( 7077):    at dalvik.system.NativeStart.main(Native Method)
I/Example update( 7077): Invalid int: ""

Android已经放弃向后兼容性了吗,还是只是忘记添加这一部分了?

我读到需要使用AsyncTask。但是我似乎无法让它为我工作,有人可以帮助我吗?


你可能已经意识到,你需要异步/多线程执行。你尝试过什么?你遇到了什么问题? - SLaks
在onStart方法中创建了一个线程来解决问题。只是刚刚才想到这个方法。 - Luke Pring
2个回答

9

从Android API v15开始,它不需要在主线程上进行繁重的处理。因此,您应该将逻辑移动到另一个线程中,如下面的源代码所示:

new Thread(new Runnable() {
   public void run() {
        // your logic
   }                        
}).start();

更多信息请参考:响应性


回复您的答案,我只是想知道为什么我和这个人一样遇到了同样的异常。我将我的代码放在Async Task中,它在非主线程中启动,而是在其他线程中,在那里我需要按一个按钮到达它。我使用的API级别是14和17。 - Raditya Kurnianto

0

只需在调用异步任务的活动的onCreate方法中添加此代码。

代码:

StrictMode.ThreadPolicy policy =
    new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

API 8 的等效代码是什么? - Dr TJ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接