• Android长时间定时任务实现


    在服务的onStartCommand方法里面使用AlarmManager 定时唤醒发送广播,在广播里面启动服务

      每次执行startService方法启动服务都会执行onStartCommand

    1、服务定时唤醒  60秒发一次广播

    public class MediaService extends Service {
        public MediaService() {
    
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            // TODO: Return the communication channel to the service.
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
        /*每次调用startService启动该服务都会执行*/
        public int onStartCommand(Intent intent, int flags, int startId) {
    
            Log.d("TAG", "启动服务:" + new Date().toString());
    
            AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
    
            long triggerTime = SystemClock.elapsedRealtime() + 60000;
            Intent i = new Intent(this, AlarmReceiver.class);
            PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
            manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, pi);
            return super.onStartCommand(intent, flags, startId);
        }
    
    }

    采用AlarmManger实现长期精确的定时任务

    AlarmManager的常用方法有三个:

    • set(int type,long startTime,PendingIntent pi);//一次性
    • setExact(int type, long triggerAtMillis, PendingIntent operation)//一次性的精确版
    • setRepeating(int type,long startTime,long intervalTime,PendingIntent 
      pi);//精确重复
    • setInexactRepeating(int type,long startTime,long 
      intervalTime,PendingIntent pi);//非精确,降低功耗

    type表示闹钟类型,startTime表示闹钟第一次执行时间,long intervalTime表示间隔时间,PendingIntent表示闹钟响应动作


    对以上各个参数的详细解释 
    闹钟的类型:

    • AlarmManager.ELAPSED_REALTIME:休眠后停止,相对开机时间
    • AlarmManager.ELAPSED_REALTIME_WAKEUP:休眠状态仍可唤醒cpu继续工作,相对开机时间
    • AlarmManager.RTC:同1,但时间相对于绝对时间
    • AlarmManager.RTC_WAKEUP:同2,但时间相对于绝对时间
    • AlarmManager.POWER_OFF_WAKEUP:关机后依旧可用,相对于绝对时间

    绝对时间:1970 年 1月 1 日 0 点

    startTime: 
    闹钟的第一次执行时间,以毫秒为单位,一般使用当前时间。

    • SystemClock.elapsedRealtime():系统开机至今所经历时间的毫秒数
    • System.currentTimeMillis():1970 年 1 月 1 日 0 点至今所经历时间的毫秒数

    intervalTime:执行时间间隔。

    PendingIntent : 
    PendingIntent用于描述Intent及其最终的行为.,这里用于获取定时任务的执行动作。 
    详细参考译文:PendingIntent

    2、接收到广播调用startService启动服务

      

    public class AlarmReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent i = new Intent(context, MediaService.class);
            context.startService(i);
        }
    }

    运行结果:

                           

  • 相关阅读:
    HelloWorld入门程序
    再写博客
    iOS--小结系列一
    iOS--ARC
    ios--block
    iOS--protocol
    iOS--内存管理
    指针基本概念
    ZooKeeper系列之十:ZooKeeper的一致性保证及Leader选举
    ZooKeeper系列之九:ZooKeeper API简介及编程
  • 原文地址:https://www.cnblogs.com/tangchun/p/9675349.html
Copyright © 2020-2023  润新知