web-dev-qa-db-ja.com

進行中の通知を静かに更新する

他のデバイスにワイヤレスで接続するサービスがあります。サービスが有効になると、有効になっていることを示す継続的な通知があります。

サービスが有効になると、ユーザーは別のデバイスに接続します。この時点で、接続中のデバイスの名前を述べるために進行中の通知を更新したいと思います。これは、更新された情報でstartForeground(ONGOING_NOTIFICATION, notification)を再度呼び出すことで簡単に実行できます。ただし、呼び出されるたびにバーの通知が点滅します。私が本当に欲しいのは、通知バーを点滅させずにバックグラウンドで静かに更新し、ユーザーが見るために通知領域を開くまで違いを知らないようにする通知です。

startForeground()を呼び出さずに通知を更新する方法はありますか?

この動作は、ハニカムでのみ発生します。ジンジャーブレッドデバイス(およびFroyoなどを想定)は、望ましい動作をします。

38
howettl
23
denis.solonenko

私もこの問題を経験しましたが、以前のコメントと少し掘り下げて、解決策を見つけました。

更新時に通知を点滅させたくない場合、またはデバイスのステータスバーを継続的に表示したくない場合は、次の手順を実行する必要があります。

  • ビルダーでsetOnlyAlertOnce(true)を使用します
  • 更新ごとに同じビルダーを使用します。

毎回新しいビルダーを使用する場合、Androidはビューをもう一度再構築しなければならないので、一時的に表示が消えます。

良いコードの例:

class NotificationExample extends Activity {

  private NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
  private mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

  //Different Id's will show up as different notifications
  private int mNotificationId = 1;    

  //Some things we only have to set the first time.
  private boolean firstTime = true;

  private updateNotification(String message, int progress) {
    if (firstTime) {
      mBuilder.setSmallIcon(R.drawable.icon)
      .setContentTitle("My Notification")
      .setOnlyAlertOnce(true);
      firstTime = false;
    }
    mBuilder.setContentText(message)
    .setProgress(100, progress, true);

    mNotificationManager.notify(mNotificationId, mBuilder.build());
  }
}

上記のコードを使用すると、メッセージと進行状況(0〜100)を指定してupdateNotification(String、int)を呼び出すだけで、ユーザーに迷惑をかけることなく通知を更新できます。

59
Chris Noldus

これは私にとってはうまくいきました。それにより、進行中のアクティビティ(SERVICEではない)通知が「サイレントに」更新されます。

NotificationManager notifManager; // notifManager IS GLOBAL
note = new NotificationCompat.Builder(this)
    .setContentTitle(YOUR_TITLE)
    .setSmallIcon(R.drawable.yourImageHere);

note.setOnlyAlertOnce(true);
note.setOngoing(true);
note.setWhen( System.currentTimeMillis() );

note.setContentText(YOUR_MESSAGE);

Notification notification = note.build();
notifManager.notify(THE_ID_TO_UPDATE, notification );
7
Britc