每次打开应用程序时,AlarmManager都会关闭

时间:2016-10-29 04:54:03

标签: android alarmmanager

我正在运行此代码,在创建方法

上的MainActivity中设置一个Alarm Manager
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点设置闹钟,闹钟工作正常,直到它被解雇一次。一旦闹钟在上午10点完成,它每次打开应用程序时都会一直停止。

有些人可以解释我是否需要更改代码?

编辑:

我使用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);

}

1 个答案:

答案 0 :(得分:0)

启动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);
    }