利用服务播放音乐的实例,大部分采用SDK上的方式,
MainActivity:
package com.example.androidtest;import com.example.androidtest.myService.LocalBinder;import android.os.Bundle;import android.os.IBinder;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity { protected myService mService;//用于保存sevice所返回的myService对象,以调用Service中所提供的方法 protected boolean mBound;//用于判断绑定情况 private ServiceConnection mConnection = new ServiceConnection() {//作为bindService参数,在绑定后将调用 onServiceConnected,并接受到返回的IBinder对象,该对象可用于获取service所要提供的数据,本例中由于在服务中的LocalBinder添加了getService方法,故可用于获取myService对象 @Override public void onServiceConnected(ComponentName className, IBinder service) { LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) {//在unbindService后调用,用作清理资源 mBound = false; mService.stopMusic(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindService(new Intent(this, myService.class), mConnection, Context.BIND_AUTO_CREATE);//绑定服务 Button startButton = (Button) findViewById(R.id.button1); Button pauseButton = (Button) findViewById(R.id.button2); Button stopButton = (Button) findViewById(R.id.button3); startButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mService.playMusic(); // TODO Auto-generated method stub } }); pauseButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mService.pauseMusic(); // TODO Auto-generated method stub } }); stopButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mService.stopMusic(); } }); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (mBound == true) { unbindService(mConnection);//解除绑定 } }}
myService:
package com.example.androidtest;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class myService extends Service { private LocalBinder localBinder=new LocalBinder();; private MediaPlayer mediaPlayer;//创建一个以raw/music为播放文件的MediaPlayer对象,可用于播放音乐 @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub mediaPlayer=MediaPlayer.create(myService.this,R.raw.music); return localBinder; } //创建内部类作为onBind返回值,用于给客户端获取服务端的载体 public class LocalBinder extends Binder { myService getService() {//直接返回myService对象,个人认为此种方法比较简单,也可在此创建其他需要返回给客户端的方法,用于通信 return myService.this; } } //客户端可调用方法: public void playMusic() { mediaPlayer.start(); } public void pauseMusic() { mediaPlayer.pause(); } public void stopMusic(){ mediaPlayer.stop(); }}