title: Music Player Seekbar using Android Studio
body: <p>I was working in a very simple music player with a seek bar.
  I could make it working but I got a problem with playing music, it doesn't work correctly every second - it backwards a while, then remain again like it's a buggy.</p>
  
  <p>Here's full code:</p>
  
  <pre><code>private MediaPlayer mediaPlayer;
  private Button button;
  private TextView textView;
  private SeekBar seek;
  private Handler mHandler = new Handler();
  
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
  
  
      button = (Button)findViewById(R.id.button);
      textView = (TextView)findViewById(R.id.text);
      seek = (SeekBar)findViewById(R.id.seek);
  
      mediaPlayer = new MediaPlayer();
      mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.threedays);
  
  
      MainActivity.this.runOnUiThread(new Runnable() {
  
          @Override
          public void run() {
  
  
  
              if(mediaPlayer != null){
                  int mCurrentPosition = mediaPlayer.getCurrentPosition() / 1000;
                  seek.setProgress(mCurrentPosition);
              }
              mHandler.postDelayed(this, 1000);
          }
      });
  
  
      seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
          @Override
          public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
  
  
              seekBar.setMax(mediaPlayer.getDuration() / 1000);
              textView.setText(progress + "/" + seekBar.getMax());
              mediaPlayer.seekTo(progress*1000);
          }
  
          @Override
          public void onStartTrackingTouch(SeekBar seekBar) {
  
          }
  
          @Override
          public void onStopTrackingTouch(SeekBar seekBar) {
  
          }
      });
  
  
      mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
          @Override
          public void onCompletion(MediaPlayer mp) {
  
              pause();
  
          }
      });
  
  
      button.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
  
              if (mediaPlayer.isPlaying()) {
                  pause();
              } else {
  
                  start();
              }
  
          }
      });
  }
  
  public void start(){
      if(mediaPlayer!=null) {
          mediaPlayer.start();
          button.setText("Pause");
      }
  }
  
  public void pause(){
      if(mediaPlayer!=null) {
          mediaPlayer.pause();
          button.setText("Play");
      }
  }
  
  @Override
  protected void onDestroy() {
  
      if(mediaPlayer!=null &amp;&amp; mediaPlayer.isPlaying()) {
          mediaPlayer.pause();
          mediaPlayer.release();
          mediaPlayer = null;
      }
  
      super.onDestroy();
  }
  </code></pre>