android.os.NetworkOnMainThreadException

This Exception occurs in Android if you are executing some network activity on the main UI thread.
The good practice is to use AsyncTask to execute som network activity on the UI thread.

But But But....

AsyncTask is deprecated in Api level 30 :)

Still you can use the the below code to execute any network Activity on our main thread.


Code:

if (android.os.Build.VERSION.SDK_INT > 9) {
     StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
   }

Else you can create a new thread like :



    Thread thread = new Thread(){
@Override
public void run() {
super.run();
//start any network activity
    }
    };
 
    thread.run();

    //to stop a thread

    thread.interrupt();



Hope this will e helpful:)

Comments