Error StrictMode$AndroidBlockGuardPolicy.onNetwork
本问题已经有最佳答案,请猛点这里访问。
我创建了android应用程序并使用
1 2 | android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) |
我该如何解决这个问题
谢谢
你必须在MainActivity Class上插入2行"StrictMode",例如下面的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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
最好使用这里提到的
1 2 3 4 | if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } |
或这个 :
1 2 3 4 5 6 7 8 9 10 11 | 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(); |
在您的活动中发生
只需在create方法后添加两行
1 2 | StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); |