android service 之 Binder

1,創建MusicPlayService繼承Service

?
1
2
3
public class MusicPlayService extends Service{
    
}

2, 在MusicPlayService中創建內部類Mybinder繼承Binder

?
1
2
3
4
5
6
 public final class Mybinder extends Binder{
  public MusicPlayService getService()
  {
   return  MusicPlayService.this;
  }
 }

3, 重寫onBinder()方法,反回內部類Mybinder實例對象

?
1
2
3
4
 public IBinder onBind(Intent arg0) {
  // TODO Auto-generated method stub
  return new Mybinder();
 }

4,重寫onCreate()

?
1
2
3
4
5
6
7
 public void onCreate() {
  // TODO Auto-generated method stub
  Toast.makeText(this"MusicSevice onCreate()" , Toast.LENGTH_SHORT).show();
        Log.e("test""--->onCreate()");
        //musicplay=BackgroundMusicPlay.getBackgroundMusicPlay(this);
        super.onCreate();
 }

5,在activity中綁定service

?
1
2
3
4
5
6
MusicPlayService service;//聲明服務對象 
//綁定服務
Intent intent2=new Intent(ShorMusicPlay.this, MusicPlayService.class);
bindService(intent2, conn, BIND_AUTO_CREATE);
//調用服務,通過第6步中的 service=((Mybinder)arg1).getService();得到實例對象
service.playMusic();//playMusic可自行在MusicPlayService中添加

6,在ServiceConnection的onServiceConnected得到MusicPlayService的實例對象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
 private ServiceConnection conn=new ServiceConnection() {
  @Override
  public void onServiceConnected(ComponentName arg0, IBinder arg1) {
   // TODO Auto-generated method stub
   Log.e("test"" on  Service  Connected");
   service=((Mybinder)arg1).getService();//得到MusicPlayService實例對象
  }
  @Override
  public void onServiceDisconnected(ComponentName arg0) {
   // TODO Auto-generated method stub
   Log.e("test"" on  Service   Disconnected");
  }
 };

7,在onDestroy()方法中解除綁定

?
1
2
3
4
5
 protected void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  unbindService(conn);
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章