How to set an alarm to be scheduled at an exact time after all the newest restrictions on Android?

后端 未结 6 556
半阙折子戏
半阙折子戏 2020-12-13 13:49

Note: I tried various solutions that are written about here on StackOverflow (example here). Please do not close this without checking if your solution from what you\'ve fou

6条回答
  •  执笔经年
    2020-12-13 14:27

    1. Make sure the intent you broadcast is explicit and has the Intent.FLAG_RECEIVER_FOREGROUND flag.

    https://developer.android.com/about/versions/oreo/background#broadcasts

    Intent intent = new Intent(context, Receiver.class);
    intent.setAction(action);
    ...
    intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    
    PendingIntent operation = PendingIntent.getBroadcast(context, 0, intent, flags);
    
    1. Use setExactAndAllowWhileIdle() when targeting API 23+.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, operation);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, operation);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, time, operation);
    }
    
    1. Start your alarm as a Foreground Service:

    https://developer.android.com/about/versions/oreo/background#migration

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(intent);
    } else {
        context.startService(intent);
    }
    
    1. And don't forget permissions:
    
    

提交回复
热议问题