NotificationManager: notify: идентификатор поврежден: отправлено, получено 0 - PullRequest
0 голосов
/ 12 февраля 2019

Последние пару дней я сталкиваюсь с проблемой NotificationManager в моем приложении, и мне кажется, что я не подхожу к ее решению.

У меня очень простой ThreadPoolExecutor для загрузки нескольких файлов,но в то же время мне нужно показать прогресс загрузки внутри панели уведомлений.

class DownloadTask implements Runnable{
String url;
String localFile;
DownloadResultUpdateTask resultUpdateTask;
Context mContext;
final int mNotificationId;

NotificationManager notificationManager;
Notification.Builder notificationBuilder;
PendingIntent pendingIntent;

public DownloadTask(String urlIn, String localFileIn,
                    DownloadResultUpdateTask drUpdateTask,Context context,int notificationId){
    url = urlIn;
    localFile = localFileIn;
    resultUpdateTask = drUpdateTask;
    mContext = context;
    mNotificationId = notificationId;
}

@Override
public void run() {
    String msg;
    if(downloadFile(mNotificationId)){
        msg = "file downloaded successful "+url;


    }else{
        msg = "failed to download the file "+url;
        notificationBuilder.setContentTitle("Download Failed");
        notificationManager.notify(mNotificationId, notificationBuilder.build());
    }
    //update results download status on the main thread
    resultUpdateTask.setBackgroundMsg(msg);
    DownloadManager.getDownloadManager().getMainThreadExecutor()
            .execute(resultUpdateTask);
}

public boolean downloadFile(int  notifId){
    try{
        //pending intent
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", new File(localFile));
            intent.setData(apkUri);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            intent.setData(Uri.fromFile(new File(localFile)));
        }
        pendingIntent = PendingIntent.getActivity(mContext.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);


        //createing notification
        notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        //Set notification information:
        notificationBuilder = new Notification.Builder(mContext.getApplicationContext());
        notificationBuilder.setOngoing(true)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("Downloading PDF")
                .setContentText("0%")
                .setProgress(100, 0, false)
                .setAutoCancel(true)
                .setPriority(Notification.PRIORITY_MAX)
                .build();

        //Send the notification:
        Notification notification = notificationBuilder.build();
        notificationManager.notify(notifId, notification);

        //downloading file
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();

        InputStream in = response.body().byteStream();
        FileOutputStream fileOutput =
                new FileOutputStream(localFile);

        byte[] buffer = new byte[1024*4];
        int bufferLength = 0;

        int target = (int) response.body().contentLength();
        long downloaded = 0;
        int currentPercentage = 0;

        while ((bufferLength = in.read(buffer)) != -1) {
            downloaded += bufferLength;
            currentPercentage = (int)(downloaded * 100) / target;
            if (currentPercentage >= 30 && currentPercentage <= 40 || currentPercentage >= 60 && currentPercentage <= 70
                    || currentPercentage >= 90 && currentPercentage <= 100) {
                notificationBuilder.setProgress(100, currentPercentage, false).setContentText(currentPercentage + "%");
                notificationManager.notify(notifId, notificationBuilder.build()); // facing problem in thisl ine
            }
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();
        response.body().close();
        notificationBuilder.setContentTitle("Download Completed");
        notificationBuilder.setContentText("Click to open " +  url.substring(url.lastIndexOf("/")+1));
        notificationBuilder.setContentIntent(pendingIntent);
        notificationManager.notify(mNotificationId, notificationBuilder.build());

    }catch (Exception e){e.printStackTrace(); return false;}
    return true;
}

Я могу успешно загрузить все файлы.но при обновлении индикатора выполнения я получаю предупреждение ниже, так что уведомление застревает, не показывает загруженный успешно, даже если он загружен.хотя каждый раз, когда я передаю уникальный идентификатор уведомления для разных уведомлений о загрузке.

W/NotificationManager: notify: id corrupted: sent 519, got back 0 

я добавил условие для обновления прогресса только тогда, когда оно достигнет 40, 60 или между 90 и 100, просто чтобы минимизировать количество прогрессаОбновление вызова для повышения производительности.

Любая помощь приветствуется.Спасибо!

...