我正在尝试创建一个发送多个预定警报的应用,通过根据特定时间(不是时间间隔,但是时间)显示一天。
我已经实现了在每个意图中触发通知的AlarmReceiver.class
,但问题是我没有收到任何通知。我试图在Log
方法中显示onReceiver()
,但邮件尚未显示,因此尚未发出警报。
这是setAlarm()
函数,用于设置实例化Calendar
的小时和时间:
public void setAlarm()
{
SharedPreferences pref = this.getSharedPreferences("NOTIFICATION_CODE", Context.MODE_PRIVATE);
String mName = NameFld.getText().toString();
String mFormat = FormatSpn.getSelectedItem().toString();
Date date = new Date();
Calendar calendar = Calendar.getInstance();
Calendar current = Calendar.getInstance();
current.setTime(date);
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, picker_hour);
calendar.set(Calendar.MINUTE, picker_minute);
calendar.set(Calendar.SECOND, 0);
if(current.before(calendar))
{
calendar.add(Calendar.DATE, 1);
}
medName = mName;
medFormat = mFormat;
int _reqCode = pref.getInt("reqCode", -1);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(this, _reqCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE);
aManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);
editor = pref.edit();
editor.putInt("reqCode", ++_reqCode);
editor.commit();
}
要设置时间,我实施了TimePickerDialog
,我将小时和分钟值存储到picker_hour
和picker_minute
。
由于我必须发送多个闹钟,因此我使用SharedPreferences
存储reqCode
,然后在每次发送时识别PendingIntent
。
这是AlarmReceiver.class
,它为每个收到的意图发出通知。每个通知都通过reqCode
:
PendingIntent
标识
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String[] data = AddMedicine.getData();
SharedPreferences pref = context.getSharedPreferences("NOTIFICATION_CODE", context.MODE_PRIVATE);
int reqCode = pref.getInt("reqCode", -1);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true);
builder.setTicker("It's pill time!");
builder.setContentTitle(data[0]);
builder.setContentText(data[1]);
builder.setSmallIcon(R.drawable.ic_launcher);
Notification notification = builder.build();
NotificationManager nManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
nManager.notify(reqCode, notification);
Log.i("NOTIFICATION", "FIRED!");
}}
P.S。每次用户创建警报时都会设置警报,以便通过reqCode
安排它们。
那么,有谁知道如何根据时间发送多个警报?提前谢谢!