我很好奇安卓系统中的NotificationManager.notify
和startForeground
有什么不同。
发布于 2019-12-22 23:46:37
使用NotificationManager.notify
,您可以发布任意多的通知更新,包括通过Noticiation.Builder.setProgress
对进度条进行调整,这样您就只向用户显示一个通知,这就是startForeground
所要求的通知。
当您想要通过startForeground()更新通知集时,只需构建一个新的通知,然后使用NotificationManager来通知它。
关键点是使用相同的通知id。
我没有测试重复调用startForeground()
来更新通知的场景,但我认为使用NotificationManager.notify
会更好。
更新通知不会将服务从前台状态移除(这只能通过调用stopForground
来完成。
下面是一个示例:
private static final int notif_id=1;
@Override
public void onCreate (){
this.startForeground();
}
private void startForeground() {
startForeground(notif_id, getMyActivityNotification(""));
}
private Notification getMyActivityNotification(String text){
// The PendingIntent to launch our activity if the user selects
// this notification
CharSequence title = getText(R.string.title_activity);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MyActivity.class), 0);
return new Notification.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher_b3)
.setContentIntent(contentIntent).getNotification();
}
/**
* this is the method that can be called to update the Notification
*/
private void updateNotification() {
String text = "Some text that will update the notification";
Notification notification = getMyActivityNotification(text);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notif_id, notification);
}
您可以找到有关NotificationManager.notify
here的更多示例和说明
为了了解更多关于startForeground
的知识,我还建议您参考这个page
可以在here中找到startForeground
的用法
https://stackoverflow.com/questions/59445044
复制相似问题