当我在下面的代码中将AlarmManager设置为Im做错时,立即触发警报

时间:2019-03-14 10:42:05

标签: android alarmmanager repeatingalarm

阿拉曼经理班

我使用alaramManager.setRepeating在某个时间间隔后每次重复

public class AlarmService {

Long time;
AlarmManager alarmManager;
PendingIntent pendingIntent;
Context context;

public AlarmService(Context context){
    this.context = context;
}

public AlarmService(Context context, Long time) {
    this.time = time * 60000;
    Log.e("time",this.time+" AlaramService");
    this.context = context;
}

public void setAlarm() {
    alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, ReminderBroadcastReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), time, pendingIntent);

    Log.e("time",time+" setAlarm");

}

public void cancelAlarm() {
    Intent intent = new Intent(context, ReminderBroadcastReceiver.class);
    alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent,0);
    alarmManager.cancel(sender);
}

}

将AlarmManager设置为在特定时间后拨打电话

Long time = Long.valueOf(settingsData.getInterval().split(" ")[0]);
                AlarmService alarmService = new AlarmService(Setting.this,time);
                alarmService.cancelAlarm();
                alarmService.setAlarm();

ReminderBroadcastService进行通知

public class ReminderBroadcastReceiver extends BroadcastReceiver {


@Override
public void onReceive(final Context context, Intent intent) {
    Toast.makeText(context, "Received", Toast.LENGTH_SHORT).show();

    NotificationService notificationService = new NotificationService(context);
    notificationService.callNotification();
}

1 个答案:

答案 0 :(得分:2)

您正在传递System.currentTimeMillis()

alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), time, pendingIntent);

设置闹钟功能中的闹钟时间。这就是为什么它立即触发。传递未来的时间,而不是像现在一样在第二天设置闹钟

alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+86400000L, time, pendingIntent);