Caused by: android.os.NetworkOnMainThreadException
产生的原因。官方解释:
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
上面的意思是,从SDK3.0開始,google不再同意网络请求(HTTP、Socket)等相关操作直接在主线程中。事实上本来就不应该这样做,直接在UI线程进行网络操作。会堵塞UI、用户体验不好。
也就是说。在SDK3.0以下的版本号,还能够继续在主线程里这样做,在3.0以上,就不行了。所以。在以下的代码中。使用Thread、Runnable、Handler这三个类:
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); } }
第三种、直接忽视,强制使用(强烈不推荐,可是改动简单)
在MainActivity文件的setContentView(R.layout.activity_main)以下加上例如以下代码
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都是在当前的主线程里。非子线程。