这有效:需要带有 NotificationCompat.Builder 的 IntentService 提供与 NotificationManager.notify() .setContentIntent(pendingIntent) 一起使用的通知。发送通知时,通知出现在通知中并且是持久的(在用户单击它之前一直保持活动状态,此时它会启动 .setContentIntent 中指定的活动)。好的!什么不起作用:我希望该服务像电话服务一样长期存在,因此似乎建议使用 startForeground()。但是,当我包含它时,关联的通知确实会出现在托盘中,但它不是 PERSISTENT 并且在 IntentService 结束时消失(与上面不同)。(关联的通知也使用 .setContentIntent 并启动另一个 Activity。) 有什么想法吗?服务在检测到某个(罕见的)“事件”之前不会死亡,这一点至关重要。在用户点击它之前通知保持活跃也很重要!
这是简化的代码(后一种情况):谢谢!
public class SService extends IntentService {
public SService() {
super("SService");
}
@Override
protected void onHandleIntent(Intent sIntent) {
//Notification construction:
Notification notif;
Context context = this;
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent bIntent = new Intent(context, BarNotifActivity.class);
PendingIntent pbIntent = PendingIntent.getActivity(context, 0, bIntent,0);
Notification barNotif;
NotificationCompat.Builder bBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.bar_title))
.setContentText(getString(R.string.bar_text))
//.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pbIntent);
barNotif = bBuilder.build();
this.startForeground(1, barNotif);
long[] vibration = {0, 300, 1000, 300, 1000, 300, 1000, 300, 1000};
Intent mIntent = new Intent(context, NotifReceiverActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, mIntent,0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.alert_text))
.setContentText(getString(R.string.alert_text))
.setTicker("**Notification Arrived!**")
.setVibrate(vibration)
//.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pIntent);
notif = mBuilder.build();
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notif.flags |= Notification.FLAG_INSISTENT;
try {
Thread.sleep(7000); //Pause 7 sec.
} catch (InterruptedException e) {
e.printStackTrace();
}
mNotificationManager.notify(1, notif);
}
}