我收到通知,提醒用户服药。当我添加服用药物的新时间时,例如,在晚上9点和晚上9点01分,只有最后一个通知处于活动状态。 这是我的代码:
AddTime.java :(部分)
Cursor cursor2 = sqdb.rawQuery("SELECT Name FROM Medicine WHERE _id = " + mId, null);
while(cursor2.moveToNext()) {
med = cursor2.getString(cursor2.getColumnIndex("Name"));
} //med - Name of medicine
String sql = "SELECT _id FROM Time WHERE mId = "+mId+" AND Year = "+year+" AND Month = '"+_month+"' AND Day = "+_numDay+" AND Week = '"+_week+"' AND Hour = "+_hour+" AND Minute = "+_min+" AND AMORPM = '"+_ampm+"' AND CalendarDate = '"+calDate+"'";
Cursor cursor = sqdb.rawQuery(sql, null);
int tId = 0;
while(cursor.moveToNext()) {
tId = cursor.getInt(cursor.getColumnIndex("_id"));
} //Unique id for notification
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent _intent = new Intent(this, TimeAlarm.class);
_intent.putExtra("TIMEID", tId);
_intent.putExtra("MEDNAME", med);
Calendar c = Calendar.getInstance();
int Years = c.get(Calendar.YEAR);
int Months = c.get(Calendar.MONTH);
int Days = c.get(Calendar.DAY_OF_MONTH);
int Hours = c.get(Calendar.HOUR_OF_DAY);
int Minutes = c.get(Calendar.MINUTE);
GregorianCalendar curDate = new GregorianCalendar(Years, Months, Days, Hours, Minutes, 0);
GregorianCalendar nextDate = new GregorianCalendar(year, Month, _numDay, _hour, _min, 0);
long millisecDiff = nextDate.getTimeInMillis() - curDate.getTimeInMillis();
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, _intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millisecDiff, pIntent);
TimeAlarm.java
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
int timeid = intent.getExtras().getInt("TIMEID");
String medname = intent.getExtras().getString("MEDNAME");
CharSequence from = "Title";
CharSequence message = "Message";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.icon,
"Text", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(timeid, notif);
}
}
答案 0 :(得分:3)
PendingIntent.getBroadcast中称为请求代码的第二个参数需要对每个新警报都是唯一的,否则它将覆盖。它在文档中说这个requestCode当前没有使用。文档错了。
你有
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, _intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millisecDiff, pIntent);
你想要的是
PendingIntent pIntent = PendingIntent.getBroadcast(this, SomeUniqueIndex, _intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millisecDiff, pIntent);