在android 中我們一般用 Handler 做主線程 和 子線程 之間的通信 。
現在有了一種更為簡潔的寫法,就是 Activity 里面的 runOnUiThread( Runnable )方法。
利用Activity.runOnUiThread(Runnable)把更新ui的代碼創建在Runnable中,然后在需要更新ui時,把這個Runnable對象傳給Activity.runOnUiThread(Runnable)。
Runnable對像就能在ui程序中被調用。如果當前線程是UI線程,那么行動是立即執行。如果當前線程不是UI線程,操作是發布到事件隊列的UI線程。
package com.app;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//創建一個線程
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(MainActivity.this, "hah", 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();
}
}
