如何在奥利奥创建下载进度通知?

时间:2018-06-14 07:46:24

标签: android android-notifications android-8.0-oreo

我正在创建一个可以从服务器下载文件并在状态栏中显示进度的应用程序。这是我的代码:

private void startDownload(final String fileUrl) {
    Thread thread = new Thread() {
        @Override
        public void run() {
            NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(DownloadsActivity.this);

            String contentTitle = "Start downloading";
            Intent notifyIntent = new Intent();
            PendingIntent notifyPendingIntent = PendingIntent.getActivity(DownloadsActivity.this, DOWNLOAD_NOTIFICATION_ID, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder notificationBuilder = createNotificationBuilder("downloader_channel");
            notificationBuilder.setContentIntent(notifyPendingIntent);
            notificationBuilder.setTicker("Start downloading from the server");
            notificationBuilder.setOngoing(true);
            notificationBuilder.setAutoCancel(false);
            notificationBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
            notificationBuilder.setContentTitle(contentTitle);
            notificationBuilder.setContentText("0%");
            notificationBuilder.setProgress(100, 0, false);
            notificationManagerCompat.notify(DOWNLOAD_NOTIFICATION_ID, notificationBuilder.build());

            boolean success;
            try {
                String fileName = DownloadUtils.getInstance().getFullFileName(fileUrl);
                File tmpFile = new File(fileName + ".tmp");

                URL url = new URL(fileUrl);
                URLConnection conection = url.openConnection();
                conection.connect();
                int fileLength = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream to write file

                OutputStream output = new FileOutputStream(tmpFile);

                byte data[] = new byte[1024];

                long total = 0;
                int count, tmpPercentage = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    output.write(data, 0, count);
                    int percentage = (int) ((total * 100) / fileLength);
                    if (percentage > tmpPercentage) {
                        notificationBuilder.setContentText(percentage + "%");
                        notificationBuilder.setProgress(100, percentage, false);
                        notificationManagerCompat.notify(DOWNLOAD_NOTIFICATION_ID, notificationBuilder.build());
                        tmpPercentage = percentage;
                    }
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

                // rename file but cut off .tmp
                File newFile = new File(fileName);
                success = tmpFile.renameTo(newFile);
            } catch (Exception e) {
                showLog("[Download Error]: " + e.getMessage());
                success = false;
            }
            showLog("Download finished");
            contentTitle = "Downloaded";
            String statusText = success ? "Done" : "Fail";
            int resId = success ? android.R.drawable.stat_sys_download_done : android.R.drawable.stat_notify_error;
            notificationBuilder.setContentTitle(contentTitle);
            notificationBuilder.setSmallIcon(resId);
            notificationBuilder.setOngoing(false);
            notificationBuilder.setAutoCancel(true);
            notificationBuilder.setContentText(statusText);
            notificationBuilder.setProgress(0, 0, false);
            notificationManagerCompat.notify(DOWNLOAD_NOTIFICATION_ID, notificationBuilder.build());
            isDownloading = false;
        }
    };
    isDownloading = true;
    thread.start();
}

private NotificationCompat.Builder createNotificationBuilder(String channelId) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        String channelName = getString(R.string.app_name);
        NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
        notificationChannel.setLightColor(Color.BLUE);
        notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(notificationChannel);
        }
    }
    return new NotificationCompat.Builder(this, channelId);
}

在下载过程中,它会正确显示进度,但会在每个进度百分比时生成通知声音。还有一个问题是,下载完成后,仍会显示进度,用户无法清除通知。

注意:它在旧版本上运行正常。仅在Android 8中发生。

3 个答案:

答案 0 :(得分:1)

我通过在创建通知渠道时将NotificationManager.IMPORTANCE_DEFAULT更改为NotificationManager.IMPORTANCE_LOW来解决此问题。

答案 1 :(得分:0)

您不必设置Notification IMPORTANCE_LOW,只需将其设置为notification.setAlertOnlyOnce(true)。 下载完成后,可以使用新标题或描述更新通知,也可以关闭此通知并使用其他通知ID创建新通知。

答案 2 :(得分:-1)

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setOnlyAlertOnce();