Как обновить текст уведомления для службы переднего плана в Android?



у меня есть настройка службы переднего плана в 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);

}


Я создаю сервис в моей основной деятельности, как показано ниже:



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

4 ответов:

Я думаю, что вызов startForeground() снова с тем же уникальным идентификатором и Notification С новой информацией будет работать, хотя я не пробовал этот сценарий.

если вы хотите обновить уведомление, установленное startForeground (), просто создайте новое уведомление, а затем используйте NotificationManager для его уведомления.

ключевым моментом является использование одного и того же идентификатора уведомления.

Я не тестировал сценарий повторного вызова startForeground() для обновления уведомления, но я думаю, что с помощью NotificationManager.уведомлять было бы лучше.

обновление уведомления не приведет к удалению службы из состояния переднего плана (это можно сделать только путем вызова 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);
}

The документация государства

чтобы настроить уведомление, чтобы его можно было обновить, выполните его с помощью идентификатор уведомления по телефону NotificationManager.notify(). Обновлять это уведомление после того, как вы его выпустили, обновите или создадите NotificationCompat.Builder объект, построить Notification объект это и проблема Notification С таким же ID, который вы использовали ранее. Если предыдущее уведомление по-прежнему виден, система обновляет его из содержимого Notification "объект". Если предыдущий уведомление отклонено, создается новое уведомление вместо.

здесь код к вашим услугам. Создайте новое уведомление, но попросите диспетчер уведомлений уведомить тот же идентификатор уведомления, который вы использовали в startForeground.

Notification notify = createNotification();
final NotificationManager notificationManager = (NotificationManager) getApplicationContext()
    .getSystemService(getApplicationContext().NOTIFICATION_SERVICE);

notificationManager.notify(ONGOING_NOTIFICATION, notify);

для полных кодов образца, вы можете проверить здесь:

https://github.com/plateaukao/AutoScreenOnOff/blob/master/src/com/danielkao/autoscreenonoff/SensorMonitorService.java

улучшение ответа Luca Manzo в android 8.0+ при обновлении уведомления он будет звучать и отображаться как Heads-up.
чтобы предотвратить это, вам нужно добавить setOnlyAlertOnce(true)

код:

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){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
        ((NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(
        NotificationChannel("timer_notification","Timer Notification",NotificationManager.IMPORTANCE_HIGH))
}

        // The PendingIntent to launch our activity if the user selects
        // this notification
        PendingIntent contentIntent=PendingIntent.getActivity(this,
        0,new Intent(this,MyActivity.class),0);

        return new NotificationCompat.Builder(this,"my_channel_01")
        .setContentTitle("some title")
        .setContentText(text)
        .setOnlyAlertOnce(true) // so when data is updated don't make sound and alert in android 8.0+
        .setOngoing(true)
        .setSmallIcon(R.drawable.ic_launcher_b3)
        .setContentIntent(contentIntent)
        .build();
}

/**
 * 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);
}

Comments

    Ничего не найдено.