报警触发与给定时间无关

时间:2016-03-31 17:56:20

标签: android alarmmanager alarm

我在活动的final int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { layout.setBackgroundDrawable( getResources().getDrawable(R.drawable.yourimg)); } else { layout.setBackground(R.drawable.yourimg); } 上使用以下函数setAlarm()为每天晚上10点注册闹钟(提醒)

但是每次活动打开时,都会调用接收方onCreate()(在任何时候打开活动)。

AlarmReceiver

清单文件是

private static AlarmManager alarmMgr;
private static PendingIntent alarmIntent;


 public static void setAlarm(Context context) {
    alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR, 10);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(calendar.SECOND, 0);
    calendar.set(calendar.MILLISECOND, 0);
    calendar.set(Calendar.AM_PM, Calendar.PM);
    millisecond =  calendar.getTimeInMillis();


    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, millisecond, AlarmManager.INTERVAL_DAY, alarmIntent);
}

1 个答案:

答案 0 :(得分:-1)

您花了不少行为日历变量设置适当的时间。但是当你在alarmMgr上调用setInExactRepeating方法时,你会告诉它在几毫秒内启动它。

alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, millisecond, AlarmManager.INTERVAL_DAY, alarmIntent); 

相反,您希望通过指定转换为毫秒的日历变量来告诉setInExactRepeating方法在适当的时间触发:

  alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);