先写两个错误:
1.android.os.NetworkOnMainThreadException
2.android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
第一个是因为网络请求放在了主线程中进行;第二个是因为子线程中又对主线程做的 UI 进行操作。
最后参考这个http://www.tuicool.com/articles/MvmeYr,测试通过。
正确的方式:
1.网络请求必须要放到子线程去做
2.通过 handler 来将子线程获取的数据传递到主线程中取。
new Thread(runnable).start(); Handler handler = new Handler(){ public void handleMessage(Message msg){ super.handleMessage(msg); Bundle data = msg.getData(); String val = data.getString("value"); //下面是主线程中的 UI 操作举例 tabContent = (TextView) findViewById(R.id.tabContent); tabContent.setText(val); } } Runnable runnable = new Runnable(){ public void run(){ String apiUrl = "http://xxx"; String res = HttpGet(apiUrl); Message msg = new Message(); Bundle data = new Bundle(); data.putString("value",res); msg.setData(data); handler.sendMessage(msg); } } public HttpGet(String url){ //封装下 httpGet }
效果如图,马上就要成功啦,happy: