編輯:進階開發
Service 是一種在背景執行、處理長時間作業而且不需要使用者互動的元件。典型情境像是背景播放音樂,或是在使用者切換到其他 App 時仍持續從網路抓取資料,而不阻塞前景的操作體驗。
Service 基本上有兩種狀態:
| 狀態 | 說明 |
|---|---|
| Started(已啟動) | 由 Activity 等元件呼叫 startService() 啟動。一旦啟動,即使發起它的元件被銷毀,服務仍會持續在背景執行,直到有人呼叫 stopService() 或服務自行呼叫 stopSelf()。 |
| Bound(已綁定) | 由元件呼叫 bindService() 建立。這種模式提供用戶端/伺服器式的介面,讓元件能與服務溝通、送出請求並取得結果,也支援跨行程的行程間通訊(IPC)。 |
每個 Service 都有生命週期回呼,讓你能監看狀態變化並在恰當時機做事。下圖左側是透過 startService() 啟動時的生命週期,右側則是透過 bindService() 綁定時的生命週期:
要建立一個服務,需要寫一個類別繼承 Service 或其子類別。Service 基底類別定義了下列回呼,你不必全部實作,但應該知道每個時機的意義:
| 回呼 | 說明 |
|---|---|
| onStartCommand() | 當其他元件呼叫 startService() 要求啟動服務時,系統呼叫此方法。若實作它,工作完成後應以 stopSelf() 或 stopService() 結束服務。 |
| onBind() | 當其他元件呼叫 bindService() 綁定服務時呼叫。要讓用戶端能與服務通訊,必須回傳一個 IBinder 介面;若不打算被綁定,回傳 null 即可。 |
| onUnbind() | 所有用戶端都解除綁定特定介面時呼叫。 |
| onRebind() | 在新的用戶端連上服務時呼叫(此服務先前已被所有用戶端解除綁定)。 |
| onCreate() | 服務第一次被建立時呼叫,無論是由 onStartCommand() 還是 onBind() 觸發,適合執行一次性的初始化。 |
| onDestroy() | 服務不再被使用、即將銷毀時呼叫,應在此釋放執行緒、已註冊的 listener、receiver 等資源。 |
以下是一個把各個回呼都列出來的服務骨架:
package com.yiibai; import android.app.Service; import android.os.IBinder; import android.content.Intent; import android.os.Bundle; public class HelloService extends Service { /** indicates how to behave if the service is killed */ int mStartMode; /** interface for clients that bind */ IBinder mBinder; /** indicates whether onRebind should be used */ boolean mAllowRebind; /** Called when the service is being created. */ @Override public void onCreate() { } /** The service is starting, due to a call to startService() */ @Override public int onStartCommand(Intent intent, int flags, int startId) { return mStartMode; } /** A client is binding to the service with bindService() */ @Override public IBinder onBind(Intent intent) { return mBinder; } /** Called when all clients have unbound with unbindService() */ @Override public boolean onUnbind(Intent intent) { return mAllowRebind; } /** Called when a client is binding to the service with bindService()*/ @Override public void onRebind(Intent intent) { } /** Called when The service is no longer used and is being destroyed */ @Override public void onDestroy() { } }
這個範例示範如何建立一個服務,並用兩個按鈕來啟動與停止它。請沿用先前章節建立的 Hello World 專案:
| 步驟 | 說明 |
|---|---|
| 1 | 用 Eclipse IDE 建立 Android 專案,命名 HelloWorld,套件 com.example.helloworld。 |
| 2 | 修改 MainActivity.java,加入 startService() 與 stopService() 呼叫。 |
| 3 | 在 com.example.helloworld 下新增 MyService.java,實作服務相關邏輯。 |
| 4 | 在 AndroidManifest.xml 中以 <service.../> 標籤註冊服務。 |
| 5 | 修改 res/layout/activity_main.xml,加入一組含兩個按鈕的線性配置。 |
| 6 | 在 res/values/strings.xml 定義 start_service 與 stop_service 兩個字串常數。 |
| 7 | 執行應用程式,在模擬器上驗證結果。 |
以下是修改後 MainActivity.java 的內容:
package com.example.helloworld; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.content.Intent; import android.view.View; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } // Method to start the service public void startService(View view) { startService(new Intent(getBaseContext(), MyService.class)); } // Method to stop the service public void stopService(View view) { stopService(new Intent(getBaseContext(), MyService.class)); } }
接著是 src/com.example.helloworld/MyService.java。這個範例只實作了 onStartCommand() 與 onDestroy() 兩個方法,並用 Toast 提示狀態:
package com.example.helloworld; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.widget.Toast; public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // Let it continue running until it is stopped. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); } }
然後在 AndroidManifest.xml 中加上 <service.../> 標籤註冊服務:
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.helloworld" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <service android:name=".MyService" /> </application> </manifest>
版面配置放兩個按鈕,分別觸發啟動與停止:
<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/btnStartService" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start_service" android:onClick="startService"/> <Button android:id="@+id/btnStopService" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/stop_service" android:onClick="stopService" /> </LinearLayout>
最後在 res/values/strings.xml 補上兩個按鈕文字:
<resources> <string name="app_name">HelloWorld</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="title_activity_main">MainActivity</string> <string name="start_service">Start Service</string> <string name="stop_service">Stop Service</string> </resources>
現在執行修改後的 Hello World。請確認 AVD 與環境都已就緒,開啟專案的 Activity 檔並點擊工具列上的「Run」
圖示。若一切正常,模擬器會顯示如下畫面:
點擊「Start Service」按鈕,服務就會啟動,onStartCommand() 被觸發,模擬器底部會跳出提示訊息:
想結束服務,只要按下「Stop Service」按鈕即可。這個範例示範了最基本的通知式回饋;實務上,長時間的背景作業通常還會搭配前景通知(foreground notification)與 Worker、JobScheduler 等機制,以符合各版本 Android 的背景執行限制。
Android ROOT權限解析:高級控制、漢化與一鍵工具的風險
ROOT權限能帶來什麼 在Android世界,ROOT權限常被視為進階玩法的門票。取得最高權限後,使用者可以存取系統目錄、移除預裝程式、更換主題、載入漢化包,也能讓部分需
Android 的中文名「安致」與它正在爬升的市場份額
用戶選購 Android 手機時,難免會注意到系統名稱,於是「安致」這個名字能否被廣大使用者接受,就成了業界討論的話題——有猜測認為這是 Android 的中文註冊商標。
讓你的第一個 Android 程式跑起來:AVD 建立與專案結構圖解
Android 程式可以促使行動裝置創新,讓使用者體驗到最優越的行動服務,同時開發商也將得到一個新的開放平台,得以開發既有用又有吸引力的行動服務並推廣這些產品。本文是一份
Myriad 推 Android 虛擬機 讓 MeeGo 也能跑 Android 程式
在 Android 快速擴張的同時,其他智慧型手機平台的光芒被掩蓋了不少。原因很單純:Android 是繼 iOS 之後迅速壯大、且擁有大量軟體應用的平台,而這正是手機用