Handler实现异步操作, 注意:不能异步更新UI

xiaoxiao2021-03-01  13

//异步加载Ad数据 HandlerThread handlerThared = new HandlerThread("new Thread"); handlerThared.start();//开启一个新的线程,脱离UI(主)线程 final Handler handler = new Handler(handlerThared.getLooper()){ /** * 覆盖Handler中的handlleMessage方法 * 异步 */ @Override public void handleMessage(Message msg) { // Result result = (Result) msg.obj; // @SuppressWarnings("unchecked") // List<Product> productList = (List<Product>) result.getResultList(); // int index = 0; // for(Product p : productList){ // View ad = thiz.createAdView(p, index); // //为每张AD图片添加TouchEvent // ad.setOnTouchListener(thiz); // thiz.adFlipper.addView(ad, index); // index++; // } } }; handler.postDelayed(new Runnable() { @Override public void run() {// //查询推荐商品 Result result = XmlCrawler.queryTjProduct(1, 10); if(result != null){ Message msg = handler.obtainMessage(); msg.obj = result; //利用handler通过msg传递参数 handler.sendMessage(msg); } } },1000 * 0);

解析:

HandlerThread handlerThared = new HandlerThread("new Thread"); handlerThared.start();//开启一个新的线程,脱离UI(主)线程 final Handler handler = new Handler(handlerThared.getLooper()){

1:如果想让handler异步, 必须使用HandlerThread 新开启一个线程

2:handleMessage 中可以做一些异步操作,但是不能异步更新UI

否则将会报异常:Only the original thread that created a view hierarchy can touch its views.

创建只有创建它的线程才可以touch它、 也就是 UIThread

因为创建handler时候指定的参数 handlerThared.getLooper() 注定了, handler 与主线程 是两个不同的线程

3:如果参数指定为 handlerThared.getLooper().getMainLooper() 则不能实现异步功能, 仍然是同一个线程

以上描述, 是我通过代码得出的结论 , 不一样正确

看到这篇文章的博友们。 仅供参考

如果想实现真正意义上的异步更新UI , 还是用AsyncTask吧 这个方便

转载请注明原文地址: https://www.6miu.com/read-3850009.html

最新回复(0)