1

I have a situation where I need to update the notification progress bar after some few more milliseconds. If I use notification manager to update the progress, then the notification will show up even after calling stopForground(true) which is not what I need.

Here is the sample code using the notification manager to update.

private void doStuff() {

    // starting in foreground
    startForeground(123, notification.build());

    final Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            final Handler handler  = new Handler(Looper.getMainLooper());

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    timer++;
                    if(timer > 10){
                        stopForeground(true);
                        stopSelf();
                        return;
                    }
                    if(!bound){
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                notificationManager.notify(123, notification.setProgress(10, timer, false).build());
                            }
                        }, 2000);
                    }

                    handler.postDelayed(this, 1000);

                }
            }, 1000);
        }
    });

    thread.start();
}

otherwise, if I use startForground() way, the notification won't show up after the 2000 milliseconds and I get the desired behavior as shown below:

  private void doStuff() {

    // starting in foreground
    startForeground(123, notification.build());

    final Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            final Handler handler  = new Handler(Looper.getMainLooper());

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    timer++;
                    if(timer > 10){
                        stopForeground(true);
                        stopSelf();
                        return;
                    }
                    if(!bound){
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startForeground(123, notification.setProgress(10, timer, false).build());
                            }
                        }, 2000);
                    }

                    handler.postDelayed(this, 1000);

                }
            }, 1000);
        }
    });

    thread.start();
}

My question is if there would be something wrong I'm not aware of using this way because I have never seen anyone doing it. Please help! Thanks!

Sam Matt
  • 123
  • 2
  • 8

0 Answers0