Quantcast
Channel: How can I fix 'android.os.NetworkOnMainThreadException'? - Stack Overflow
Viewing all articles
Browse latest Browse all 191

Answer by Rahul for How do I fix 'android.os.NetworkOnMainThreadException'?

$
0
0

Never do any long running work on UI thread, that long running work can be communication with server, read/write on file etc. These tasks should be on background thread, thats why Service, AsyncTask, Threads created. You can disable StrictMode that will prevent crash but that never recommended.

I would suggest you take an advantage of StrictMode atleast in Debug mode. Use below code to get logs of any issue which slows down your App on main thread.

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
            .detectAll()
            .penaltyLog()
            .build());

You can set different penalties -

penaltyLog() // to print log
penaltyDeath() // This will crash you App(so costly penalty)
penaltyDialog() // Show alert when something went lazy on Main thread

There is so much about https://developer.android.com/reference/android/os/StrictMode.html


Viewing all articles
Browse latest Browse all 191

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>