How to repeat alarm in android 6.0

你。 提交于 2019-12-12 13:23:57

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/43450427/how-to-repeat-alarm-in-android-6-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!