I would like to set a repeating alarm, in android 8 or 9 it works. The question is how to set it to work it in 12 working parallel with android 8?
This is in the main activity, I set a startAlarm, and there is the missing part how to set the alarm in the case of sdk >= 31. When I start android to test it sends a notification at the beginning of the application but it do not send notification later.
MainActivity.java:
private void startAlarm(long when) { AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { if (alarmManager.canScheduleExactAlarms()) { Log.e(TAG, "startAlarm: canScheduleExactAlarms"); } } Intent intent = new Intent(this, AlarmReceiver.class); PendingIntent pendingIntent; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 1, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); } else { pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 1, intent, 0); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ alarmManager.setExactAndAllowWhileIdle( AlarmManager.RTC_WAKEUP, when*1000, pendingIntent ); } else { alarmManager.setExact( AlarmManager.RTC_WAKEUP, when*1000, pendingIntent ); } } I set AlarmReceiver to send notification. AlarmReceiver:
public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NotificationHelper notificationHelper = new NotificationHelper(context); NotificationCompat.Builder nb = notificationHelper.getChannelNotification(); notificationHelper.getManager().notify(1, nb.build()); long timeInSec = System.currentTimeMillis() / 1000; Settings.setLastNotificationSent(timeInSec, context); } } I set the permission in the manifest. AndroidManifest:
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/> <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/> <receiver android:name=".receiver.AlarmReceiver" android:exported="true" android:enabled="true"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> Reset to default