28
28
import static android .app .Notification .VISIBILITY_PUBLIC ;
29
29
30
30
import java .lang .Integer ;
31
+ import java .lang .reflect .Method ;
31
32
import java .util .Calendar ;
32
33
import java .util .Random ;
33
34
import java .util .Set ;
@@ -50,6 +51,8 @@ public class UnityNotificationManager extends BroadcastReceiver {
50
51
private HashSet <Integer > mVisibleNotifications ;
51
52
private ConcurrentHashMap <Integer , Notification .Builder > mScheduledNotifications ;
52
53
private NotificationCallback mNotificationCallback ;
54
+ private int mExactSchedulingSetting = -1 ;
55
+ private Method mCanScheduleExactAlarms ;
53
56
54
57
static final String TAG_UNITY = "UnityNotifications" ;
55
58
@@ -513,15 +516,28 @@ synchronized List<Notification.Builder> loadSavedNotifications() {
513
516
return intent_data_list ;
514
517
}
515
518
516
- private static boolean canScheduleExactAlarms (AlarmManager alarmManager ) {
517
- // The commented-out if below is the correct one and should replace the one further down
518
- // However it requires compile SDK 31 to compile, cutting edge and not shipped with Unity at the moment of writing this
519
- // It means exact timing for notifications is not supported on Android 12+ out of the box
520
- //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
521
- //return alarmManager.canScheduleExactAlarms();
522
- if (Build .VERSION .SDK_INT >= 31 )
519
+ private boolean canScheduleExactAlarms (AlarmManager alarmManager ) {
520
+ // exact scheduling supported since Android 6
521
+ if (Build .VERSION .SDK_INT < Build .VERSION_CODES .M )
523
522
return false ;
524
- return Build .VERSION .SDK_INT >= Build .VERSION_CODES .M ;
523
+ if (mExactSchedulingSetting < 0 )
524
+ mExactSchedulingSetting = mContext .getApplicationInfo ().metaData .getInt ("com.unity.androidnotifications.exact_scheduling" , 1 );
525
+ if (mExactSchedulingSetting == 0 )
526
+ return false ;
527
+ if (Build .VERSION .SDK_INT < 31 )
528
+ return true ;
529
+
530
+ try {
531
+ if (mCanScheduleExactAlarms == null )
532
+ mCanScheduleExactAlarms = AlarmManager .class .getMethod ("canScheduleExactAlarms" );
533
+ return (boolean )mCanScheduleExactAlarms .invoke (alarmManager );
534
+ } catch (NoSuchMethodException ex ) {
535
+ Log .e (TAG_UNITY , "No AlarmManager.canScheduleExactAlarms() on Android 31+ device, should not happen" , ex );
536
+ return false ;
537
+ } catch (Exception ex ) {
538
+ Log .e (TAG_UNITY , "AlarmManager.canScheduleExactAlarms() threw" , ex );
539
+ return false ;
540
+ }
525
541
}
526
542
527
543
// Call AlarmManager to set the broadcast intent with fire time and interval.
0 commit comments