我将AlarmManager
和NotificationManager
与BroadcastReceiver
一起使用。
当我设置具有特定日期的闹钟时,它是第一次工作。但是,当我修改日期并单击确认按钮时,警报可以在任何日期运行
立即。我想设置过期日期后的警报间隔时间和固定时间。
它有什么问题?我现在不明白。
confirmButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
//set alarm with expiration date
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
setOneTimeAlarm();
Toast.makeText(fridgeDetails.this, "Alarm automatic set",
Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
finish();
}
public void setOneTimeAlarm() {
c.set(Calendar.HOUR_OF_DAY, 14);
c.set(Calendar.MINUTE, 49);
c.set(expiredYear, expiredMonth, expiredDay);
Intent myIntent = new Intent(fridgeDetails.this, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
fridgeDetails.this, 0, myIntent, PendingIntent.FLAG_ONE_SHOT);
am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
});
AlarmService.java
public class AlarmService extends BroadcastReceiver{
NotificationManager nm;
@Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
CharSequence from = "Check your fridge";
CharSequence message = "It's time to eat!";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.ic_launcher,
"Keep Fridge", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.defaults |= Notification.DEFAULT_SOUND;
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);
}
}
答案 0 :(得分:2)
您需要设置属性而不是FLAG_ONE_SHOT。这适用于单次报警事件,不适用于重复。试试这个
PendingIntent pendingIntent = PendingIntent.getBroadcast(
fridgeDetails.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
查看有关here
的详细信息修改强>
正如您使用PendingIntent
进行通知一样PendingIntent contentIntent = PendingIntent.getActivity(context, 0,new Intent(), 0);
在这里你传递了Intent的空对象,你需要传递类名,当你点击通知哪个Activity会像你在警报设置时那样启动
Intent myIntent = new Intent(fridgeDetails.this, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
fridgeDetails.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
现在只需在意图中传递Acitivity名称,就像想要启动您的家庭活动和活动名称一样,如“homeactivity”
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,new Intent(context,HomeActivity.class), 0);