Two or more Foreground Notification with Progress is replacing each other while updating its progress

前端 未结 4 1049
北恋
北恋 2021-01-22 04:15

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

4条回答
  •  佛祖请我去吃肉
    2021-01-22 04:29

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

提交回复
热议问题