0

我已经体验过这段代码在Android 2.2上运行流畅。但在Android 4.0上它崩溃了。

我假设,它是由HttpClient引起的。所以我将代码移到了Runnable中,但它一直在崩溃。

new Runnable() {

        @Override
        public void run() {
            try {        
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI(serverroot + URI_ARGS));
                client.execute(request);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.run();

在不使用AsyncTask的情况下是否有另一种方法可以做到这一点?

4

1 回答 1

0

API11NetworkOnMainThreadException开始,如果您在 UI 线程上使用网络,则会引发新的异常,因此您需要将代码移出 UI 线程。Runnable只是界面它不会帮助你没有实际Thread

new Thread(new Runnable() {

    @Override
    public void run() {
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(serverroot + URI_ARGS));
            client.execute(request);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}).start();
于 2013-05-05T19:23:12.240 回答