Android基础之创建Alarm定时任务 | 带源码

简介

  • 一般有两种实现方式,使用Java API提供的Timer类,一种是使用Android的Alarm机制
  • Timer有个明显的短板,不太适用于需要长期在后台运行的定时任务

Alarm机制

  • MainActivity
//启动服务
Intent intent = new Intent(this,LongRunningService.class);
startService(intent);
  • LongRunningService
public class LongRunningService extends Service {
    public LongRunningService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                //...
            }
        }).start();
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        //一分钟毫秒数
        int anMinute = 60 * 1000;

        //设定一个任务在10秒钟之后执行
        //使用SystemClock.elapsedRealtime()可以获取到系统开机至今所经历的时间的毫秒数
        //使用System.currentTimeMillis()可以获取到从1970/1/1/0点至今所经历的毫秒数
        long triggerAtTime = SystemClock.elapsedRealtime() + anMinute;

        Intent i = new Intent(this,LongRunningService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this,0,i,0);

        //第一个参数是整型参数,有4种值可以选择,第二个参数是定时任务触发的时间,第三个参数是能够执行服务或广播的PendingIntent
        //ELAPSED_REALTIME表示让定时任务的触发时间从系统开机开始算起,但不会唤醒CPU
        //ELAPSED_REALTIME_WAKEUP同上,但会唤醒CPU
        //RTC表示让定时任务触发从1970/1/1/0点算起,但不会唤醒CPU
        //RTC_WAKEUP同上,但会唤醒CPU
        //在Android4.4之后,set启动变得不准确,用以延长电池使用时间,若想要准时,则setExact()
        //该服务会在6min后再次执行
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendingIntent);

        return super.onStartCommand(intent, flags, startId);
    }
}
  • Manifest
<service
            android:name=".LongRunningService"
            android:enabled="true"
            android:exported="true"></service>
  • 下载地址

DoSomeAndroidTest/AlarmActivity at main · qricis/DoSomeAndroidTest · GitHub

若有收获,就点个赞吧

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值