Error StrictMode$AndroidBlockGuardPolicy.onNetwork

This question already has an answer here:

  • How do I fix android.os.NetworkOnMainThreadException? 49 answers

  • you have to insert 2 lines "StrictMode" on MainActivity Class, example's below:

    public class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
    
            try {
                // JSON here
            } catch (JSONException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
    
            setContentView(R.layout.activity_main);
            Intent intent=new Intent(this,HomeActivity.class);
            startActivity(intent);
        }
    }
    

    Aey.Sakon


    Better to use AsyncTask as mentioned here, an Alternative for just getting rid of the Exception is use :

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

    or this :

    Thread thread = new Thread(new Runnable(){
    @Override
    public void run() {
        try {
            //Your code goes here
        } catch (Exception e) {
           Log.e(TAG, e.getMessage());
        }
    }
    });
    thread.start();
    

    in your Activity where Exception occurs.


    在创建方法后只需添加两行

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    
    链接地址: http://www.djcxy.com/p/29522.html

    上一篇: android.os.NetworkOnMainThreadException与android 4.2

    下一篇: 错误StrictMode $ AndroidBlockGuardPolicy.onNetwork