android Activity runOnUiThread() 方法使用,runonuithread

來源:互聯網
上載者:User

android Activity runOnUiThread() 方法使用,runonuithread
在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();        }    }

  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.