这个主要用到及格简单的API和建一个服务,直接看代码,比较简单
.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn_main_play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="play" />
<Button
android:id="@+id/btn_main_pause"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="pause" />
<Button
android:id="@+id/btn_main_stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stop" />
<Button
android:id="@+id/btn_main_exit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="exit" />
</LinearLayout>
.java
public class MainActivity extends ActionBarActivity implements OnClickListener{
private Button btn_main_play;
private Button btn_main_pause;
private Button btn_main_stop;
private Button btn_main_exit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//得到控件
btn_main_play = (Button) findViewById(R.id.btn_main_play);
btn_main_pause = (Button) findViewById(R.id.btn_main_pause);
btn_main_stop = (Button) findViewById(R.id.btn_main_stop);
btn_main_exit = (Button) findViewById(R.id.btn_main_exit);
//设置监听器
btn_main_play.setOnClickListener(this);
btn_main_pause.setOnClickListener(this);
btn_main_stop.setOnClickListener(this);
btn_main_exit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(this,MyService.class);
if(v==btn_main_play){
//传递数据 播放
intent.putExtra("action", "play");
//开启服务
startService(intent);
}else if(v==btn_main_pause){
//传递数据 暂停
intent.putExtra("action", "pause");
startService(intent);
}else if(v==btn_main_stop){
//传递数据 停止
intent.putExtra("action", "stop");
startService(intent);
}else if(v==btn_main_exit){
//退出程序并结束服务
finish();
stopService(intent);
}
}
}
MyService.java
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//得到传来的值
String action = intent.getStringExtra("action");
if(action.equals("play")){
play();
}else if(action.equals("pause")){
pause();
}else if(action.equals("stop")){
stop();
}
return super.onStartCommand(intent, flags, startId);
}
private MediaPlayer player;
/**
* 开始
*/
public void play(){
if(player==null){
//创建MediaPaly对象 并加载相应的音乐文件
player=MediaPlayer.create(this, R.raw.everything_at_once);
}
if(!player.isPlaying()){
player.start();
}
}
/**
* 暂停
*/
public void pause(){
if(player!=null){
player.pause();
}
}
/**
* 停止
*/
public void stop(){
if(player!=null){
player.stop();
player.reset();//重置
player.release();//释放加载的音乐文件
player=null;
}
}
/**
* 结束服务
*/
@Override
public void onDestroy() {
super.onDestroy();
stop();
}
}