Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create download progress notification in Oreo?

I am creating an App which can download a file from the server and display progress in status bar. Here's my code:

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);
}

During the download, it displays progress correctly, but it produces notification sound every percent of progress. One more problem is that when the download finished, it still display the progress and user cannot clear the notification.

Note: it works fine on older versions. Only happens in Android 8.

like image 793
Leap Bun Avatar asked Nov 07 '22 05:11

Leap Bun


1 Answers

I solved it by changing NotificationManager.IMPORTANCE_DEFAULT to NotificationManager.IMPORTANCE_LOW while creating notification channel.

like image 161
Leap Bun Avatar answered Dec 16 '22 16:12

Leap Bun