解决办法有两个思路,分别是:
第一种方法:直接忽视,强制使用(强烈不推荐,但是修改简单)
在MainActivity文件的setContentView(R.layout.activity_main)下面加上如下代码
1 2 3 4 | if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);} |
第二种方法:使用Thread、Runnable、Handler (推荐使用)
在Runnable中做HTTP请求,不用阻塞UI线程~
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 27 28 29 | public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.share_mblog_view); new Thread(runnable).start();}Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle data = msg.getData(); String val = data.getString("value"); Log.i("mylog","请求结果-->" + val); }}Runnable runnable = new Runnable(){ @Override public void run() { // // TODO: http request. // Message msg = new Message(); Bundle data = new Bundle(); data.putString("value","请求结果"); msg.setData(data); handler.sendMessage(msg); }} |