Android中延时执行的几种方法

文章目录

  • 1、Handler.postDelay
  • 2、Handler.sendEmptyMessage
  • 3、Thread.sleep
  • 4、Timer
  • 5、AlarmManager
  • 全部代码

1、Handler.postDelay

最简单快捷

 /**
     * 建议使用优先级:1
     */
    private void useHandler1(){
        handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                showUI();
            }
        },6000);
    }

2、Handler.sendEmptyMessage

稍微简单快捷

 /**
     * 建议使用优先级:2
     */
    private void userHandler2(){
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1000:
                        showUI();
                        break;
                    default:
                        break;
                }
            }
        };
        handler.sendEmptyMessageDelayed(1000,9000);
    }

3、Thread.sleep

性能不好,以上三种底层执行代码基本一致

 /**
     * 建议使用优先级:4
     */
    private void useThread(){
        Thread thread = new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(12000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showUI();
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
    }

4、Timer

简小的定时任务

/**
     * 建议使用优先级:3
     * 简单应用场合,但不适用于那些需要长期在后台运行的定时任务
     */
    private void useTimer(){
        stopTimer();

        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showUI();
                    }
                });
            }
        };

        timer.schedule(timerTask,3000);

    }

    private void stopTimer(){
        if(timerTask != null){
            timerTask.cancel();
            timerTask = null;
        }

        if(timer != null){
            timer.cancel();
            timer = null;
        }
    }

5、AlarmManager

使用起来比较麻烦,但很精准,不太会用这货

    private void userAlarmManager(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,17);
        calendar.set(Calendar.MINUTE,11);
        Intent intent = new Intent("com.xmliu.mytimerdemo.BlockReceiver");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),10*1000,pendingIntent);
    }

全部代码

package com.xmliu.mytimerdemo;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private Timer timer;
    private TimerTask timerTask;

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

//        useTimer();
//        useHandler1();
//       userHandler2();
//        useThread();
            userAlarmManager();

    }

    private void showUI(){
        TextView textView = findViewById(R.id.text);
        textView.setText("timer示例");
    }

    /**
     * 在17:11之后,每分钟的执行一次
     */
    private void userAlarmManager(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,17);
        calendar.set(Calendar.MINUTE,11);
        Intent intent = new Intent("com.xmliu.mytimerdemo.BlockReceiver");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),10*1000,pendingIntent);
    }

    /**
     * 建议使用优先级:4
     */
    private void useThread(){
        Thread thread = new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(12000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showUI();
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
    }

    /**
     * 建议使用优先级:2
     */
    private void userHandler2(){
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1000:
                        showUI();
                        break;
                    default:
                        break;
                }
            }
        };
        handler.sendEmptyMessageDelayed(1000,9000);
    }

    /**
     * 建议使用优先级:1
     */
    private void useHandler1(){
        handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                showUI();
            }
        },6000);
    }

    /**
     * 建议使用优先级:3
     * 简单应用场合,但不适用于那些需要长期在后台运行的定时任务
     */
    private void useTimer(){
        stopTimer();

        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showUI();
                    }
                });
            }
        };

        timer.schedule(timerTask,3000);

    }

    private void stopTimer(){
        if(timerTask != null){
            timerTask.cancel();
            timerTask = null;
        }

        if(timer != null){
            timer.cancel();
            timer = null;
        }
    }
}

package com.xmliu.mytimerdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * Date: 2019/6/17 17:08
 * Email: [email protected]
 * Author: diyan
 * Description: TODO
 */
public class BlockReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("xunming","-----BlockReceiver-------");
    }
}

你可能感兴趣的:(Android,Java)