你的位置:首页 > 软件开发 > 操作系统 > Android之NetworkOnMainThreadException异常

Android之NetworkOnMainThreadException异常

发布时间:2015-03-13 00:00:42
看名字就应该知道,是网络请求在MainThread中产生的异常 先来看一下官网的解释: Class OverviewThe exception that is thrown when an application attempts to perform a network ...

看名字就应该知道,是网络请求在MainThread中产生的异常

 

先来看一下官网的解释:

 

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.

http://developer.android.com/intl/zh-cn/reference/android/os/NetworkOnMainThreadException.html

 

解释一下,从Honeycomb SDK(3.0)开始,google不再允许网络请求(HTTP、Socket)等相关操作直接在Main Thread类中,其实本来就不应该这样做,直接在UI线程进行网络操作,会阻塞UI、用户体验相当bad!即便google不禁止,一般情况下我们也不会这么做吧~

所以,也就是说,在Honeycomb SDK(3.0)以下的版本,你还可以继续在Main Thread里这样做,在3.0以上,就不行了,建议

 

1,和network有关比较耗时的操作放到一个子线程里,然后用Handler消息机制与主线程通信。

  public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    this.setContentView(R.layout.test);    // 开启一个子线程,进行网络操作,等待有返回结果,使用handler通知UI    new Thread(networkTask).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);      // TODO      // UI界面的更新等相关操作    }  };  /**   * 网络操作相关的子线程   */  Runnable networkTask = 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之NetworkOnMainThreadException异常

关键词:Android

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录