所以我遇到了这个问题,每当我设置一个警报时它就会发送通知,即使时间不匹配。我正在使用这个类来设置闹钟并取消闹钟。
package com.example.home.quoteapp.notification;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import com.example.home.quoteapp.readers.NotificationsReader;
import java.util.Calendar;
public class AlarmActivater {
private final Context context;
public AlarmActivater(Context context) {
this.context = context;
}
public void setAlarm() {
cancelAlarm();
if (!NotificationsReader.getNotifications().isEmpty()) {
SharedPreferences prefs = context.getSharedPreferences("time", Context.MODE_PRIVATE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, prefs.getInt("hour", 1));
calendar.set(Calendar.MINUTE, prefs.getInt("minute", 01));
calendar.set(Calendar.SECOND, 0);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
private boolean isActive() {
return (PendingIntent.getBroadcast(context, 0,
new Intent(context, AlarmReceiver.class),
PendingIntent.FLAG_NO_CREATE) != null);
}
private void cancelAlarm() {
if (!NotificationsReader.getNotifications().isEmpty() && isActive()) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, 0, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}
}
}
我在启动应用程序时调用setAlarm方法,并在时间选择器中更改时间。 prefs.getInt ...东西是正确的我已经测试过了。