标签:
Android 4.2项目:下载网络歌曲
报错:android.os.NetworkOnMainThreadException
网上搜索后知道是因为版本问题,在4.0之后在主线程里面执行Http请求都会报这个错,也许是怕Http请求时间太长造成程序假死的情况吧。那么网上的朋友也给出了相应的解决方案,这叫上有政策下有对策:
一:在发起Http请求的Activity里面的onCreate函数里面添加如下代码:
//详见StrictMode文档
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
二:使用Thread、Runnable、Handler这三个类:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.share_mblog_view); new Thread(runnable).start(); } Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle data = msg.getData(); String val = data.getString("value"); Log.i("mylog","请求结果为-->" + val); } } Runnable runnable = new Runnable(){ @Override public void run() { // // TODO: http request. // Message msg = new Message(); Bundle data = new Bundle(); data.putString("value","请求结果"); msg.setData(data); handler.sendMessage(msg); } }
异常:android.os.NetworkOnMainThreadException
标签:
原文地址:http://www.cnblogs.com/tjuscslirui/p/4573706.html