我需要在用户选择通知开始的日期和时间时发出通知。为此,我将日期,时间和注释存储在数据库中。现在,我想使用数据库中的数据启动警报,并使用每个警报的ID作为PendingIntent
的唯一ID。
这是我从数据库中获取数据的方式
db=new events_database(events_main.this);
c=db.queryData("select * from events_list ORDER BY event_ID ASC");
if(c != null && c.moveToNext())
{
int id=c.getInt(0);
String type=c.getString(1);
String date=c.getString(2);
String time=c.getString(3);
String note=c.getString(4);
String[] newDate=date.split("/");
int year=Integer.valueOf(newDate[0]);
int month=Integer.valueOf(newDate[1]);
int day=Integer.valueOf(newDate[2]);
String[] newTime=time.split(":");
int hour=Integer.valueOf(newTime[0]);
int min=Integer.valueOf(newTime[1]);
Alarms(id,year,month,day,hour,min,type,note);
}
获取后我将数据传递给Alarms方法
public void Alarms(int id, int year, int month, int day, int hour, int minute, String type, String note) {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.YEAR,year);
calendar1.set(Calendar.MONTH,month);
calendar1.set(Calendar.DAY_OF_MONTH,day);
calendar1.set(Calendar.HOUR_OF_DAY, hour);
calendar1.set(Calendar.MINUTE, minute);
calendar1.set(Calendar.MILLISECOND, 0);
if (calendar1.before(Calendar.getInstance())) {
calendar1.add(Calendar.DATE, 1);
}
Intent intent = new Intent(events_main.this, events_receiver.class);
intent.putExtra("type",type);
intent.putExtra("note",note);
intent.putExtra("id", id);
PendingIntent dog1 = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
final AlarmManager alarm1 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm1.setExact(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), dog1);
Toast.makeText(events_main.this, "alarms",Toast.LENGTH_SHORT).show();
}
然后在接收器
public class events_receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int id= Integer.valueOf(intent.getStringExtra("id"));
String note=intent.getStringExtra("note");
String type=intent.getStringExtra("type");
NotificationManager notificationManager2=(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
Intent dog_intent2=new Intent(context,HomeActivity.class);
dog_intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent dog_pending2=PendingIntent.getActivity(context, id,dog_intent2, PendingIntent.FLAG_ONE_SHOT);;
NotificationCompat.Builder builder2=new NotificationCompat.Builder(context)
.setContentIntent(dog_pending2)
.setSmallIcon(R.drawable.ic_action_prof_breed_icon)
.setSound(Uri.parse("android.resource://" +context.getPackageName()+ "/" + R.raw.dog))
.setContentTitle("Pet Guide 101")
.setContentText(type)
.setContentText(note)
.setVibrate(new long[] { 1000, 1000})
.setAutoCancel(true);
notificationManager2.notify(id,builder2.build());
}
}
但由于某种原因,警报不会被触发。当我测试代码时,我确实从数据库中获取数据,但警报仍未执行。如果你能查一查,请告诉我,如果我做错了,特别是将唯一身份证传递给接收者。