0

我有一个方法在调用 onPause 后每次都抛出 InvocationTargetException 。它发生在“long totalDuration = mp.getDuration();”的行上 我该如何停止这个异常?

/**
 * 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 ");
        }
    }

}
4

2 回答 2

3
// mHandler -> mHandler Handler instance
// this     -> mUpdateTimeTask Runnable anonymous class

mHandler.removeCallbacks( this );

不要立即停止,而是阻止下一个预定的呼叫。

于 2013-08-10T03:56:10.810 回答
1

发生这种情况是因为在onPause你打电话时mp.release()这是正确的。但是,您的任务仍在尝试在该时间点之后使用对它的引用。在您的设置中,标记您不运行onPause的哨兵值。mUpdateTimeTask

课堂上的某处:

boolean volatile sentinel = false;

在某处onResume

sentinel = false; // need to reset the flag

在某处onPause

sentinel = true;

然后在您的mUpdateTimeTask检查中,sentinel如果它是真的,请不要运行您的代码,也不要重新发布它。然后,您可以在onResume.

于 2013-08-10T03:57:26.633 回答