RGS
RGS

Reputation: 4253

Repeat alarm every 20 minutes in android

I'd like to repeat an alarm every 20 minutes. So I tried:

manifest:

<receiver android:name=".AlarmReceiver" />

AlarmReceiver.class

    public class AlarmReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
                Intent intent2 = new Intent(context, MainActivity.class);
                showNotification(context, "text", "text", intent2);

                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Ringtone r = RingtoneManager.getRingtone(context, notification);
                r.play();
        }

@TargetApi(Build.VERSION_CODES.N)
    public void showNotification(Context context, String title, String body, Intent intent) { 

... 

} 

   }

and in my main activity:

AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        Calendar time = Calendar.getInstance();
        time.setTimeInMillis(System.currentTimeMillis());
        time.add(Calendar.SECOND, 1200);
        alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pendingIntent);

It is working only the first time. I'd like to keep it repeating even when the app is not opening, any ideas?

Upvotes: 1

Views: 3362

Answers (3)

Sajith
Sajith

Reputation: 771

Try below for Repeating alarm on every 20 minutes interval

alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),1000 * 60 * 20, pendingIntent);

Upvotes: 1

Larry Schiefer
Larry Schiefer

Reputation: 15775

Starting with KitKat (API 19), alarms are all inexact, meaning the system will batch alarms around similar times together. If you need exact timing, there are different APIs to call. Further complicating things, starting with Marshmallow, Android introduced the concept of Doze, which further restricts the when/how things can wake up the device. You can still use exact alarms, but need to use the API which allows it during idle (Doze) time: setAndAllowWhileIdle(). Bear in mind that when your alarm fires, you could be in a Doze window and your app will be restricted on what kinds of operations it can perform.

Upvotes: 3

Related Questions