I have a service that will run a upload task in foreground then showing a progress in the notification. Since a user may upload multiple times with different id request then the
At last I figure it out how to do it. First I needed to run it inside a onCreate with a little delay.
@Override
public void onCreate (){
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startForeground(requestCode, getMyActivityNotification("",completedParts,totalSize));
}
},500);
}
Then create a notification provider method.
//Notification provider
private Notification getMyActivityNotification(String caption, long completedUnits, long totalUnits){
int percentComplete = 0;
if (totalUnits > 0) {
percentComplete = (int) (100 * completedUnits / totalUnits);
}
//Return the latest progress of task
return new NotificationCompat.Builder(this, CHANNEL_ID_DEFAULT)
.setSmallIcon(R.drawable.ic_file_upload_white_24dp)
.setContentTitle(getString(R.string.app_name))
.setContentText(caption)
.setProgress(100, percentComplete, false)
.setContentInfo(String.valueOf(percentComplete +"%"))
.setOngoing(true)
.setAutoCancel(false)
.build();
}
Then updating notification progress should be separated from calling a foreground.
/**
* Show notification with a progress bar.
* Updating the progress happens here
*/
protected void showProgressNotification(String caption, long completedUnits, long totalUnits, int code) {
createDefaultChannel();
mCaption = caption;
requestCode = code;
completedParts = completedUnits;
totalSize = totalUnits;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null) {
//Update the notification bar progress
mNotificationManager.notify(requestCode, getMyActivityNotification(caption,completedUnits,totalUnits));
}
}