// mHandler -> mHandler Handler instance
// this -> mUpdateTimeTask Runnable anonymous class
mHandler.removeCallbacks( this );
Don't stop instantly, but prevent next scheduled call.
Question
I have a method that is throwing an InvocationTargetException every single time right after onPause is called. Its happening on the line of "long totalDuration = mp.getDuration();" How do I go about stopping this exception?
/**
* 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 onPause(){
super.onPause();
if(mp != null){
try{
mp.stop();//mp=mediaplayer
mp.release();
} catch(Exception e){
Log.e(TAG, "Error in onPause()\n ");
}
}
}
Solution
// mHandler -> mHandler Handler instance
// this -> mUpdateTimeTask Runnable anonymous class
mHandler.removeCallbacks( this );
Don't stop instantly, but prevent next scheduled call.
OTHER TIPS
This is happening because in onPause
you are calling mp.release()
which is correct. However, your task still is attempting to use a reference to it after that point in time. In your onPause
set a sentinel value that flags your mUpdateTimeTask
to not run.
Somewhere in class:
boolean volatile sentinel = false;
Somewhere in onResume
:
sentinel = false; // need to reset the flag
Somewhere in onPause
:
sentinel = true;
Then in your mUpdateTimeTask
check the sentinel
if it is true do not run your code and do not repost it. You can then execute it in onResume
.