1、异常:android.os.NetworkOnMainThreadException
在android2.3之后 在主线程中必须使用另一个线程 如handler机制,或者异步任务获取网络数据
如果你访问网络的操作 必须放在主线程中执行,那么 在oncreate()中添加:
public void onCreate(Bundle savedInstanceState) { // 详见StrictMode文档 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); super.onCreate(savedInstanceState); setContentView(R.layout.main); InitDialog(); }
这样,高版本中也可以在主线程中执行网络操作了,或者是再启动线程去执行网络操作:
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); } }
扩展:Handler主要接受子线程发送的数据, 并用此数据配合主线程更新UI,参考http://www.pin5i.com/showtopic-android-handler.html
多线程参考:http://www.cnblogs.com/ccdc/p/3836966.html