編輯:關於 Android 程式設計
上一篇《Android 中 Service 服務詳解(一)》談的是透過 Context 的 startService() 與 stopService() 來啟動與停止服務。Service 其實還有一組夥伴方法:綁定服務與解綁服務。這種模式讓 Activity 與 Service 的關係更緊密——你不只是把它拉起來,還能直接呼叫它、請它辦事。
關鍵是在 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>
綁定模式最不一樣的地方,是你要提供一個 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 基本組件用法總結》。
Android 內容觀察者實戰:監聽簡訊資料庫變化
當我們需要即時掌握 Android 系統中某個資料庫的變化,例如簡訊收件匣的更新,就可以使用內容觀察者 ContentObserver。它能夠在指定 URI 的內容發生改
微信登入頁圖片是幾月拍的?地理試題與拍攝冷知識
江蘇省高中學業水平測試地理試題中,出現了關於微信登入頁圖片的判斷題,引發熱議。題目詢問登入頁的地球影像可能拍攝於 6 月還是 12 月,以及 M 地吹的是西風還是東南信風
Android 靜態代碼檢查利器 Lint 的三種用法
基於 Gradle 的 Lint 檢查 在 gradle 中自帶了一個 lint 任務,可以直接執行靜態代碼檢查,但前提是你要在 build.gradle 中配置好 li
Android 貪吃蛇實戰:虛擬方向鍵三角形按鈕點擊變色
在自定義方向鍵中,除了繪製三角形之外,還需要讓按鈕在按下時產生視覺回饋。本篇以 DirectionKeys 為例,說明如何透過 onTouchEvent 與 invali