Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have Custom Notification for android.os.DownloadManager?

Currently I am using below code snippet to download a file using DownloadManager:

String servicestring = Context.DOWNLOAD_SERVICE;
                DownloadManager downloadmanager;
                downloadmanager = (DownloadManager) getSystemService(servicestring);
                Uri uri = Uri
                        .parse("some url here");
                DownloadManager.Request request = new Request(uri);

Using this code I am getting below notification.

enter image description here

My question is, can we add some cross button in this notification so that if user click that button it will cancel download?

Expected output:

(user must be able to cancel download when click on this red cross icon)

enter image description here

Please suggest some way if any. Thank you

like image 398
Vikasdeep Singh Avatar asked Apr 23 '14 06:04

Vikasdeep Singh


People also ask

Do I need download manager on my Android?

If you're usually on an erratic mobile network, the chances of this happening are even higher. Hence, you need a download manager. Download managers can help you overcome several common hassles about downloading from the internet.

What is the use of download manager in Android?

The download manager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file.

How do I fix Download Manager on Android?

I would try this: - Select Download Manager in settings - apps, force stop, storage and clear STORAGE. - Select Play Store in settings apps, force stop, storage, clear CACHE. - Restart the phone and see if the problem persists.


1 Answers

I am using NotificationManager to show downloading percentage and cancel button.

Create pending intent to handle Cancel button click event.

mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(getApplicationContext());
mBuilder.setContentTitle("Extracting link")
         .setContentText("Please wait")
         .setSmallIcon(R.drawable.notification_icon_new)
         .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
         .setColor(getResources().getColor(R.color.colorAccent))
         .setSound(defaultSoundUri)
         .addAction(R.drawable.ic_pause_circle_filled_black_24dp, "Pause", pendingIntentPause)
         .addAction(R.drawable.ic_cancel_black_24dp, "Cancel", pendingIntentCancel)
         .setContentIntent(pendingIntent)
         .setCategory(NotificationCompat.CATEGORY_MESSAGE)
         .setProgress(0, 0, true);
    mNotifyManager.notify(randomNumber, mBuilder.build()); 

Looper mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
initDownload(urlString, randomNumber, mServiceHandler);

download logic and update notification progress.

private void initDownload(String downloadUrl, int notificationId, ServiceHandler mServiceHandler) {
        try {

            URL url = new URL(downloadUrl);
            URLConnection connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a typical 0-100% progress bar
            int fileLength = connection.getContentLength();
            String fileExtension = MimeTypeMap.getFileExtensionFromUrl(downloadUrl);
            fileName = System.currentTimeMillis() + "." + fileExtension;

            // download the file
            InputStream input = new BufferedInputStream(connection.getInputStream());
            OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/" + AppConstant.APP_FOLDER_NAME + "/" + fileName);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            int previousProgress = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                int progress = (int) (total * 100 / fileLength);
                output.write(data, 0, count);
                if (progress == 100 || progress > previousProgress + 4) {
                    // Only post progress event if we've made progress.
                    previousProgress = progress;
                    Message msg = mServiceHandler.obtainMessage();
                    Bundle bundle = new Bundle();
                    bundle.putInt("ID", notificationId);
                    bundle.putInt("PROGRESS", progress);
                    msg.setData(bundle);
                    mServiceHandler.sendMessage(msg);
                }
            }
            output.flush();
            output.close();
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

private final class ServiceHandler extends Handler {

    ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        try {
            int mNotificationId = msg.getData().getInt("ID");
            int mProgress = msg.getData().getInt("PROGRESS");
            if (mProgress == -1) {
                mBuilder.setContentTitle("Download fail")
                        .setContentText("Try another one")
                        .setAutoCancel(true)
                        .setOngoing(false)
                        .setProgress(0, 0, false);
            } else {
                mBuilder.setContentTitle("Downloading...")
                        .setContentText(mProgress + " % downloaded")
                        .setProgress(100, mProgress, false);
                if (mProgress == 100) {
                    mBuilder.setContentTitle(fileName)
                            .setContentText("Download complete, Tap to view")
                            .setAutoCancel(true)
                            .setOngoing(false)
                            .setProgress(0, 0, false);
                }
            }
            mNotifyManager.notify(mNotificationId, mBuilder.build());

        } catch (Exception e) {
            Log.d("shams", " Exception--->  " + e);
            HashMap<String, String> parameters11 = new HashMap<>();
            parameters11.put("error_message", e.getMessage());
            FlurryAgent.logEvent("video_download_fail_exception", parameters11);
            e.printStackTrace();
        }
    }
}

enter image description here

like image 111
Shamsul Avatar answered Oct 12 '22 05:10

Shamsul