2

我的音乐播放器应用程序似乎有问题。当我退出它时,它会弹出强制关闭警告。这是代码的一部分,我认为在调试后可能是问题的原因:

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);
           }
        };

这是logcat:

12-13 13:26:01.700: E/AndroidRuntime(31838): FATAL EXCEPTION: main
12-13 13:26:01.700: E/AndroidRuntime(31838): java.lang.IllegalStateException
12-13 13:26:01.700: E/AndroidRuntime(31838):    at android.media.MediaPlayer.getDuration(Native Method)
12-13 13:26:01.700: E/AndroidRuntime(31838):    at com.example.musicshare.AndroidBuildingMusicPlayerActivity$1.run(AndroidBuildingMusicPlayerActivity.java:341)
12-13 13:26:01.700: E/AndroidRuntime(31838):    at android.os.Handler.handleCallback(Handler.java:587)
12-13 13:26:01.700: E/AndroidRuntime(31838):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-13 13:26:01.700: E/AndroidRuntime(31838):    at android.os.Looper.loop(Looper.java:123)
12-13 13:26:01.700: E/AndroidRuntime(31838):    at android.app.ActivityThread.main(ActivityThread.java:3691)
12-13 13:26:01.700: E/AndroidRuntime(31838):    at java.lang.reflect.Method.invokeNative(Native Method)
12-13 13:26:01.700: E/AndroidRuntime(31838):    at java.lang.reflect.Method.invoke(Method.java:507)
12-13 13:26:01.700: E/AndroidRuntime(31838):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
12-13 13:26:01.700: E/AndroidRuntime(31838):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
12-13 13:26:01.700: E/AndroidRuntime(31838):    at dalvik.system.NativeStart.main(Native Method)

我认为问题出在 mp.getDuration 上,但我不知道如何解决。

4

2 回答 2

5

看起来即使您退出后,您的可运行任务仍会在后面运行。所以我的猜测是你可能忘记打电话给removeCallbacks().

我的建议是在您onBackPressed()或退出应用程序的地方添加以下行,

 mHandler.removeCallbacks(mUpdateTimeTask);

确保全局声明 Runnable mUpdateTimeTask 以便它在您的代码中可用。

于 2012-12-13T06:29:34.477 回答
0

应该在 postRunnable 之前移除回调

mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.post(...);
于 2016-01-29T10:52:54.583 回答