編輯:關於 Android 程式設計
Service 作為四大元件之一,值得我們投入更多關注。
在 Android 中,Activity 主要負責前台頁面的展示,Service 則主要負責需要長期運行的任務。舉例來說,一個從 Service 播放音樂的音樂播放器,應被設為前台運行,因為使用者會明確地察覺它的存在——狀態欄可能會顯示當前歌曲,並允許使用者開啟一個 Activity 與播放器互動。
1. 非綁定
透過呼叫應用元件的 startService() 方法來啟動服務。一旦啟動,服務就會在背景持續運行,即使啟動它的應用元件已被關閉。通常已啟動的服務只處理單一功能,也不需要將結果回傳給呼叫者,例如從網路下載或上傳檔案。當服務的工作處理完畢,才會自行關閉。
2. 綁定(bind)
透過呼叫應用元件的 bindService() 方法來綁定服務。已綁定的服務會提供一個客戶端—伺服器互動介面,用於與應用互動、發送請求、取得結果,甚至透過 IPC 存取行程。只要有一個應用元件綁定了服務,服務就會啟動;多個元件可以同時綁定同一個服務。當所有元件都解除綁定後,該綁定服務便會被銷毀。
onStartCommand()
當其他元件(例如 Activity)透過 startService() 請求啟動服務時,系統會呼叫此方法。此方法一旦執行,服務便啟動並在背景長期運行。若實作了它,你就要負責在任務完成時透過 stopSelf() 或 stopService() 停止服務(若只想提供綁定功能,則無需實作此方法)。
onBind()
當元件呼叫 bindService() 想要綁定服務(例如執行行程間通訊)時,系統會呼叫此方法。實作時必須回傳一個 IBinder,讓客戶端能與服務通訊。你必須總是實作這個方法,但若不允許綁定,則應回傳 null。
onCreate()
系統在服務第一次建立時呼叫此方法,用來執行只運行一次的初始化工作(在 onStartCommand() 或 onBind() 等之前)。若服務已在運行,此方法不會被呼叫。
onDestroy()
系統在服務不再被使用、即將銷毀時呼叫此方法。你的服務應在此釋放資源,例如執行緒、已註冊的監聽器與接收器等等。這是服務收到的最後一次呼叫。
如果一個元件透過 startService() 啟動服務(最終導致 onStartCommand() 被呼叫),服務會持續運行,直到它透過 stopSelf() 自行停止,或另一個元件呼叫 stopService() 將其停止。
1. 非綁定
新建一個 MyService 繼承自 Service,並重寫父類的 onCreate()、onStartCommand() 與 onDestroy() 方法。
public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } @Override protected void onHandleIntent(Intent intent) { // IntentService會使用單獨的線程來執行該方法的代碼 // 該方法內執行耗時任務,比如下載文件,此處只是讓線程等待20秒 long endTime = System.currentTimeMillis() + 20 * 1000; System.out.println("onStart"); while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("----耗時任務執行完成---"); } }
我們在版面檔中加入兩個按鈕,一個用於啟動 Service,一個用於停止 Service。接著打開或新建 MainActivity 作為主 Activity,加入啟動與停止 Service 的邏輯:
public class MainActivity extends Activity implements OnClickListener { private Button startService; private Button stopService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService = (Button) findViewById(R.id.start_service); stopService = (Button) findViewById(R.id.stop_service); startService.setOnClickListener(this); stopService.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.start_service: Intent startIntent = new Intent(this, MyService.class); startService(startIntent); break; case R.id.stop_service: Intent stopIntent = new Intent(this, MyService.class); stopService(stopIntent); break; default: break; } }
專案中的每一個 Service 都必須在 AndroidManifest.xml 中註冊,因此還要編輯該檔:
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > …… <service android:name="com.example.servicetest.MyService" > </service> </application>
生命週期分析
onCreate() 方法只在 Service 第一次被建立時呼叫。若服務已被建立過,無論呼叫多少次 startService(),onCreate() 都不會再執行。因此你可以多按幾次 Start Service 按鈕測試,每次只會印出 onStartCommand() 中的日誌。
2. 綁定的 Service
public class LocalService extends Service { // Binder given to clients private final IBinder mBinder = new LocalBinder(); // Random number generator private final Random mGenerator = new Random(); public class LocalBinder extends Binder { LocalService getService() { // 返回本service的實例到客戶端,於是客戶端可以調用本service的公開方法 return LocalService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } /**客戶端所要調用的方法*/ public int getRandomNumber() { return mGenerator.nextInt(100); } }
下面是一個綁定到 LocalService,並在按鈕按下時呼叫 getRandomNumber() 的 Activity 範例:
public class BindingActivity extends Activity { LocalService mService; boolean mBound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onStart() { super.onStart(); // 綁定到類LocalService的實例 Intent intent = new Intent(this, LocalService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // 從service解除綁定 if (mBound) { unbindService(mConnection); mBound = false; } } /** 當按鈕按下時調用(在layout文件中定義的button並用android:onClick 屬性指定響應到本方法) */ public void onButtonClick(View v) { if (mBound) { // 調用LocalService的一個方法 // 然而,如果這個調用中有掛起操作,那麼這個請求應發 // 生在另一個線程來避免拉低activity的性能. int num = mService.getRandomNumber(); Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show(); } } /** 定義service綁定的回調,傳給bindService() 的*/ private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { //我們已經綁定到了LocalService,把IBinder進行強制類型轉換並且獲取LocalService實例. LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; }
1. 採用 Context.startService() 啟動服務時,相關的生命週期方法:
onCreate()–> onStart()–> onDestroy()
onCreate() 在服務被建立時呼叫,無論呼叫多少次 startService() 或 bindService(),服務只會被建立一次。
onStart() 只有採用 startService() 啟動服務時才會回調,在服務開始運行時呼叫。多次呼叫 startService() 雖不會重複建立服務,但 onStart() 會被多次呼叫。
onDestroy() 在服務被終止時呼叫。
2. 採用 Context.bindService() 啟動服務時,相關的生命週期方法:
onCreate()–> onBind() –> onUnbind() –> onDestroy()
onBind() 只有採用 bindService() 啟動服務時才會回調,在呼叫者與服務綁定時呼叫;當呼叫者已與服務綁定,多次呼叫 bindService() 不會導致此方法被多次呼叫。
onUnbind() 只有採用 bindService() 啟動服務時才會回調,在呼叫者與服務解除綁定時呼叫。
如果先以 startService() 啟動服務,再呼叫 bindService() 綁定,然後呼叫 unbindService() 解除綁定,最後再次 bindService() 綁定,觸發的生命週期方法如下:
onCreate()–>onStart()–>onBind()–>onUnbind()[重載後的方法需返回true–>onRebind()
那麼,如果同時點擊了 Start Service 與 Bind Service 按鈕會怎樣呢?你會發現,無論單獨點 Stop Service 還是 Unbind Service,Service 都不會被銷毀,必須兩個都點一下,Service 才會銷毀。也就是說,點擊 Stop Service 只會讓 Service 停止,點擊 Unbind Service 只會讓 Service 與 Activity 解除關聯。一個 Service 必須在既沒有與任何 Activity 關聯、又處於停止狀態時,才會被銷毀。
關鍵在於 Service 的「背景」概念。Thread 大家都熟悉,用於開啟子執行緒,把耗時操作放在這裡執行就不會阻塞主執行緒。而我們最初往往直覺認為 Service 是用來處理背景任務、放耗時操作的,於是產生混淆。但其實 Service 是運行在主執行緒裡的,兩者並無直接關聯。
那 Service 到底有何用處?
關鍵是別把「背景」和「子執行緒」混為一談,這是兩個完全不同的概念。Android 的「背景」指的是它的運行完全不依賴 UI——即使 Activity 被銷毀、程式被關閉,只要行程還在,Service 就能繼續運行。
舉例來說,某些應用需要與伺服器始終保持心跳連線,就可以用 Service 來實現。你可能會問:前面不是說 Service 運行在主執行緒嗎?在這裡一直執行心跳連線難道不會阻塞主執行緒?當然會,但我們可以在 Service 中再開一條子執行緒,把耗時邏輯放在裡面處理就沒問題了。
Activity 很難控制 Thread。Activity 被銷毀後,就再也無法取得先前建立的子執行緒實例;而且在一個 Activity 中建立的子執行緒,另一個 Activity 也無法操作。Service 則不同,所有 Activity 都能與 Service 關聯,並方便地操作其中的方法。即使 Activity 被銷毀,之後只要重新與 Service 建立關聯,就又能取得原有 Service 中 Binder 的實例。因此,用 Service 處理背景任務,Activity 就能放心地 finish,完全不必擔心無法控制背景任務。
IntentService 是 Service 的子類,比普通 Service 多了幾項功能。
先看 Service 本身存在的兩個問題:
Service 不會專門啟動一條獨立行程,它與所屬應用位於同一個行程中;
Service 也不是專門的一條新執行緒,因此不應直接在 Service 中處理耗時任務。
IntentService 的特徵:
會建立獨立的 worker 執行緒來處理所有 Intent 請求;
會用獨立 worker 執行緒處理 onHandleIntent() 中的程式碼,無需處理多執行緒問題;
所有請求處理完畢後,IntentService 會自動停止,無需呼叫 stopSelf();
為 onBind() 提供預設實作,回傳 null;
為 onStartCommand() 提供預設實作,把請求 Intent 加入佇列。
實作方式:
public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } @Override protected void onHandleIntent(Intent intent) { // IntentService會使用單獨的線程來執行該方法的代碼 // 該方法內執行耗時任務,比如下載文件,此處只是讓線程等待20秒 long endTime = System.currentTimeMillis() + 20 * 1000; System.out.println("onStart"); while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("----耗時任務執行完成---"); } }
Activity 中的呼叫程式碼:
public void startIntentService(View source) { // 創建需要啟動的IntentService的Intent Intent intent = new Intent(this, MyIntentService.class); startService(intent); }
以上就是本文對 Android Service 元件方法的詳細介紹,希望對你有所幫助。
動手做音樂播放器(上):用 Service 實現播放核心
第 7 節 播放音樂 播放列表已經準備就緒,接下來讓它真正響起來。最終效果如下: 實現播放需要兩側配合:播放界面負責交互與展示,音樂服務負責真正的播放控制。 7.1
Android 無法取消標題欄的處理方式
在 Android 中取消標題欄,常見做法是透過 requestWindowFeature 或設定全螢幕主題。但在 Android 5.0 之後,部分寫法可能無法達到預期
MVC 三層架構在不同 Java 框架中的實作解析
在企業級 Java Web 開發中,MVC 三層架構一直是理解請求流程、職責分離與系統擴展的重要基礎。不同的框架雖然名稱與 API 各異,但核心思想仍然圍繞著模型、視圖
自定義 ViewGroup 生命週期執行順序全解析
為什麼要搞清執行順序 自定義 ViewGroup 時,最容易犯的錯誤就是把邏輯寫在了錯誤的回調裡——比如在構造方法中獲取寬高(此時必然是 0),或者在 onMeasure