第一种:调用主线程mHandler的post(Runnable r)方法。
该方法中的Runnable对象会被会加入到mHandler所在线程的Message消息队列中,假设mHandler在主线程中则Runnable 对象中的run方法将会在主线程中运行。所以能够达到更新UI线程的目的。
提示:
Handler另一个与之类似的方法postDelayed(Runnable r, long delayMillis),该方法会在进行指定delayMillis时间的延迟之后将runnable对象加入到mHandler所在的线程中。
例如以下方法:
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
showToastByRunnable(MainActivity.this, "", 3000);
}
}.start();
/**
* 在非UI线程中使用Toast
* @param context 上下文
* @param text 用以显示的消息内容
* @param duration 消息显示的时间
* */
private void showToastByRunnable(final Context context, final CharSequence text, final int duration) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, text, duration).show();
}
});
}
另外一种:通过handler向主线程发送消息的机制该更新UI