Android UI线程与工作线程之间通信


一、Handler处理线程间通信
       Handler主要有两个用途:
    1) schedule messages and runnables to be executed as some point in the future
             消息的分发和处理,安排 messages 和 runnables在未来某个时刻被执行;
    2)enqueue an action to be performed on a different thread than your own.
         队列action在其他线程上被执行;
    
     UI主线程处理来自工作线程的消息:UI 主线程上新建一个Handler hander= new Handler(), 然后在工作线程上执行handler.sendMessage , handler.post 操作。这样在工作线程上启动的动作或发送的消息就会在UI主线程上被处理执行。
   反之,也一样,工作线程创建的hander也可以处理来自UI主线程发送来的message消息




二、AsyncTask异步任务
       这可能是最好的办法,简单!继承AsyncTask,简化了与UI线程交互的工作线程任务的执行。它在工作线程执行耗时操作,而在UI线程发布执行结果。

 
public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    /** The system calls this to perform work in a worker thread and
      * delivers it the parameters given to AsyncTask.execute() */
    protected Bitmap doInBackground(String... urls) {
        return loadImageFromNetwork(urls[0]);
    }
    
    /** The system calls this to perform work in the UI thread and delivers
      * the result from doInBackground() */
    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}


    


三、工作线程上发送Runnable到UI主线程上执行,还有如下几种方式:

调用 View.post(Runnable) 方法的代码实例如下:

public void onClick(View v) {
    new Thread(new Runnable() {
        public void run() {
            final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
            mImageView.post(new Runnable() {
                public void run() {
                    mImageView.setImageBitmap(bitmap);
                }
            });
        }
    }).start();
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值