Android 给贪吃蛇游戏加背景音乐

Android有个贪吃蛇的游戏,但是打开这个游戏非常枯燥,给加个背景音乐吧

1、增加一个类,这个类是继承Service的,如下。

package com.example.Android.snake; import Android.app.Service; import Android.content.Intent; import Android.media.MediaPlayer; import Android.os.IBinder; public class MusicServer extends Service { private MediaPlayer mediaPlayer; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onStart(Intent intent,int startId){ super.onStart(intent, startId); if(mediaPlayer==null){ // R.raw.mmp是资源文件,MP3格式的 mediaPlayer = MediaPlayer.create(this, R.raw.mmp); mediaPlayer.setLooping(true); mediaPlayer.start(); } } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); mediaPlayer.stop(); } }

 

2、在AndroidManifest.xml中添加如下代码。

 

3.在Snake.java加入以下代码

 

package com.example.Android.snake; import Android.app.Activity; import Android.os.Bundle; import Android.view.Window; import Android.widget.TextView; import Android.content.Intent; public class Snake extends Activity { private SnakeView mSnakeView; private Intent intent = new Intent("com.angel.Android.MUSIC"); private static String ICICLE_KEY = "snake-view"; /** * Called when Activity is first created. Turns off the title bar, sets up * the content views, and fires up the SnakeView. * */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.snake_layout); //start background music startService(intent); mSnakeView = (SnakeView) findViewById(R.id.snake); mSnakeView.setTextView((TextView) findViewById(R.id.text)); if (savedInstanceState == null) { // We were just launched -- set up a new game mSnakeView.setMode(SnakeView.READY); } else { // We are being restored Bundle map = savedInstanceState.getBundle(ICICLE_KEY); if (map != null) { mSnakeView.restoreState(map); } else { mSnakeView.setMode(SnakeView.PAUSE); } } } @Override protected void onPause() { super.onPause(); // Pause the game along with the activity mSnakeView.setMode(SnakeView.PAUSE); stopService(intent); } @Override public void onSaveInstanceState(Bundle outState) { //Store the game state outState.putBundle(ICICLE_KEY, mSnakeView.saveState()); } }

你可能感兴趣的:(Android,android,游戏,service,import,null,class)