Android NetworkOnMainThreadException when calling Url.OpenStream

谁说我不能喝 提交于 2020-01-03 04:36:06

问题


I get this exception when running my code on emulator (Android 4.0.3 / API 15). While opening a stream it will throw an exception. Error-message is null.

try {
    String adress        = "xxx";
    URL url              = new URL(adress);
    InputSource source   = new InputSource(url.openStream());

} catch (Exception e) {
    (new TextView).setText("Error: "+e.getMessage());
}

URL is still working with the emulator (in browser).

I have cleaned the project.

Also Internet connection is allowed:

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

Exception : android.os.NetworkOnMainThreadException


回答1:


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 :

  • Keeping your application Responsive
  • NetworkOnMainThreadException

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




回答2:


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



来源:https://stackoverflow.com/questions/15685153/android-networkonmainthreadexception-when-calling-url-openstream

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