您的位置:首页 > 移动开发 > Android开发

解决android.os.NetworkOnMainThreadException

2014-06-05 18:40 375 查看
在我用手机测试我们的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.csdn.net/detail/changliangdoscript/7452907

原文地址: http://www.2cto.com/kf/201402/281526.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android application