1.在AndroidManifest.xml文件中的<application>标签内加入下边语句
<service android:name=".MusicServer">
<intent-filter>
<action android:name="com.angel.Android.MUSIC"/>
<category android:name="android.intent.category.default" />
</intent-filter>
</service>
2.新建MusicServer.java类,内容为
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.abc);
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mediaPlayer.stop();
}
}
3.将歌曲放入raw文件夹下,名称为abc
4.在Activity中加入代码
private Intent Serviceintent = new Intent("com.angel.Android.MUSIC");
onCreate方法中加入startService(Serviceintent);
5.退出的页面添加
//防止退出后音乐不停止问题
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopService(ServiceIntent);
System.exit(0);
}