Android NetworkOnMainThreadException when calling Url.OpenStream

為{幸葍}努か 提交于 2019-12-06 15:40:06

Please never run a networking operation on the main (UI) thread .

Main thread is used to:

  • interact with user.
  • render UI components.

any long operation on it may risk your app to be closed with ANR message.

Take a look at the following :

you can easily use an AsyncTask or a Thread to perform your network operations.

Here is a great tutorial about threads and background work in android: Link

Works for me:

Manifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

.java:

private static boolean DEVELOPER_MODE = true;
...
protected void onCreate(Bundle savedInstanceState) {

     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());
     }  
...

hope it helps.

see also : http://developer.android.com/reference/android/os/StrictMode.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!