如何更新通知文本在Android的前景的服务?前景、文本、通知、Android

2023-09-04 08:35:18 作者:伤丶点到为止

我有一个前台服务安装在Android系统。我想更新通知文本。我创建的服务,如下图所示。

我如何更新,它是此前台服务中设置的通知文本?什么是更新通知的最佳实践?任何样品code将AP preciated。

 公共类NotificationService延伸服务{

    私有静态最终诠释ONGOING_NOTIFICATION = 1;

    私人的通知的通知;

    @覆盖
    公共无效的onCreate(){
        super.onCreate();

        this.notification =新的通知(R.drawable.statusbar,gettext的(R.string.app_name),System.currentTimeMillis的());
        意图notificationIntent =新的意图(这一点,AbList.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(此,0,notificationIntent,0);
        this.notification.setLatestEventInfo(这一点,gettext的(R.string.app_name),更新此文字,pendingIntent);

        startForeground(ONGOING_NOTIFICATION,this.notification);

    }
 

我创造了我的主要活动服务,如下所示:

  //开始通知服务
    意图serviceIntent =新的意图(这一点,NotificationService.class);
    startService(serviceIntent);
 

解决方案

我会认为调用 startForeground()再以相同的唯一ID和的通知用新信息会的工作,虽然我还没有尝试过这种情况。

Android 13早期开发版曝光 无休止广告或成过去

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

解决方案

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.