繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM