如何在android 6.0中重复闹钟

时间:2017-04-17 11:20:20

标签: android alarmmanager android-6.0-marshmallow

我正在使用setExactAndAllowWhileIdle()设置闹钟。但它只能工作一次。如何设置间隔1天的重复警报? 在API Level 23 setInexactRepeating方法正常工作之前。

2 个答案:

答案 0 :(得分:2)

广播接收器事件正在执行时重新充电。

我的意思是,

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

答案 1 :(得分:0)

AlarmManager.setRepeating 在不同的Android版本上无法正常运行。

尝试 setExact 。它不会重复,但您可以实现如下所述的重复功能:

更新了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);
    }
}

我们维持一个repeatCount&变量(基于偏好)并在AlarmReceiver&中增加它。通过使用repeatCount * System.currentTimeMillis();

计算nextAlarmTime来再次计划警报