Seekbar on Android does not move automatically

I wanted to create a seekBar that tracks the progress of the media player, but it does not work well enough, the music plays, but the search remains inactive. Is there something I forgot?

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); seekBar = (SeekBar) findViewById(R.id.seekBar1); seekBar.setOnSeekBarChangeListener(this); } public void onClick(View v){ if(v == stopButton){ mediaPlayer.pause(); }else if(v == startButton){ mediaPlayer.start(); run(); }else if(v == quitButton ){ mediaPlayer.stop(); mediaPlayer.release(); } } public void run() { int currentPosition= 0; int total = mediaPlayer.getDuration(); while (mediaPlayer.isPlaying()) { currentPosition= mediaPlayer.getCurrentPosition(); seekBar.setProgress(currentPosition); } } 
+4
source share
1 answer

In the Tutorial for Android Android Developers, see Updating SeekBar Progress and Timer

 /** * Update timer on seekbar * */ public void updateProgressBar() { mHandler.postDelayed(mUpdateTimeTask, 100); } /** * Background Runnable thread * */ private Runnable mUpdateTimeTask = new Runnable() { public void run() { long totalDuration = mp.getDuration(); long currentDuration = mp.getCurrentPosition(); // Displaying Total Duration time songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration)); // Displaying time completed playing songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration)); // Updating progress bar int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration)); //Log.d("Progress", ""+progress); songProgressBar.setProgress(progress); // Running this thread after 100 milliseconds mHandler.postDelayed(this, 100); } }; /** * * */ @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { } /** * When user starts moving the progress handler * */ @Override public void onStartTrackingTouch(SeekBar seekBar) { // remove message Handler from updating progress bar mHandler.removeCallbacks(mUpdateTimeTask); } /** * When user stops moving the progress hanlder * */ @Override public void onStopTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mUpdateTimeTask); int totalDuration = mp.getDuration(); int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration); // forward or backward to certain seconds mp.seekTo(currentPosition); // update timer progress again updateProgressBar(); } 
+5
source

Source: https://habr.com/ru/post/1479843/


All Articles