Android 如何使用开关按钮在背景音乐上播放/停止声音
我正在Android上开发一个游戏,我有一个背景音乐,我想停止使用活动中的开关,而不是启动音乐的开关,即参数开关。音乐在主菜单中 这是我的音乐课:Android 如何使用开关按钮在背景音乐上播放/停止声音,android,nullpointerexception,background-music,Android,Nullpointerexception,Background Music,我正在Android上开发一个游戏,我有一个背景音乐,我想停止使用活动中的开关,而不是启动音乐的开关,即参数开关。音乐在主菜单中 这是我的音乐课: public class BackgroundMusic { private MediaPlayer player; public Menu context; public BackgroundMusic(Menu pContext) { context = pContext; player = MediaPlayer.cr
public class BackgroundMusic {
private MediaPlayer player;
public Menu context;
public BackgroundMusic(Menu pContext) {
context = pContext;
player = MediaPlayer.create(context.getApplicationContext(), R.raw.opening);
player.setLooping(true);
player.setVolume(1.0f, 1.0f);
}
public void start() {
player.start();
}
public void stop(){
player.pause();
}
}
下面是我用于交换机的代码:
buttonmusique = (Switch) findViewById(R.id.switch3);
buttonmusique.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("bouton",String.valueOf(buttonmusique.isChecked()));
// If the music is playing
if (isChecked) {
media.start();
buttonmusique.setText("Musique On"); //To change the text near to switch
Log.d("You are :", "Checked");
} else {
media.stop();
// Resume the music player
buttonmusique.setText("Musique OFF"); //To change the text near to switch
Log.d("You are :", " Not Checked");
}
}
});
问题是,如果我按下开关,它会将我送回主菜单(在某些手机上,应用程序崩溃)
这是logcat:
E/bouton: false
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: pts3.botanicagofinal, PID: 14271
java.lang.NullPointerException: Attempt to invoke virtual method 'void pts3.botanicagofinal.BackgroundMusic.stop()' on a null object reference
at pts3.botanicagofinal.Parametres$3.onCheckedChanged(Parametres.java:61)
at android.widget.CompoundButton.setChecked(CompoundButton.java:156)
at android.widget.Switch.setChecked(Switch.java:1071)
at android.widget.Switch.toggle(Switch.java:1066)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:22314)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6223)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated.
我想知道是否有可能以其他方式工作,或者我的代码中是否有错误
提前感谢您的反馈。请显示logcat异常的stacktrace。我刚刚将它添加到您声明的
媒体
?看起来媒体是null
。媒体在主菜单中声明,但我想用我的开关停止类参数中的音乐。是的,媒体在类参数中为null,但我不知道为什么。显然,如果在其他类中声明,它将为null。您应该在服务中使用mediaplayer,在onCheckChangeListener中,您应该将意图传递给该服务以停止mediaplayer。