android.os.NetworkOnMainThreadException

来源:互联网 发布:淘宝数据魔方登陆 编辑:程序博客网 时间:2024/04/30 18:39

依旧是昨天提到的那个android app,出现了一个这样的问题,android.os.NetworkOnMainThreadException

说明是Only the original thread that created a view hierarchy can touch its views.最为纠结的是我这代码是在网上找的,把网上找的代码项目加进eclipse中,运行发现是好用的,可是我把代码原样拷贝过来却是不好用的,于是我就在找区别,发现根本就没有区别,mainfest.xml文件也一样了,于是去网上找,好吧,我好水,找了挺久,晚饭都没吃~~

进入正题:

其实原因是以为网上找的那个项目用的是4.1.2版本的android api,而我的项目中用的是4.3版本的android api,这个就是导致问题的原因,Android的相关View和控件不是线程安全的,有两种解决方法

1.在主线程中添加如下代码即可,不知道是什么,但是可以用

// 详见StrictMode文档  StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()          .detectDiskReads()          .detectDiskWrites()          .detectNetwork()   // or .detectAll() for all detectable problems          .penaltyLog()          .build());  StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()          .detectLeakedSqlLiteObjects()          .detectLeakedClosableObjects()          .penaltyLog()          .penaltyDeath()          .build()); 
2.用多线程,不再主线程里面进行更行UI的操作

Runnable   runnableUi=new  Runnable(){          @Override          public void run() {              //更新界面              final String mobile = mobileText.getText().toString();              final InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("mobilesoap.xml");          try               {           addressView.setText(MobileInfoService.getMobileAddress(inStream, mobile));              }        catch (Exception e)              {                  Log.e(TAG, e.toString());                  Toast.makeText(MainActivity.this, "查询失败", 1).show();              }          }                }; 


new Thread(){                  public void run(){                      handler.post(runnableUi);                       }                                 }.start();  
这样问题也就解决了

原创粉丝点击