我正在开发一款允许用户设置时间的应用。在每一次我想设置通知。但是,通知仅在应用程序运行时才有效。
这是我的alarmReceiver
Bundle bu = intent.getExtras();
int Code = 0;
if (bu != null) {
Code = bu.getInt("TIME_CODE");
}
Intent MyServiceIntent = new Intent(context, ServiceNotification.class);
MyServiceIntent.putExtra("TIME_CODE", Code);
context.startService(MyServiceIntent);
这是我的服务
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Bundle bu = intent.getExtras();
int TimeCode = 0;
if (bu != null) {
TimeCode = bu.getInt("TIME_CODE");
}
NotificationManager mManager;
mManager = (NotificationManager) this.getApplicationContext()
.getSystemService(
this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),
MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,
"Nuovo messaggio da cura alert", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
this.getApplicationContext(), 0, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(),
"Le notifiche funzionano", "It is working....",
pendingNotificationIntent);
notification.vibrate = new long[] { 100L, 100L, 200L, 500L };
mManager.notify(TimeCode, notification);
try {
Uri notification_uri = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
notification_uri);
r.play();
} catch (Exception e) {
Log.e("ECCEZIONE SERVIZIO", e.getMessage());
}
}
这是MainActivity中的一种方法,每次在DB中添加PendingIntent。
for (int i = 0; i < TimeItem.size(); ++i) {
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("TIME_CODE", i);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, i,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
AddCurrentPendingId(i, "Test");
String time = TimeItem.get(i);
int Position = time.indexOf(":");
int hour = Integer.parseInt(time.substring(0, Position));
int min = Integer.parseInt(time.substring(Position + 1));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, min);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
am.set(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);
}
当我为通知设置时间并关闭应用时,未收到通知。当我打开我的应用程序时,通知到达。 谢谢
P.S。:我不想使用GCM服务。