Android でフォアグラウンド サービスの通知テキストを更新するにはどうすればよいですか? 質問する

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

ベストアンサー1

startForeground() によって設定された通知を更新する場合は、新しい通知を作成し、NotificationManager を使用して通知するだけです。

重要な点は、同じ通知 ID を使用することです。

Notification を更新するために 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);
}

ドキュメンテーション

通知を更新できるように設定するには、 を呼び出して通知 ID で通知を発行しますNotificationManager.notify()。通知を発行した後にこの通知を更新するには、NotificationCompat.Builderオブジェクトを更新または作成し、Notificationそこからオブジェクトを構築して、Notification以前使用したのと同じ ID で を発行します。以前の通知がまだ表示されている場合は、オブジェクトの内容から更新されますNotification。以前の通知が閉じられている場合は、代わりに新しい通知が作成されます。

おすすめ記事