Search code examples
androidservicemedia-playerandroid-seekbar

How to update SeekBar from MediaPlayer running in Service?


In my app i maid a MediaPlayer playing from Service, to update SeekBar i maid a timer task in Service

timer = new Timer();
timer.scheduleAtFixedRate(new RemindTask(), 0, 1 * 1000);

class RemindTask extends TimerTask {
    @Override
    public void run() {
        if (mediaPlayer!=null && mediaPlayer.isPlaying()){
           MusicPlayerActivity.progress=mediaPlayer.getCurrentPosition();
           MusicPlayerActivity.total=mediaPlayer.getDuration();
        }
    }
}

and using runnable list i made a run method in activity page,

@Override
public void run()
{
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            seekBar.setMax(total);
            seekBar.setProgress(progress);
        }
    });
}

But my issue is that app is very much slow and going stuck.


Solution

  • Use bound service if you need service to activity communication check it here. Or use libraries like EventBus