我将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);
}
}
最佳答案
您需要设置属性而不是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的空对象,您需要传递类的名称,当您单击通知时将启动活动,如在警报设置时间中那样,
Intent myIntent = new Intent(fridgeDetails.this, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
fridgeDetails.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
现在只需在意图中传递活动名称,例如假设您要启动家庭活动和活动名称(例如“ homeactivity”)
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,new Intent(context,HomeActivity.class), 0);