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中添加如下代码。
<service android:name=".MusicServer">
<intent-filter>
<action android:name="com.angel.Android.MUSIC"/>
<category android:name="android.intent.category.default" />
</intent-filter>
</service>
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());
}
}
这样运行游戏时候就能听到背景音乐了