多个活动时,Android通知未更新

时间:2019-01-30 19:16:11

标签: java android notifications

我正在开发一个下载文件的应用程序。我有一条通知,跟踪每次下载的进度,可以一次下载多个文件。当显示单个通知时,不会出现任何问题。但是,当同时显示多个通知时,它们会在到达特定点时停止更新。

这是我用来更新通知的相关代码:

private static volatile int _id = 1312;

private int notifId;
private DownloadState state;
private Context context;
private NotificationManagerCompat _notifs;
private NotificationCompat.Builder _builder;

public DownloadNotifier(Context cxt, DownloadState _state) {
    context = cxt;
    state = _state;
    state.setListener(this);
    notifId = _id++;
    _notifs = NotificationManagerCompat.from(context);
    createNotify();
    _notifs.notify(notifId, _builder.build());
}

public void createNotify() {
    _builder = new NotificationCompat.Builder(context, NOTIF_CHANNEL)
         .setContentTitle(DownloadState.Status.getString(state.getStatus()))
            .setContentText(state.getTitle())
            .setSmallIcon(android.R.drawable.stat_sys_download)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setProgress(100, 0, false)
            .setOngoing(true);
}

private int _pUpdates = 0;

@Override
public void onProgress(DownloadState state) {
    if (state.getStatus() != DownloadState.Status.DOWNLOADING)
        return;
    if (_pUpdates % 10 == 0 || state.getProgress() == state.getSize()) {
        _builder.setContentTitle(DownloadState.Status.getString(state.getStatus()));
        _builder.setProgress((int) state.getSize(), (int) state.getProgress(), false);
        _builder.setContentText(state.getTitle() + " (" + DownloadState.getHumanReadableSize(state.getProgress()) + "/" + DownloadState.getHumanReadableSize(state.getSize()) + ")");
        _notifs.notify(notifId, _builder.build());
    }
    _pUpdates++;
}

@Override
public void onStatus(DownloadState state) {
    if (_builder == null)
        return;
    _builder.setContentTitle(DownloadState.Status.getString(state.getStatus()));
    if (state.getStatus() != DownloadState.Status.DOWNLOADING)
        _builder.setProgress(0, 0, true);
    if (state.getStatus() == DownloadState.Status.COMPLETE) {
        _builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
        _builder.setOngoing(false);
        _builder.setProgress(0, 0, false);
        state.setListener(null);
    }
    Log.e("Notif", "Download state change " + DownloadState.Status.getString(state.getStatus()) + " (" + notifId + ").");
    _notifs.notify(notifId, _builder.build());
}

无论何时调用onProgress回调,通知都会按预期成功更新。但是,在调用onStatus回调时,如果可见此代码发布的多个通知,则通知将无法更改。我看不出为什么会发生这种情况。

我确定onStatus回调是最后一个要调用的方法(即onProgress方法不会在onStatus方法之后运行,因此不会像{ {1}}方法永远不会运行。

Logcat还成功报告了onStatus消息,因此我知道回调正在运行,并且在"Download state change..." if语句中设置了一个断点以确保此条件确实成立,并且该语句中的代码正在运行(过去)。

简而言之,问题在于state.getStatus() == DownloadState.Status.COMPLETE方法中的代码肯定正在运行,但是无法更新通知(即进度条仍然可见,标题未更改等)。

注意:此问题似乎是Android Oreo独有的。

0 个答案:

没有答案