Android:无法在主线程上执行网络操作

时间:2012-10-24 18:35:35

标签: android

  

可能重复:
  android.os.NetworkOnMainThreadException

我正在尝试为Android构建一个RSS阅读器。 这是我的代码。我收到错误,说无法在线程上执行网络操作。

URL url = null;
try {
url = new URL((data.get(position).getThumbnail()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream content = null;
try {
content = (InputStream)url.getContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(content , "src"); 
Bitmap mIcon1 = null;
try {
mIcon1 =
BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}

详细说明: API是16 我正在使用XP专业版,SP3。 Android操作系统:Jelly Bean

这是我的logcat错误: http://pastebin.com/9wyVpNHV

3 个答案:

答案 0 :(得分:3)

正确。从Android 4.0(或4.1)开始,如果在主应用程序线程上执行网络I / O,则会自动失败。请将您的上述代码移至后台帖子,例如AsyncTask

答案 1 :(得分:2)

使用线程和处理程序轻松地在UI线程和其他线程之间交换数据

//Handler to send commands to UI thread
    Handler handler = new Handler();

    Thread th = new Thread(new Runnable() {
        public void run() {

            URL url = null; 
            InputStream content = null;
            try { 
                url = new URL((data.get(position).getThumbnail())); 

                content = (InputStream)url.getContent();
                Drawable d = Drawable.createFromStream(content , "src");  
                final Bitmap mIcon1 = BitmapFactory.decodeStream(url.openConnection().getInputStream());; 

                handler.post(new Runnable() {

                    public void run() {
                        //here you can do everything in UI thread, like put the icon in a imageVew
                    }
                });

            } catch (Exception e) { 
                e.printStackTrace();
                handler.post(new Runnable() {

                    public void run() {
                        Toast.makeText(YourActivityName.this, e.getMessage(), Toast.LENGTH_LONG);
                    }
                });
            } 


        }
    });
    th.start();

答案 2 :(得分:0)

如上所述,在最近的API网络操作应该在一个单独的线程中完成,否则它们会引发异常。以下是开发人员网站的一些示例:

Perform Network Operations on a Separate Thread