1to add a background music to the game first you need to add a class, this class is inheritedService, as follows.
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.mmpis a resource file,MP3format of
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, inAndroidmanifest.xmlAdd the following code。
<service android:name= ". Musicserver ">
<intent-filter>
<action android:name= "Com.angel.Android.MUSIC"/>
<category android:name= "Android.intent.category.default"/>
</intent-filter>
</service>
3, inSnake.javaAdd the following code (red for the newly added)
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 ());
}
}
So you can hear the background music when you run the game.
Android in the game to achieve the background music function