Ankur Khandelwal
Ankur Khandelwal

Reputation: 269

How to repeat alarm in android 6.0

I am using the setExactAndAllowWhileIdle() to set the alarm. But it works for only one time. How will I set the repeating alarm with interval 1 day? Before the API Level 23 setInexactRepeating method working fine.

Upvotes: 3

Views: 1915

Answers (2)

Vyacheslav
Vyacheslav

Reputation: 27211

Recharge your alarm when you broadcast receiver event is executing.

I mean,

public class CustomBroadcast extends WakefulBroadcastReceiver {
    public static final String somekey = "somekey.somekey.somekey";
    @Override
    public void onReceive(Context ctx, Intent intent) {
        // TODO Auto-generated method stub
        ComponentName comp = new ComponentName(ctx.getPackageName(),
        YourSevice.class.getName());
        YourCustomClass.yourrechargefunction();
        startWakefulService(ctx, intent.setComponent(comp));
    }
}

public class YourCustomClass {
    private final static int somekey_int = anynumber;
    public static void yourrechargefunction() {
        Intent intent = new Intent(CustomBroadcast.somekey):
        PendingIntent pi = wPendingIntent.getBroadcast(ctx,somekey_int, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nexttime, pi);
    }
}

Upvotes: 2

PEHLAJ
PEHLAJ

Reputation: 10126

AlarmManager.setRepeating doesn't work properly on different android versions.

Try setExact. It won't repeat but you can achieve repeating functionality as mentioned below:

Updated AlarmReceiver.java

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        context.sendBroadcast(new Intent("SERVICE_TEMPORARY_STOPPED"));

        long repeatCount = PreferenceManager.getDefaultSharedPreferences(context).getLong("REPEAT_COUNT", 0L);

        repeatCount++;

        PreferenceManager.getDefaultSharedPreferences (context).edit().putLong("REPEAT_COUNT", repeatCount).apply()

        AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent alarmIntent = new Intent(this, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
        manager.setExact(AlarmManager.RTC_WAKEUP, (repeatCount *System.currentTimeMillis()),pendingIntent);
    }
}

Here we maintain a repeatCount & variable (preference based) and increment it in your AlarmReceiver & schedule alarm again by calculating nextAlarmTime using repeatCount * System.currentTimeMillis();

Upvotes: 0

Related Questions