通过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);
}
});
}
}
}
}
网友评论