我在Android中有一个前台服务设置.我想更新通知文本.我正在创建服务,如下所示.
如何更新在此前台服务中设置的通知文本?更新通知的最佳做法是什么?任何示例代码将不胜感激.
public class NotificationService extends Service {
private static final int ONGOING_NOTIFICATION = 1;
private Notification notification;
@Override
public void onCreate() {
super.onCreate();
this.notification = new Notification(R.drawable.statusbar, getText(R.string.app_name), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, AbList.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
this.notification.setLatestEventInfo(this, getText(R.string.app_name), "Update This Text", pendingIntent);
startForeground(ONGOING_NOTIFICATION, this.notification);
}
Run Code Online (Sandbox Code Playgroud)
我正在我的主要活动中创建服务,如下所示:
// Start Notification Service
Intent serviceIntent = new Intent(this, NotificationService.class);
startService(serviceIntent);
Run Code Online (Sandbox Code Playgroud) 我一直试图使用以下方法删除服务设置的持久通知:
startForeground(1337, notification);
Run Code Online (Sandbox Code Playgroud)
我用来取消它的代码:
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.cancel(1337); // cancel existing service notification, doesn't take effect
nManager.cancelAll(); //surpluous, but also doesn't take effect
Run Code Online (Sandbox Code Playgroud)
为了澄清我为什么这样做:服务以默认的持久性通知开始.当我的应用运行时,它需要将此通知替换为另一个.notify()然而,使用现有的通知工作非常完美,我还需要它来显示新通知的滚动条文本.这就是为什么我决定删除现有的通知(使用上面的代码),创建一个新的,然后我startForeground()再次调用并将新的通知传递给它,所以我的服务仍然存在.
android foreground android-service notificationmanager android-notifications