我目前正在使用广播接收器启动服务,该接收器在设备启动后 60 秒触发。此广播接收器触发警报,以便我的服务每 60 秒运行一次。代码如下:
public class ScheduleReceiver extends BroadcastReceiver {
// Restart service every 60 seconds
private static final long REPEAT_TIME = 1000 * 60;
@Override
public void onReceive(Context context, Intent intent) {
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, StartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// Start 60 seconds after boot completed
cal.add(Calendar.SECOND, 60);
// Fetch every 60 seconds
// InexactRepeating allows Android to optimize the energy consumption
service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), REPEAT_TIME, pending);
}
}
以上启动服务如下:
public class StartServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, PhotoService.class);
context.startService(service);
}
}
我想以某种方式对其进行修改,以便我的服务在手机屏幕打开时每 60 秒运行一次,而在关闭时每 20 分钟运行一次。
做这个的最好方式是什么 ?当屏幕关闭/打开时,我可以动态修改警报吗?
谢谢你的帮助,
问候,
菲多