如何在 Android 中更新前台服务的通知文本? [英] How do I update the notification text for a foreground service in Android?

查看:45
本文介绍了如何在 Android 中更新前台服务的通知文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Android 中设置了前台服务.我想更新通知文本.我正在创建如下所示的服务.

I have a foreground service setup in Android. I would like to update the notification text. I am creating the service as shown below.

如何更新在此前台服务中设置的通知文本?更新通知的最佳做法是什么?任何示例代码将不胜感激.

How can I update the notification text that is setup within this foreground service? What is the best practise for updating the notification? Any sample code would be appreciated.

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);

    }

我正在我的主要活动中创建服务,如下所示:

I am creating the service in my main activity as shown below:

    // Start Notification Service
    Intent serviceIntent = new Intent(this, NotificationService.class);
    startService(serviceIntent);

推荐答案

我认为再次使用相同的唯一 ID 和 Notification 调用 startForeground()新信息会起作用,但我还没有尝试过这种情况.

I would think that calling startForeground() again with the same unique ID and a Notification with the new information would work, though I have not tried this scenario.

更新:根据评论,您应该使用 NotifcationManager 更新通知,您的服务将继续保持在前台模式.看看下面的答案.

Update: Based on the comments, you should use NotifcationManager to update the notification and your service continues to stay in the foreground mode. Take a look at the answer below.

这篇关于如何在 Android 中更新前台服务的通知文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆