前言
Android 中我们通常用handler 做主线程和子线程之间的通信。现在有了一个更简洁方便的方式,就是利用Activity 里面的 runOnUiThread(Runnable )方法。
利用Activity.runOnUiThread(Runnable)把更新ui的代码创建在Runnable中,然后在需要更新ui时,把这个Runnable对象传给Activity.runOnUiThread(Runnable)。
Runnable对像就能在ui程序中被调用。如果当前线程是UI线程,那么行动是立即执行。如果当前线程不是UI线程,操作是发布到事件队列的UI线程。
使用
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_svg);
//创建一个线程
new Thread(new Runnable() {
@Override
public void run() {
//延迟两秒
try {
Thread.sleep( 2000 );
} catch (InterruptedException e) {
e.printStackTrace();
}
//主线程
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(SvgActivity.this, "ui线程", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
Activity的runOnUiThread(Runnable)的方法
/**
* Runs the specified action on the UI thread. If the current thread is the UI
* thread, then the action is executed immediately. If the current thread is
* not the UI thread, the action is posted to the event queue of the UI thread.
*
* @param action the action to run on the UI thread
*/
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}