美文网首页程序员Android知识
Android将任务抛到UI线程的几种方法

Android将任务抛到UI线程的几种方法

作者: Mr云台 | 来源:发表于2016-10-25 15:03 被阅读0次

有的时候,我们希望能将任务抛回到UI线程去做,比如修改界面。如果当前没有处在UI线程,那应该怎么把任务抛到UI线程去呢?

以下是Android系统提供的3个将任务抛回UI线程的方法

  • Activity.runOnUiThread(Runnable)
  • View.post(Runnable)
  • View.postDelayed(Runnable, long)

例如,在某一个线程中,通过View.post()方法将任务抛回UI线程

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();
}

如果你不能判定,当前是不是UI线程,可以用如下两个方法:

方法一:使用Looper类判断,如果相等则是UI线程

Looper.myLooper() == Looper.getMainLooper()

方法二:通过查看Thread类的当前线程

Thread.currentThread() == Looper.getMainLooper().getThread()

相关文章

网友评论

    本文标题:Android将任务抛到UI线程的几种方法

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