I make an activity with a RecyclerView
;
In the RecyclerView
, I made a song list with a seekbar and play button.
In seekbar, this moved with music current position using thread
But change activity, music is stop but error
I want when i change the activity, music is stop and not error
Please help me
//seekbar change listener
seekbar.setMax(music.getDuration());
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if(fromUser)
music.seekTo(progress);
}
});
//music playing
public void button(View v){
if(music.isPlaying()){
music.stop();
try {
music.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
music.seekTo(0);
button.setText(R.string.start);
seekbar.setProgress(0);
}else{
music.start();
button.setText(R.string.stop);
Thread();
}
}
//Thread
public void Thread(){
Runnable task = new Runnable(){
public void run(){
while(music.isPlaying()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
seekbar.setProgress(music.getCurrentPosition());
}
}
};
Thread thread = new Thread(task);
thread.start();
}
The thread only can be kill in Activity or Fragment. Use this class to override your recyclerview click listener.
Create new java file and name it
RecyclerItemClickListener.java
In your activity/fragment
Now, you can use OnPause() and OnStop() method to kill the thread or services