文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Android常用定时器的实现方式

2024-04-02 19:55

关注

前言

android开发中,常用定时器实现方式有以下几种:

1、Handler与sleep

2、Handler与postDelayed

3、Handler与timer

注:Handler的主要作用就是用来处理接收到的信息;用Handler消息传递机制是为了多个线程并发更新UI的同时,保证线程安全;

一、Handler 与 sleep

public class HandlerAndSleep {

    // 1、定义一个Handler类,用于处理接受到的Message.
    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            // do something eg.
            Log.d("HandlerAndSleep", "HandlerAndSleep");
        }
    };

    // 2、新建一个实现Runnable接口的线程类
    class MyThread implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(10000);
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public HandlerAndSleep() {
        //3、在需要启动线程的地方加入下面语句,启动线程后,线程每10s发送一次消息
        new Thread(new MyThread()).start();
    }
}

结果打印如下:

2022-05-30 11:30:42.320 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
2022-05-30 11:30:52.324 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
2022-05-30 11:31:02.326 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
2022-05-30 11:31:12.335 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
2022-05-30 11:31:22.338 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
2022-05-30 11:31:32.339 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
2022-05-30 11:31:42.347 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep

二、Handler 与 postDelayed

public class HandleAndPostDelayed {

    Handler handler = new Handler(){
        @Override
        public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
            Log.d("HandleAndPostDelayed", "HandleAndPostDelayed");
            return super.sendMessageAtTime(msg, uptimeMillis);
        }
    };

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // do something
            handler.postDelayed(this, 2000);
        }
    };

    HandleAndPostDelayed() {
    	// 开启定时器
        handler.postDelayed(runnable, 2000);
		// 停止定时器
//        handler.removeCallbacks(runnable);
    }
}

结果打印如下:

2022-05-30 14:32:41.533 24351-24351/com.yh.study D/HandleAndPostDelayed: HandleAndPostDelayed
2022-05-30 14:32:43.534 24351-24351/com.yh.study D/HandleAndPostDelayed: HandleAndPostDelayed
2022-05-30 14:32:45.537 24351-24351/com.yh.study D/HandleAndPostDelayed: HandleAndPostDelayed
2022-05-30 14:32:47.539 24351-24351/com.yh.study D/HandleAndPostDelayed: HandleAndPostDelayed
2022-05-30 14:32:49.546 24351-24351/com.yh.study D/HandleAndPostDelayed: HandleAndPostDelayed
2022-05-30 14:32:51.550 24351-24351/com.yh.study D/HandleAndPostDelayed: HandleAndPostDelayed

三、Handler 与 timer

public class HandlerAndTimer {

    private final Timer timer = new Timer();
    private TimerTask task;
    Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            // do something
            Log.d("HandlerAndTimer", "HandlerAndTimer");
            super.handleMessage(msg);
        }
    };

    public HandlerAndTimer() {
        task = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        };
        //启动定时器 参数对应为 TimerTask 延迟时间 间隔时间
        timer.schedule(task, 2000, 2000);
    }
}

结果打印如下:

2022-05-30 14:43:40.922 25052-25052/com.yh.study D/HandlerAndTimer: HandlerAndTimer
2022-05-30 14:43:42.924 25052-25052/com.yh.study D/HandlerAndTimer: HandlerAndTimer
2022-05-30 14:43:44.925 25052-25052/com.yh.study D/HandlerAndTimer: HandlerAndTimer
2022-05-30 14:43:46.926 25052-25052/com.yh.study D/HandlerAndTimer: HandlerAndTimer
2022-05-30 14:43:48.927 25052-25052/com.yh.study D/HandlerAndTimer: HandlerAndTimer

在Android上常用的定时器有两种,一种是Java.util.Timer,一种就是系统的AlarmService。

public class MainActivity extends AppCompatActivity {

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            tCount++;
            timerTV.setText(tCount+"");
            super.handleMessage(msg);
        }
    };

    Timer timer = new Timer();
    int tCount = 0;
    int sCount = 0;
    TextView timerTV;
    TextView serviceTV;

    String ALARM_RECEIVER_ACTION = "com.yh.study.AlarmReceiver";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timerTV = findViewById(R.id.timer_tv);
        serviceTV = findViewById(R.id.service_tv);

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }
        }, 2*1000, 5*1000);

        AlarmReceiver alarmReceiver = new AlarmReceiver(new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                sCount++;
                serviceTV.setText(sCount+"");
                super.handleMessage(msg);
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ALARM_RECEIVER_ACTION);
        registerReceiver(alarmReceiver, intentFilter);

        Intent intent = new Intent(ALARM_RECEIVER_ACTION);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
//
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(),
                pendingIntent);
    }
}
public class AlarmReceiver extends BroadcastReceiver {
    Handler handler;
    AlarmReceiver(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("onReceive", "onReceive");
        handler.sendEmptyMessage(0);
        Intent serviceIntent = new Intent(context, MyService.class);
        context.startService(serviceIntent);
    }
}
public class MyService extends IntentService {
    public MyService() {
        super("MyService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent alarmIntent = new Intent("com.yh.study.AlarmReceiver");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5*1000,
                pendingIntent);
    }
}

以下结论来源其他博主

(小子在验证过程中,连接usb情况正常,拔掉usb后与结论不符,可能是小子哪里写的有问题)

在Timer中,当连接USB线进行调试时,会发现一切工作正常,每5秒更新一次界面,即使是按下电源键,仍然会5秒触发一次。 当拔掉USB线,按下电源键关闭屏幕后,过一段时间再打开,发现定时器明显没有继续计数,停留在了关闭电源键时的数字。
在AlarmService中,拔掉USB线,按下电源键,过一点时间再次打开屏幕,发现定时器一直在计数。

测试机型小米8,上timer,下AlarmService

补充:采用Handler与timer及TimerTask结合的方法

1. 定义定时器、定时器任务及Handler句柄

private final Timer timer = new Timer();
private TimerTask task;
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        // 要做的事情
        super.handleMessage(msg);
    }
};

2. 初始化计时器任务

task = new TimerTask() {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        Message message = new Message();
        message.what = 1;
        handler.sendMessage(message);
    }
};

3. 启动定时器

timer.schedule(task, 2000, 2000);

总结 

到此这篇关于Android常用定时器实现的文章就介绍到这了,更多相关Android常用定时器内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯