警报不会发生火灾,有时根本不发射

时间:2016-06-30 22:08:07

标签: android alarmmanager

我试图在用户选择的时间发出警报。然而,我注意到警报在选定的一分钟内永远不会消失。即如果用户从TimePicker对话框中选择8:30,则警报通常会在8:30分钟内某处触发,有时会在一分钟后触发。此外,有时警报根本不会发射。目标是更新当前警报,以便始终不创建新警报。我是Android闹钟服务的新手,所以我希望有人可以看看。这是一些代码:

在我的onCreate

中调用此方法
private void initAlarmService() {
    calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());

    ComponentName receiver = new ComponentName(getContext(), AlarmReceiver.class);
    pm = getContext().getPackageManager();
    pm.setComponentEnabledSetting(receiver,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);


    alarmIntent = new Intent(getContext(), AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(getContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    manager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
}

选择时间时会调用此方法:

private void setTime(int hour, int minute) {
    if(sharedPreferences.contains("ALARM_PREF")){
        manager.cancel(pendingIntent);
    }

    sharedPreferences.edit().putString("ALARM_PREF", ""+hour + ":" +minute).apply();

    //set date object time to picker value
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, minute);
    calendar.set(Calendar.SECOND, 0);

    //interval = 1000 * 60 * 60 * 24
    manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTime().getTime(), interval, pendingIntent);

    //This just outputs to a textview
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
    time = sdf.format(calendar.getTime().getTime());
    alarmText.setText(time);
    calendar.setTimeInMillis(System.currentTimeMillis());
}

1 个答案:

答案 0 :(得分:1)

如果您在API 19+设备上看到了您所描述的行为,那么AlarmManager documentation中的这条说明可能会解释原因:

  

注意:从API 19(KITKAT)开始,警报传递是不准确的:操作系统   将移动警报以最小化唤醒和电池使用。那里   是支持需要严格交付的应用程序的新API   担保;请参阅setWindow(int,long,long,PendingIntent)和   setExact(int,long,PendingIntent)。应用程序   targetSdkVersion早于API 19将继续看到   以前的行为,其中所有警报都在何时传递   请求。

在您的情况下,您需要切换到使用setExact()。遗憾的是,没有setExactRepeating(),所以当您收到第一次警报时,您必须再次手动设置它。

相关问题