Why isn't my alarm going off? (android)

2019-08-28 20:23发布

问题:

My alarm does not go off at the specific time or at all (I have tried setting it to one minute of current time). I have made sure that setAlarm() is going off because the log Log.d("asas", "adasd"); goes off. I do not know what is wrong, if you see how I can fix this please let me know. Thanks

public void setAlarm(){
    AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, DrawOverAppsService.class);
    PendingIntent alarmIntent = PendingIntent.getActivity(MainActivity.this, 123, intent, 0);
    if(sp.getBoolean("startChecked",false) == true) {
        Log.d("asas", "adasd");
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(java.util.Calendar.HOUR_OF_DAY, 19);
        alarmMgr.setRepeating(AlarmManager.RTC,
                calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, alarmIntent);
    }
    if(sp.getBoolean("startChecked",false) == false) {
        Log.d("asdasd","asdasdasd");
        alarmMgr.cancel(alarmIntent);
    }
}

回答1:

Changed PendingIntent alarmIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0); to PendingIntent alarmIntent = PendingIntent.getService(MainActivity.this, 0, intent, 0);