Уведомления не обновляются, если точка останова - PullRequest
0 голосов
/ 28 февраля 2019

У меня есть служба, которая вызывает BroadcastReceiver.Это работало нормально, но после того, как я изменил внутреннюю систему для обработки идентификаторов уведомлений, последнее обновление уведомлений должно обновить уведомление, чтобы сообщить пользователю о завершении процесса.Однако это окончательное обновление не пройдет, если я не переведу точку останова в режим отладки в методе обработки этих уведомлений.Если точка останова не установлена ​​или режим отладки не активен, это обновление обновления не будет выполнено, и уведомление отобразит свое последнее состояние, сообщающее пользователю, что процесс еще не завершен, что не соответствует действительности.

Вот метод, и Log.d() s показывают, что метод manager.notify() был вызван правильно, чтобы обновить уведомление, чтобы показать, что процесс завершен.

@Override
public void onReceive(Context context, Intent intent) {

    Download data = null;
    try {
        data = (Download) intent.getSerializableExtra(Commons.ARGS.DATA);
    } catch (ClassCastException | NullPointerException e) {
        e.printStackTrace();
    }

    switch (intent.getIntExtra(Commons.ARGS.RESULT, Commons.ARGS.FAILED)) {
        case Commons.ARGS.DESTROY:
            Log.w(TAG, "Service was destroyed");

            if (notifications && manager != null) {
                Download[] remaining = (Download[]) intent.getParcelableArrayExtra(Commons.ARGS.DATA);

                if (remaining == null) break;
                for (Download d : remaining) {
                    // Download has failed since service was destroyed; was never called and has no relations to this case. manager.notify() is called here to update the notification as "cancelled" btw
                }
            }
            break;
        case Commons.ARGS.ERR_LOAD:
            Log.w(TAG, "Failed to load queue");
            break;
    }

    if (data == null) return;

    if (notifications) {
        Intent i = new Intent(context, MainActivity.class);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(activity, Commons.Notif.DOWNLOAD_PROGRESS)
                .setContentIntent(PendingIntent.getActivity(activity, 0, i, 0))
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setSmallIcon(R.drawable.ic_notif)
                .setContentTitle(data.title)
                .setColor(context.getResources().getColor(R.color.Accent))
                .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
                .setGroup(CHANNEL_ID);

        if (manager == null) {
            manager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Downloads in Progress", NotificationManager.IMPORTANCE_DEFAULT);
                channel.setDescription("All downloads are displayed here");
                channel.enableLights(false);
                channel.enableVibration(false);
                manager.createNotificationChannel(channel);
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(CHANNEL_ID);
        }

        // Notification builder styling is handled here

        manager.notify(0, new NotificationCompat.Builder(activity, Commons.Notif.DOWNLOAD_PROGRESS)
            .setChannelId(CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_notif)
            .setGroup(CHANNEL_ID)
            .setColor(activity.getResources().getColor(R.color.Accent))
            .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
            .setGroupSummary(true)
            .setContentText("All downloads have finished.")
            .setContentTitle("Done")
            .build());

        manager.notify(DOWNLOAD_BASE_ID | (data.id & 0x00FF_FFFF), builder.build());
        Log.d(TAG, "Notification updated");
    }
}

Заранее спасибо: P

1 Ответ

0 голосов
/ 02 марта 2019

Я не знаю, что именно происходит, но отмена уведомления с помощью manager.cancel() перед его обновлением с успешным / окончательным уведомлением решила проблему.

int id = // Notification id
if (success) {
    Log.d(TAG, "Success Notification updated");
    manager.cancel(id);
} else Log.d(TAG, "Notification updated");
manager.notify(id, builder.build());
...