1.在raw目录放一个mp3文件:test.mp3;
2.建一个MediaPlay的Service文件MusicService.java
public class MusicService extends Service
{
//MediaPlayer对象
private MediaPlayer player;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
//这里可以理解为装载音乐文件
player = MediaPlayer.create(this, R.raw.test);
//开始播放
player.start();
}
public void onDestroy()
{
super.onDestroy();
//停止音乐-停止Service
player.stop();
}
}
3.主文件
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//从main.xml布局中获得Button对象
Button button_start = (Button)findViewById(R.id.start);
Button button_stop = (Button)findViewById(R.id.stop);
//设置按钮(Button)监听
button_start.setOnClickListener(start);
button_stop.setOnClickListener(stop);
}
//开始按钮
private OnClickListener start = new OnClickListener()
{
public void onClick(View v)
{
//开启Service
startService(new Intent("com.yarin.Android.MUSIC"));
}
};
//停止按钮
private OnClickListener stop = new OnClickListener()
{
public void onClick(View v)
{
//停止Service
stopService(new Intent("com.yarin.Android.MUSIC"));
}
};