我已经尝试了StackOverflow上提供的大部分解决方案,并且谷歌关于Marshmallow OS的AlarmManager
。但我没有得到解决方案。
代码:
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(context, UpdateTables.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar alarmStartTime = Calendar.getInstance();
//midnight
alarmStartTime.set(Calendar.HOUR_OF_DAY, 0);
alarmStartTime.set(Calendar.MINUTE, 1);
alarmStartTime.set(Calendar.SECOND, 0);
if (Calendar.getInstance().getTimeInMillis() > alarmStartTime.getTimeInMillis()) {
Log.i("Current time ", Constants.getDate(Calendar.getInstance().getTimeInMillis(),"yyyy-MM-dd HH:mm:ss.SSS"));
alarmStartTime.add(Calendar.DATE, 1);
}
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmStartTime.getTimeInMills(), pendingIntent);
广播接收器
public class UpdateTables extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
当我关闭应用程序时,设置的警报将从计划的警报列表中删除:
./adb shell dumpsys alarm
所以我创建了从最近的应用再次调用AlarmManager
onTaskRemoved()
的服务:
public class myService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
setTheTimeToUpdateTables(getApplicationContext());
super.onTaskRemoved(rootIntent);
}
}
尝试解决方案:
WakefulBroadcastReceiver
代替BroadCastReciever
。