android.os.NetworkOnMainThreadException
网络请求不能在主线程,修改如下:
import android.os.Handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newThread(networkTask).start();
}
Handlerhandler=newHandler() {
@Override
public voidhandleMessage(Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
String val = data.getString("value");
Log.i("mylog","请求结果为-->"+ val);
//TODO
// UI界面的更新等相关操作
}
};
/**
* 网络操作相关的子线程
*/
RunnablenetworkTask=newRunnable() {
@Override
public voidrun() {
// 在这里进行 http request.网络请求相关操作
Message msg =newMessage();
Bundle data =newBundle();
data.putString("value","请求结果");
msg.setData(data);
handler.sendMessage(msg);
}
};