Android--NetWorkOnMainThreadException异常解决

来源:互联网 发布:网络诽谤罪如何取证 编辑:程序博客网 时间:2024/06/04 19:09

解释

这是由于网络工作在主线程中执行产生的异常。从Android 3.0以后,谷歌不再允许网络请求在MainThread中执行。


解决方法

1:将网络工作放在子线程中执行。

// 刷新UI,将传来的Image消息实时显示在直播页面上    private void refreshUIImage(final String msg) {        ImagePath = msg;        final Thread t1 = new Thread(new Runnable() {            @Override            public void run() {                // TODO Auto-generated method stub                try {                    Imagebitmap = getBitMap(ImagePath);                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        });}
// 获取网络图片bitmap    public static Bitmap getBitMap(String path) throws IOException {        URL url = new URL(path);        HttpURLConnection conn = (HttpURLConnection) url.openConnection();        conn.setDoInput(true);        conn.setConnectTimeout(2000);        conn.setRequestMethod("GET");        if (conn.getResponseCode() == 200) {            InputStream inputStream = conn.getInputStream();            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);            inputStream.close();            return bitmap;        } else {            return null;        }    }

2:使用异步机制,下面的代码是网上找的。

class DownImage extends AsyncTask {        private ImageView imageView;        public DownImage(ImageView imageView) {          this.imageView = imageView;      }        @Override      protected Bitmap doInBackground(String... params) {          String url = params[0];          Bitmap bitmap = null;          try {              //加载一个网络图片              InputStream is = new URL(url).openStream();              bitmap = BitmapFactory.decodeStream(is);          } catch (Exception e) {              e.printStackTrace();          }          return bitmap;      }        @Override      protected void onPostExecute(Bitmap result) {          imageView.setImageBitmap(result);      }  }  

3:直接在主线程中进行网络操作,下面的代码是网上找的。

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()                      .detectDiskReads()                      .detectDiskWrites()                      .detectNetwork()                      .penaltyLog()                      .build());           StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()                      .detectLeakedSqlLiteObjects()                      .detectLeakedClosableObjects()                      .penaltyLog()                      .penaltyDeath()                      .build()); 

总结

关于网络工作的执行在子线程中,关于UI的修改在主线程中。


0 0
原创粉丝点击