[英]AlarmManager going off everytime i open the app
我正在運行此代碼以在創建方法的MainActivity中設置警報管理器
public void notificationCheck() {
calendar.set(Calendar.HOUR_OF_DAY, Preferences.getMorningHour(getApplicationContext()));
calendar.set(Calendar.MINUTE, Preferences.getMorningMinute(getApplicationContext()));
calendar.set(Calendar.SECOND, 0);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, AlarmReceiver.class), 0);
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
// Sets an alarm - note this alarm will be lost if the phone is turned off and on again
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
am.setAndAllowWhileIdle(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} else {
am.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
因此,應將鬧鈴設置為每天上午10:00。鬧鈴工作良好,直到觸發一次。 鬧鍾在10:00 AM完成后,每次我打開該應用程序時,它都會持續響起。
可以請我解釋一下是否需要更改代碼嗎?
編輯:
我正在使用sharedPreferences設置日歷實例的時間
首選項:
public static int getMorningHour(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(MORNING_HOUR, 9);
}
public static void setMorningHour(Context context, Integer morningHour) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(MORNING_HOUR, morningHour).apply();
}
public static int getMorningMinute(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(MORNING_MINUTE, 0);
}
public static void setMorningMinute(Context context, Integer morningMinute) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(MORNING_MINUTE, morningMinute).apply();
}
...,然后使用TimePicker對話框在我的應用程序設置中設置首選項
@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {
Preferences.setMorningHour(getApplicationContext(), hourOfDay);
Preferences.setMorningMinute(getApplicationContext(), minute);
}
當啟動Activity時,您需要檢查警報是否已經存在。 如果生活不打擾。 參見下面的代碼。
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
boolean isWorking = (PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, PendingIntent.FLAG_NO_CREATE) != null);
if (isWorking) {Log.d("alarm", "is working");} else {Log.d("alarm", "is not working");}
if(!isWorking) {
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
int timeNotif = 5 * 60 * 1000;//time in ms, 7*24*60*60*1000 for 1 week
Log.d("Notif", "Notification every (ms): " + timeNotif);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), timeNotif, pendingIntent);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.