Android的android.os.NetworkOnMainThreadException异常

作者: 蓝骑士 分类: Android 发布时间: 2012-11-16 14:48

今天突然发现,以前写的Android应用腾讯微博分享功能不能用了,闹心啊。。。。。。

于是,开始了调试之路。。。

打开Eclipse,控制台报出android.os.NetworkOnMainThreadException异常,我去。。闹心,原来是这货。。。

去官网查了下,发现从Android 3.0开始,不允许在主线程中运行Network操作。

官网提供的示例代码用StrictMode来解决这个问题。

 

 public void onCreate() {
     if (DEVELOPER_MODE) {
         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());
     }
     super.onCreate();
 }

 

但是,咱的应用是跑在2.1以上的啊,StrictMode在Android 2.3以后才提供。。。

再一次闹心了。。。

只能尝试别的方法。。。。看到官网上有这么一段话

If you find violations that you feel are problematic, there are a variety of tools to help solve them: threads, HandlerAsyncTaskIntentService, etc. But don’t feel compelled to fix everything that StrictMode finds. In particular, many cases of disk access are often necessary during the normal activity lifecycle. Use StrictMode to find things you did by accident. Network requests on the UI thread are almost always a problem, though.

意思就是可以用threads、handler、AsyncTask、IntentService来解决这个问题,StrictMode不能解决一切的问题。

采用Thread+Handler成功解决NetworkOnMainThreadException问题。

 

最后提一下:

StrictMode is not a security mechanism and is not guaranteed to find all disk or network accesses. While it does propagate its state across process boundaries when doing Binder calls, it’s still ultimately a best effort mechanism. Notably, disk or network access from JNI calls won’t necessarily trigger it. Future versions of Android may catch more (or fewer) operations, so you should never leave StrictMode enabled in applications distributed on Google Play.

意思就是StrictMode并不是万能的,它并不能解决所有的问题,但是在Android将来的版本中,它将会帮助我们找出错误。

所以,期待StrictMode以后的表现。

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!