Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Service 詳解(二):以 Binder 綁定服務,讓 Activity 直接指揮後台

編輯:關於 Android 程式設計

上一篇《Android 中 Service 服務詳解(一)》談的是透過 Context 的 startService() 與 stopService() 來啟動與停止服務。Service 其實還有一組夥伴方法:綁定服務與解綁服務。這種模式讓 Activity 與 Service 的關係更緊密——你不只是把它拉起來,還能直接呼叫它、請它辦事。

一、改造 Service:加入 MusicBinder

關鍵是在 Service 中建一個繼承 Binder 的內部類,把要對外暴露的業務方法放進去,再由 onBind() 把這個物件交出去。

 package com.example.testservice; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; import android.widget.Toast; public class MyService extends Service { //創建自己的綁定服務業務邏輯 class MusicBinder extends Binder{ public void ready(){ Log.d("MyService", "----ready Method---"); } public void play(){ Log.d("MyService", "----play Method---"); } } private MusicBinder musicBinder = new MusicBinder(); @Override public IBinder onBind(Intent arg0) { Toast.makeText(this, "服務的onBind方法被調用", Toast.LENGTH_SHORT).show(); return musicBinder; } /** * 服務第一次創建的時候調用 */ @Override public void onCreate() { super.onCreate(); Toast.makeText(this, "服務的onCreate方法被調用", Toast.LENGTH_SHORT).show(); } /** * 服務每一次啟動的時候調用 */ @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "服務的onStartCommand方法被調用", Toast.LENGTH_SHORT).show(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Toast.makeText(this, "服務的onDestroy方法被調用", Toast.LENGTH_SHORT).show(); super.onDestroy(); } } 

MusicBinder 裡的 ready()、play() 是模擬方法,用來驗證 Activity 端能否直接觸及 Service 的邏輯層。

二、版面:加上綁定與解綁按鈕

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="啟動服務" /> <Button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="停止服務" /> <Button android:id="@+id/button3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="綁定服務" /> <Button android:id="@+id/button4" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="解綁服務" /> </LinearLayout> 

三、MainActivity:ServiceConnection 是核心

綁定模式最不一樣的地方,是你要提供一個 ServiceConnection。當連結建立成功,系統會把 Service 交回的 IBinder 送進 onServiceConnected(),此時做一次型別轉換,就能直接呼叫 Binder 上的方法。

 package com.example.testservice; import com.example.testservice.MyService.MusicBinder; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener{ private Button startService_Button; private Button stopService_Button; private Button bindService_Button; private Button unbindService_Button; private MyService.MusicBinder musicBinder; //創建ServiceConnection,在綁定服務的時候會用到。 private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName service) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { //類型轉換 musicBinder = (MyService.MusicBinder) service; //指揮服務需要做的工作 musicBinder.ready(); musicBinder.play(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //獲取開啟服務按鈕 startService_Button = (Button) findViewById(R.id.button1); //獲取停止服務按鈕 stopService_Button = (Button) findViewById(R.id.button2); //獲取綁定服務按鈕 bindService_Button = (Button) findViewById(R.id.button3); //獲取解綁服務按鈕 unbindService_Button = (Button) findViewById(R.id.button4); //調用點擊事件 startService_Button.setOnClickListener(this); stopService_Button.setOnClickListener(this); bindService_Button.setOnClickListener(this); unbindService_Button.setOnClickListener(this); } /** * 點擊事件 */ @Override public void onClick(View view) { switch(view.getId()){ case R.id.button1: //"開啟服務"按鈕 Intent startIntent = new Intent(this,MyService.class); //開啟服務 startService(startIntent); break; case R.id.button2: //"停止服務"按鈕 Intent stopIntent = new Intent(this,MyService.class); //停止服務 stopService(stopIntent); break; case R.id.button3: //"綁定服務"按鈕 Intent bindIntent = new Intent(this,MyService.class); bindService(bindIntent, connection, BIND_AUTO_CREATE); break; case R.id.button4: //"解綁服務"按鈕 Intent unbindIntent = new Intent(this,MyService.class); unbindService(connection); break; default: break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } 

綁定動作發生在 onClick 的 button3 分支:bindService() 的第三個參數是旗標,此處的 BIND_AUTO_CREATE 代表綁定成功後若服務不存在就自動建立。解綁則呼叫 unbindService()。

四、實測結果

按下「綁定服務」:

 

除了各生命週期方法的 Toast 依序出現,ready 與 play 也會被執行,並在 Logcat 中留下紀錄。

按下「解綁服務」:

五、流程總結

綁定:Context 的 bindService → Service 的 onCreate → Service 的 onBind → 服務運行,Activity 取得 Binder 後即可跨元件呼叫。

解綁:服務運行 → Context 的 unBindService → Service 的 onDestroy → 服務停止。

綁定模式的價值在於「雙向溝通」:startService 是單向下指令,bindService 則讓 Activity 與 Service 之間有了物件層級的通道。實作背景播放、音樂控制、長時間下載這類需要頻繁互動的場景時,這才是正解。更多內容可參考本站《Android 基本組件用法總結》。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved