サブスレッドとプライマリスレッドの通信の他の方法の概要


前の2つのブログでは、サブスレッドとプライマリスレッド間の通信について個別に説明しています.Thread-Handler-MessageとAsyncTaskです.非同期通信を実現するには、次の3つの方法があります.
1つ目:runOnUiThread(Runnable action)この方法はActivityで定義されており、公式ドキュメントの説明はRuns the specified action on 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.すなわち、この方法はメインスレッドで実行する.現在のスレッドがプライマリスレッドでない場合はpostメソッドでプライマリスレッドキューに渡されて実行され、すでにプライマリスレッドにある場合はすぐに実行されます.
public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

コード例:たとえばサブスレッドsleep 2 sを開いて、あるインタフェースに入ります.ここではThread-Handler-Messageで処理せずにrunOnUIThreadを直接使用できます.
new Thread() {
                public void run() {
                    SystemClock.sleep(2000);
                    //  
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            enterActivity();
                        }
                    });
                };
            }.start();

2つ目:Viewメソッドのpost(Runnable action):戻り値がtrueの場合は、actionがメッセージキューに正常に追加されたことを示し、戻り値がfalseの場合はメッセージキューを処理するlooperが終了します.
3つ目:ViewメソッドのpostDelayMillis(Runnable action,long delayMillis).戻り値はbooleanです.また、actionもメッセージキューに追加されますが、一定時間遅延した後に実行が開始されます.戻り値がtrueの場合、looperが終了した可能性があるため、送信されたこのメッセージは破棄されるとは限らないことに注意してください.