我正在开发游戏,我想在游戏的背景下播放音乐。在切换到gameview之前,我在Game类中初始化了游戏。我也有一个其中具有布尔值的sharedPref,用于根据用户在应用程序中的早期设置如何决定是否播放音乐。我还有另一个SoundService类,应该在一个循环上播放音乐,直到游戏结束,但它从未开始播放。关于为什么会这样的任何想法?
在Game类中创建媒体播放器时,由于它是一项活动,因此能够播放音乐。但是,一旦切换到非活动Gameview,它会在几秒钟后停止播放。
public class Game extends Activity {
public static String user;
public static comHandler com;
boolean value;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
value = getIntent().getExtras().getBoolean("isOn?");//from sound settings
if(value) {
startService(new Intent(Game.this, SoundService.class));
}
setContentView(new GameView2(this));
//setContentView(new GameView(this));
}
protected void onDestroy() {
//stop service and stop music
stopService(new Intent(Game.this, SoundService.class));
super.onDestroy();
}
}
Class SoundService.java:
public class SoundService extends Service {
MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.tune); //select music file
player.setLooping(true); //set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return Service.START_NOT_STICKY;
}
public void onDestroy() {
player.stop();
player.release();
stopSelf();
super.onDestroy();
}
}
GameView2.java类:
public class GameView2 extends SurfaceView implements SurfaceHolder.Callback {
....
}