I'm working on a music player application.
I'm updating a global variable called "songPosition" inside of a thread. The problem is, whenever a song is switched, it creates a new thread, however the old one is still running in the background and also incrementing the global variable. This is causing the variable to increment quicker than I would like.
Is there a way to stop the old thread from running so that this problem doesn't persist?
Code:
private int songPosition;
new Thread(){
public void run(){
songPosition = 0;
while (songPosition < songDuration){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// here is the variable being incremented
songPosition++;
runOnUiThread(new Runnable() {
@Override
public void run() {
seekBar.setProgress(songPosition); //This requires the variable to be final which is why I have a global variable
songPositionTextView.setText(String.valueOf(songPosition));
}
});
}
}
}.start();