一、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);
}
}
- 方法
doInBackground()在工作线程中自动执行; -
onPreExecute(),onPostExecute(), 和onProgressUpdate()在UI线程中执行。 -
doInBackground()方法返回值被送往onPostExecute()。 你可以在任何时间在doInBackground()方法中调用publishProgress()方法,以在UI线程中执行onProgressUpdate()方法。- 你可以在任何线程,在任何时间取消异步任务。
三、工作线程上发送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();
}
本文介绍了Android中三种实现线程间通信的方法:使用Handler进行消息调度与处理;利用AsyncTask简化耗时任务与UI更新;以及通过Activity或View组件直接在UI线程执行任务。
1923

被折叠的 条评论
为什么被折叠?



