How to repeat an alarm in android 6.0

I use setExactAndAllowWhileIdle()

to set an alarm. But it only works once. How do I set a recurring alarm at 1 day intervals? Before API level 23 method setInexactRepeating

works fine.

+3


source to share


2 answers


Reboot the alarm when you broadcast a receiver event.

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);
    }
}

      

+2


source


AlarmManager.setRepeating does not work as expected on different Android versions.

Try setExact . It won't repeat itself, but you can achieve repeating functions like 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 repeatCount and a variable (based on preference) and increment it in your AlarmReceiver and schedule the alarm again by calculating nextAlarmTime with repeatCount * System.currentTimeMillis ();

0


source







All Articles