添加背景音乐
1、新建类MusicServer
package com.example.happy;
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格式的,res下新建raw,hb.mp3放到里面
mediaPlayer = MediaPlayer.create(this, R.raw.hb);
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mediaPlayer.stop();
}
}
2、在AndroidManifest中添加
<service
android:name=".MusicServer"
android:exported="false" >
<intent-filter>
<action android:name="com.angel.Android.MUSIC" />
<category android:name="android.intent.category.default" />
</intent-filter>
</service>
3、在类中添加背景音乐函数
//背景音乐函数,开启。添加到protected void onCreate(Bundle savedInstanceState) {}中
Intent intent = new Intent(Birthday.this,MusicServer.class);
super.onCreate(savedInstanceState);
startService(intent);
manu(); //创建private void manu() {}方法
//背景音乐函数,关闭。
protected void onStop(){
Intent intent = new Intent(Birthday.this,MusicServer.class);
stopService(intent);
super.onStop();
}