Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android Service 教學:建立與管理背景服務

編輯:進階開發

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 的背景執行限制。

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