I have a MediaPlayer which is contained in a custom ViewHolder and created by a RecyclerViewAdapter which is run by a Fragment. I am trying to update the seekbar every second to show the progress of the audio that the MediaPlayer is playing, using this question's answer:
private Handler mHandler = new Handler();
//Make sure you update Seekbar on UI thread
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if(mMediaPlayer != null){
int mCurrentPosition = mMediaPlayer.getCurrentPosition() / 1000;
mSeekBar.setProgress(mCurrentPosition);
}
mHandler.postDelayed(this, 1000);
}
});
However, since I am running it in an adapter from a fragment and not directly within an activity, I cannot use this line:
MainActivity.this.runOnUiThread(new Runnable() {
So instead, I have passed getActivity()
from the fragment into the RecyclerViewAdapter with the adapter's constructor and set it as a global variable parentActivity
.
I then created the code to update the seekbar within the RecyclerViewAdapter's onBindViewHolder() like so:
final Handler mHandler = new Handler();
this.parentActivity.runOnUiThread(new Runnable(){
@Override
public void run(){
if (mMediaPlayer != null){
int mCurrentPosition = mMediaPlayer.getCurrentPosition();
myViewHolder.seekBar.setProgress(mCurrentPosition);
}
mHandler.postDelayed(this, 1000);
}
});
My problem is that now when I play the audio, although the seekbar updates properly, the audio briefly pauses, or "skips" every second. What could be causing this and how could I fix it?
EDIT: each ViewHolder has its own SeekBar and the mMediaPlayer
is defined as a global variable in the Adapter.