美文网首页
子线程转化到Ui主线程

子线程转化到Ui主线程

作者: 晓晓桑 | 来源:发表于2019-03-15 13:19 被阅读0次

    通过private Handler handler = new Handler(Looper.getMainLooper());

    在子线程中调用:

      handler.post(new Runnable() {
    
                       @Override
                       public void run() {
    
                       }
                   });
    

    具体例子:

    public class BitmapDispatcger extends Thread {
    
        private BlockingQueue<BitmapRequest> requests;
    
        private Handler handler = new Handler(Looper.getMainLooper());
    
        public BitmapDispatcger(BlockingQueue<BitmapRequest> requests) {
            this.requests = requests;
        }
    
        @Override
        public void run() {
            //子线程
            while (!isInterrupted()) {
                //取出任务,如果队列中没有任务就会一直阻塞在这里,不往下进行
                try {
                    BitmapRequest request = requests.take();
                    //先展示loading
    
                    showLoadingImage(request);
    
    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
    
        private void showLoadingImage(BitmapRequest request) {
            if (request.getLoadingResId() > 0) {
                final ImageView imageView = request.getImageView();
                final int redId = request.getLoadingResId();
                if (imageView != null) {
                    //子线程调用主线程
                    handler.post(new Runnable() {
    
                        @Override
                        public void run() {
                            //更新ui
                            imageView.setImageResource(redId);
                        }
                    });
    
                }
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:子线程转化到Ui主线程

          本文链接:https://www.haomeiwen.com/subject/uvulmqtx.html