加入收藏 | 设为首页 | 会员中心 | 我要投稿 常州站长网 (https://www.0519zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

Android长时间定时任务达成

发布时间:2021-11-12 15:38:54 所属栏目:教程 来源:互联网
导读:在服务的onStartCommand方法里面使用AlarmManager 定时唤醒发送广播,在广播里面启动服务 每次执行startService方法启动服务都会执行onStartCommand 1、服务定时唤醒 60秒发一次广播 public class MediaService extends Service { public MediaService() { }

在服务的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启动该服务都会执行*
 
采用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及其最终的行为.,这里用于获取定时任务的执行动作。
 
2、接收到广播调用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);
    }
 
}
 
 
 
public class AlarmReceiver extends BroadcastReceiver {
 
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, MediaService.class);
        context.startService(i);
    }
}

(编辑:常州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读