标签:networkonmainthreade asynctask http协议 android网络消息 android.os.networkon
最近在实现一个Android下的数据采集的SDK,收集用户使用数据使用HTTP发送到云平台,进行数据分析。但在发送数据时报如下错误:产生的原因,官方解释:
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); } }
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都是在当前的主线程里,非子线程。
版权声明:本文为博主原创文章,未经博主允许不得转载。
Android 异常 android.os.NetworkOnMainThreadException
标签:networkonmainthreade asynctask http协议 android网络消息 android.os.networkon
原文地址:http://blog.csdn.net/a78270528/article/details/47131683