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

1、增加一个类,这个类是继承Service的,如下。
ample.android.snake;


import android.app.Service;
t.Intent;
dia.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){
Start(intent, startId);

if(mediaPlayer==null){

// p是资源文件,MP3格式的
mediaPlayer = ate(this, p);
mediaPlayer.setLooping(true);
mediaPlayer.start();

}
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
Destroy();
mediaPlayer.stop();
}
}

2、在l中添加如下代码
<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加入以下代码(红为新加的)


ample.android.snake;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;
t.Intent;

游戏xml文件修改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) {
Create(savedInstanceState);

setContentView(R.layout.snake_layout);

//start background music
        startService(intent);


mSnakeView = (SnakeView) findViewById(R.id.snake);
mSnakeView.setTextView((TextView) findViewById());

if (savedInstanceState == null) {
// We were just launched -- set up a new game
mSnakeView.setMode(SnakeView.READY);
} else {
// We are being restored
Bundle map = Bundle(ICICLE_KEY);
if (map != null) {
storeState(map);
} else {
mSnakeView.setMode(SnakeView.PAUSE);
}
}
}

@Override
protected void onPause() {
Pause();
// 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());
}

}




这样运行游戏时候就能听到背景音乐了

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。