3

)を介してフォアグラウンド サービスとして構成されているサービスを実行しており、startForeground(int id, Notification notificationこの通知を更新したいと考えています。これを達成するための私のコードは、おおよそ次のようになります。

private void setForeground() {
    Notification foregroundNotification = this.getCurrentForegroundNotification();

    // Start service in foreground with notification

    this.startForeground(MyService.FOREGROUND_ID, foregroundNotification);
}

...

private void updateForegroundNotification() {
    Notification foregroundNotification = this.getCurrentForegroundNotification();

    // Update foreground notification

    NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(MyService.FOREGROUND_ID, foregroundNotification);
}

サービスの状態に応じて通知を生成するには:

private Notification getCurrentForegroundNotification() {
    // Set up notification info

    String contentText = ...;

    // Build notification

    if (this.mUndeliveredCount > 0) {
        String contentTitleNew = ...;

        this.mNotificationBuilder
        .setSmallIcon(R.drawable.ic_stat_notify_active)
        .setContentTitle(contentTitleNew)
        .setContentText(contentText)
        .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_stat_notify_new))
        .setNumber(this.mUndeliveredCount)
        .setWhen(System.currentTimeMillis() / 1000L)
        .setDefaults(Notification.DEFAULT_ALL);
} else {
        this.mNotificationBuilder
        .setSmallIcon(R.drawable.ic_stat_notify_active)
        .setContentTitle(this.getText(R.string.service_notification_content_title_idle))
        .setContentText(contentText)
        .setLargeIcon(null)
        .setNumber(0)
        .setWhen(0)
        .setDefaults(0);
    }

    // Generate Intent

    Intent intentForMainActivity = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intentForMainActivity, 0);

    // Build notification and return

    this.mNotificationBuilder.setContentIntent(pendingIntent);
    Notification foregroundNotification = this.mNotificationBuilder.build();

    return foregroundNotification;
}

問題は、通知が正しく更新されないことです: サービスを開始してフォアグラウンドで実行すると、 でupdateForegroundNotification()数回呼び出しthis.mUndeliveredCount > 0、その後 で再度呼び出すとthis.mUndeliveredCount == 0、通知の右下隅にある小さな通知アイコンが消えません。 、大きなアイコンは提供されていませんが。この動作は、大きなアイコンが指定されている場合にのみ小さなアイコンが右下隅に表示される必要があると述べられているクラスのメソッドのドキュメントにsetSmallIcon(int icon)よると、正確には予期されていません。NotificationBuilder

public Notification.Builder setSmallIcon (int icon)

ステータス バーで通知を表すために使用される小さなアイコン リソースを設定します。展開ビューのプラットフォーム テンプレートは、大きなアイコンも指定されていない限り、このアイコンを左側に描画します。大きなアイコンも指定されている場合は、小さなアイコンが右側に移動します。

サービス通知の更新で何が間違っていますか? それともAndroidのバグですか?

4

1 に答える 1