产生的缘由。官方解释:html
Class Overview The exception that is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness. Also see StrictMode.
http://developer.android.com/intl/zh-cn/reference/android/os/NetworkOnMainThreadException.html
java
上面的意思是,从SDK3.0開始,google再也不赞成网络请求(HTTP、Socket)等相关操做直接在主线程中。事实上原本就不该该这样作,直接在UI线程进行网络操做。会堵塞UI、用户体验很差。
也就是说。在SDK3.0如下的版本号,还可以继续在主线程里这样作,在3.0以上,就不行了。因此。在如下的代码中。使用Thread、Runnable、Handler这三个类:
android
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.test); // 开启一个子线程。进行网络操做。等待有返回结果,使用handler通知UI new Thread(networkTask).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); // UI界面的更新等相关操做 } }; /** * 网络操做相关的子线程 */ Runnable networkTask = new Runnable() { @Override public void run() { // 在这里进行 http request.网络请求相关操做 MobEventService.postonKillProcess(context); Message msg = new Message(); Bundle data = new Bundle(); data.putString("value", "请求结果"); msg.setData(data); handler.sendMessage(msg); } };
class DownImage extends AsyncTask { private ImageView imageView; public DownImage(ImageView imageView) { this.imageView = imageView; } @Override protected Bitmap doInBackground(String... params) { String url = params[0]; Bitmap bitmap = null; try { //载入一个网络图片 InputStream is = new URL(url).openStream(); bitmap = BitmapFactory.decodeStream(is); } catch (Exception e) { e.printStackTrace(); } return bitmap; } @Override protected void onPostExecute(Bitmap result) { imageView.setImageBitmap(result); } }
if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); }请记住,假设在主线程里声明了一个handler。这个handler所Post 的 Runnable(Thread)、以及处理的message都是在当前的主线程里。非子线程。