我创建了一个播放声音文件的 android 应用程序。当我按下主页按钮时,我注意到声音继续播放并且没有停止,所以我在我的类中添加了以下函数:
@Override
protected void onStop()
{
super.onStop();
finish(); //kill the thread
pS.reset(); //stop the sound
}
@Override
protected void onPause()
{
super.onPause();
finish(); //kill the thread
pS.reset(); //stop the sound
}
当按下“返回”或“主页”时,它会完成这项工作,它会停止音乐并且应用程序不会强制关闭。唯一的问题是,必须播放声音才能使其不是 FC。如果没有声音播放,应用程序 FC。我猜这是
pS.reset();
当声音没有播放时,功能不知道该怎么做。
如果我将其设置为:
pS = 空;
而不是 pS.reset(),当按下“Back”或“Home”时,它会在没有 FC 的情况下做同样的事情吗?
我的 pS 初始化:
pS = MediaPlayer.create(iAct.this, R.drawable.sound);
编辑:我注释掉了
pS.reset();
并添加
pS = null;
它没有FC,但声音不会停止播放。
我更新了我的 onPause():
@Override
protected void onPause()
{
super.onPause();
if (pS.isPlaying()) {
pS.pause(); //stop the sound
finish();
}
else
finish();
}
我的日志:
04-02 13:06:40.563: E/AndroidRuntime(925): FATAL EXCEPTION: main
04-02 13:06:40.563: E/AndroidRuntime(925): java.lang.RuntimeException: Unable to pause activity {com.testcom.myapp/com.testcom.myapp.MyappActivity}: java.lang.NullPointerException
04-02 13:06:40.563: E/AndroidRuntime(925): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2354)
04-02 13:06:40.563: E/AndroidRuntime(925): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2311)
04-02 13:06:40.563: E/AndroidRuntime(925): at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:2291)
04-02 13:06:40.563: E/AndroidRuntime(925): at android.app.ActivityThread.access$1700(ActivityThread.java:117)
04-02 13:06:40.563: E/AndroidRuntime(925): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:938)
04-02 13:06:40.563: E/AndroidRuntime(925): at android.os.Handler.dispatchMessage(Handler.java:99)
04-02 13:06:40.563: E/AndroidRuntime(925): at android.os.Looper.loop(Looper.java:123)
04-02 13:06:40.563: E/AndroidRuntime(925): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-02 13:06:40.563: E/AndroidRuntime(925): at java.lang.reflect.Method.invokeNative(Native Method)
04-02 13:06:40.563: E/AndroidRuntime(925): at java.lang.reflect.Method.invoke(Method.java:507)
04-02 13:06:40.563: E/AndroidRuntime(925): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-02 13:06:40.563: E/AndroidRuntime(925): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-02 13:06:40.563: E/AndroidRuntime(925): at dalvik.system.NativeStart.main(Native Method)
04-02 13:06:40.563: E/AndroidRuntime(925): Caused by: java.lang.NullPointerException
04-02 13:06:40.563: E/AndroidRuntime(925): at com.testcom.myapp.MyappActivity.onPause(MyappActivity.java:119)
04-02 13:06:40.563: E/AndroidRuntime(925): at android.app.Activity.performPause(Activity.java:3851)
04-02 13:06:40.563: E/AndroidRuntime(925): at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1191)
04-02 13:06:40.563: E/AndroidRuntime(925): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2341)
04-02 13:06:40.563: E/AndroidRuntime(925): ... 12 more