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