android异常 android.os.NetworkOnMainThreadException

android4.2网络访问异常
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test_application/com.example.test_application.WebPicActivity}: android.os.NetworkOnMainThreadException

 

原因是在4.2中,访问网络不能在主程序中进行,有一下两种解决方案:

1.一个是在主程序中增加

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.启动单独线程访问网络

new Thread(web).start();
 /** * web线程 */ Runnable web= new Runnable(){ @Override public void run() { ...... } };

 

 

你可能感兴趣的:(android)