Android--NetWorkOnMainThreadException异常解决

解释

这是由于网络工作在主线程中执行产生的异常。从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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值