安卓/android的延時/定時方式

本文出自 “阿敏其人” 簡書博客,轉(zhuǎn)載或引用請注明出處。

一、先上總結(jié)

** 1、第一種 TimerTask+Timer 延時器 **

// ===========  第一種  TimerTask+Timer  延時器
                /**
                 * Timer類可以用來計劃執(zhí)行循環(huán)執(zhí)行任務(wù),但是如果手就休眠了,任務(wù)就不執(zhí)行了,
                 * 除非去喚醒CPU,但是頻繁的喚醒會導(dǎo)致手機消耗大量的電量,縮短待機時間。
                 */


                TimerTask task = new TimerTask(){
                    public void run(){
                        // 這句日志可以打印
                        Log.d("TTT", "我是延時日志");
                        // 下面這個改變背景的無法打印,因為子線程不能直接更改UI
                        //mTv3Second.setBackgroundColor(Color.parseColor("#00FF00"));
                        // 更改的包UI的操作我們這里放到handler里面就可以成功執(zhí)行
                        handler.sendEmptyMessage(1);
                    }
                };
                Timer timer = new Timer();
                timer.schedule(task, 3000);
                // ===========  第一種  TimerTask+Timer  延時器

.
.
** 2、第二種 線程**

                //  ===============  第二種  線程
                new Thread(new Runnable(){
                    public void run(){
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Log.d("TTT","線程延遲了3秒");
                        handler.sendEmptyMessage(2); //告訴主線程執(zhí)行任務(wù)
                    }
                }).start();
                //  ===============  第二種  線程

.
.
3、第三種 handler postDelayed

                //==============  第三種  handler postDelayed
                new Handler().postDelayed(new Runnable(){
                    public void run() {
                        mTvHandlerPostDelayed.setBackgroundColor(Color.parseColor("#0000ff"));
                    }
                }, 3000);
                // =============  第三種  handler postDelayed

.
.
** 4、第四種、AlarmManager,適用于定時比較長遠的時間,例如鬧鈴 **

5、第五種 android5.0 JobScheduler

.
.

二、簡單demo圖

當(dāng)前機器較差,沒辦法準確顯示對應(yīng)的延時時間,所以這圖看個大概就好


GIF.gif

.
.

附上代碼

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context="com.amqr.delayedtimetest.MainActivity">

    <TextView
        android:id="@+id/mTv3Second"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Timer+Task3秒后出Log和彈吐司"
        android:padding="10dp"
        android:background="#66ff0000"
        android:layout_margin="10dp"
        android:layout_centerHorizontal="true"
        />

    <TextView
        android:id="@+id/mTvNewThread"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="newThread 出 Log"
        android:padding="10dp"
        android:background="#66ff0000"
        android:layout_margin="10dp"
        android:layout_centerHorizontal="true"
        />


    <TextView
        android:id="@+id/mTvHandlerPostDelayed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HandlerPostDelayed 背景變藍"
        android:padding="10dp"
        android:background="#66ff0000"
        android:layout_margin="10dp"
        android:layout_centerHorizontal="true"
        />
</LinearLayout>

.
.
.
MainActivity

public class MainActivity extends Activity implements View.OnClickListener {

    private TextView mTv3Second;
    private TextView mTvNewThread;
    private TextView mTvHandlerPostDelayed;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    mTv3Second.setBackgroundColor(Color.parseColor("#000000"));
                 break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTv3Second = (TextView) findViewById(R.id.mTv3Second);
        mTv3Second.setOnClickListener(this);

        mTvNewThread = (TextView) findViewById(R.id.mTvNewThread);
        mTvNewThread.setOnClickListener(this);

        mTvHandlerPostDelayed = (TextView) findViewById(R.id.mTvHandlerPostDelayed);
        mTvHandlerPostDelayed.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.mTv3Second:
                // ===========  第一種  TimerTask+Timer  延時器
                /**
                 * Timer類可以用來計劃執(zhí)行循環(huán)執(zhí)行任務(wù),但是如果手就休眠了,任務(wù)就不執(zhí)行了,
                 * 除非去喚醒CPU,但是頻繁的喚醒會導(dǎo)致手機消耗大量的電量,縮短待機時間。
                 */


                TimerTask task = new TimerTask(){
                    public void run(){
                        // 這句日志可以打印
                        Log.d("TTT", "我是延時日志");
                        // 下面這個改變背景的無法打印,因為子線程不能直接更改UI
                        //mTv3Second.setBackgroundColor(Color.parseColor("#00FF00"));
                        // 更改的包UI的操作我們這里放到handler里面就可以成功執(zhí)行
                        handler.sendEmptyMessage(1);
                    }
                };
                Timer timer = new Timer();
                timer.schedule(task, 3000);
                // ===========  第一種  TimerTask+Timer  延時器
                break;

            case R.id.mTvNewThread:

/*                try {
                    Thread.sleep(3000); // 這種方式不是很好
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.d("TTT","線程延遲了3秒");*/

                // 像上面的那種寫法寫成下面這樣會好一些一般來說


                //  ===============  第二種  線程
                new Thread(new Runnable(){
                    public void run(){
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Log.d("TTT","線程延遲了3秒");
                        handler.sendEmptyMessage(2); //告訴主線程執(zhí)行任務(wù)
                    }
                }).start();
                //  ===============  第二種  線程
                break;

            case R.id.mTvHandlerPostDelayed:
                //==============  第三種  handler postDelayed
                new Handler().postDelayed(new Runnable(){
                    public void run() {
                        mTvHandlerPostDelayed.setBackgroundColor(Color.parseColor("#000000"));
                    }
                }, 3000);
                // =============  第三種  handler postDelayed
                break;


            // 第4種  AlarmManager,適用于定時比較長遠的時間,例如鬧鈴

            // 第5種  Android 5.0開始有了一個新的實現(xiàn)方案:JobScheduler
        }
    }
}

本篇完。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容