解决android.os.NetworkOnMainThreadException


在我用手机测试我们的APP的时候,抛出一个如题的异常:
android.os.NetworkOnMainThreadException

字面意思是说:在主线程中的网络异常。然后我就去了解了下这个异常,先看看官方的说明:


NetworkOnMainThreadException

Class Overview


The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.

Also see StrictMode 

所以事情就很清楚了。一个APP如果在主线程中请求网络操作,将会抛出此异常。Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。

解决方案有两个,一个是使用StrictMode,二是使用线程来操作网络请求。

 

第一种方法:简单暴力,强制使用,代码修改简单(但是非常不推荐)

在MainActivity文件的setContentView(R.layout.activity_main)下面加上如下代码

 

if(android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = newStrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

第二种方法 将请求网络资源的代码使用Thread去操作。在Runnable中做HTTP请求,不用阻塞UI线程。 


publicvoid onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.main_view);
    newThread(runnable).start(); //here or somewhere to start
}
 
Handler handler = newHandler(){
    @Override
    publicvoid handleMessage(Message msg) {
        super.handleMessage(msg);
        Bundle data = msg.getData();
        String val = data.getString("value");
        Log.i(TAG,"请求结果:"+ val);
    }
}
 
Runnable runnable = newRunnable(){
    @Override
    publicvoid run() {
        // TODO: http request.
        Message msg = newMessage();
        Bundle data = newBundle();
        data.putString("value","请求结果");
        msg.setData(data);
        handler.sendMessage(msg); //send to the handler of the caller thread
    }
}

上面是比较通用的方法,我的代码:

// Android 4.0 之后不能在主线程中请求HTTP请求
            newThread(newRunnable(){
                @Override
                publicvoid run() {
                    cachedImage = asyncImageLoader.loadDrawable(imageUrl, position);
                    imageView.setImageDrawable(cachedImage);
                }
            }).start();



测试使用的完整例程下载: http://download.youkuaiyun.com/detail/changliangdoscript/7452907


原文地址: http://www.2cto.com/kf/201402/281526.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值