0

This question has been asked a few times, but I still could not find a answer.

I'm updating the progress on my SeekBar using a Handler, like this:

Handler handler = new Handler();
private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {
      mSeekBar.setProgress(mPlayer.getDuration());
      handler.postDelayed(runnableCode, 2000);
    }
};

// Start the initial runnable task by posting through the handler
handler.post(runnableCode);

After looking at this question.


The problem is that I'm experiencing lag. Every time the SeekBar gets update, there is a small lag.

Please note that I'm not talking about when the user 'manually' selects the SeekBar. I know I should check if(fromUser) in onProgressChanged when doing that.

Also, I did try a Timer with the same result.

Has anybody experienced this issue and how should I going about resolving this?

ClassA
  • 2,480
  • 1
  • 26
  • 57

1 Answers1

1

Use an Asynctask in the Background to move your SeekBar:

Asynctask : https://developer.android.com/reference/android/os/AsyncTask

@Override
protected Integer doInBackground(Void... params) {
    if(MainActivity.playing) {
        int percent;
        int position = MainActivity.Player.getCurrentPosition();
        int timeRunning = MainActivity.Player.getDuration();
        if (timeRunning == 0 || position == 0) {
            percent = 0;
        } else {
            percent = (position * 100) / timeRunning;
        }

        return percent;
    }
    return -1;
}
@Override
protected void onPostExecute(Integer result) {
    if(result  != -1){
    MainActivity.Mbar.setProgress(result);}

}

and then execute this task once in a secound with a timer in your Activity:

Timer:https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html

time.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            new AsyncTask().execute();
        }
    },0,1000);

Hope that helps you

Donatic
  • 323
  • 1
  • 13
  • Currently you are just getting the position of the player in the background and still setting the progress in `onPostExecute`. So what you are saying is that calling `Player.getCurrentPosition();` is what is causing the lag? – ClassA Aug 23 '18 at 13:07