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

透徹理解Android Service:基礎知識與編寫實戰

編輯:關於 Android 程式設計

首先,什麼是Service?

Service就是Android系統中的服務,它有這麼幾個特點:它無法與使用者直接交互,必須由使用者或其他程式顯式啟動;它的優先級比較高——比處於前台的應用低,但比其他後台應用高,這就決定了當系統因記憶體不足而銷毀某些閒置資源時,它被銷毀的概率很小。

那麼,什麼時候我們需要使用Service呢?

Service是運行在後台的應用,對使用者來說已不再是關注焦點。舉個例子:當我們打開音樂播放後想去看圖片,又不希望音樂停下來,這時就會用到Service;再比如,點開一個下載連結後,我們顯然不想乾瞪著眼等它下載完,而是希望能一邊在後台下載、一邊去逛逛新聞,這同樣需要Service來幫忙。

Service的分類:
一般我們把Service分為兩類:本地Service與遠程Service。

1. 本地Service:顧名思義,就是與當前應用同處一個進程的Service,彼此共享同一塊記憶體區域,因此某些資料的共享特別方便、簡單。

2. 遠程Service:主要涉及不同進程間的Service訪問。由於Android出於系統安全考慮,不同進程之間無法用一般方式共享資料,為此Android提供了一個AIDL工具(Android Interface Description Language,Android接口描述語言),後文會對它做詳細介紹。

Service啟動流程
context.startService() 啟動流程:
context.startService() → onCreate() → onStart() → Service running → context.stopService() → onDestroy() → Service stop

如果Service還沒運行,Android會先呼叫onCreate(),再呼叫onStart();如果Service已經在運行,則只呼叫onStart(),因此一個Service的onStart方法可能會被重複調用多次。如果呼叫stopService(),會直接走到onDestroy;如果是呼叫者自己直接退出而沒呼叫stopService,Service會一直在後台運行,該Service的呼叫者再次啟動後可透過stopService關閉它。所以呼叫startService的生命週期為:onCreate → onStart(可多次調用)→ onDestroy。

context.bindService() 啟動流程:
context.bindService() → onCreate() → onBind() → Service running → onUnbind() → onDestroy() → Service stop

onBind()會返回給客戶端一個IBinder介面實例,IBinder允許客戶端回調服務的方法,例如取得Service的實例、運行狀態或其他操作。此時呼叫者(Context,例如Activity)會與Service綁定在一起,Context退出後,Service就會依序呼叫onUnbind → onDestroy 相應退出。所以呼叫bindService的生命週期為:onCreate → onBind(只一次,不可多次綁定)→ onUnbind → onDestroy。在Service每一次的開啟關閉過程中,只有onStart可被多次調用(透過多次startService),其他的onCreate、onBind、onUnbind、onDestroy在一個生命週期中都只能被調用一次。

Service生命週期:

和Activity相比,Service的生命週期已經簡單得不能再簡單了,只有onCreate()→onStart()→onDestroy()三個方法。

Activity中與Service相關的方法:

  • startService(Intent intent):啟動一個Service
  • stopService(Intent intent):停止一個Service

如果我們想使用Service中的一些資料或訪問其中的方法,就要透過下面的方法:

  • public boolean bindService(Intent intent, ServiceConnection conn, int flags);
  • public void unbindService(ServiceConnection conn);

其中intent是跳轉到Service的intent,如Intent intent = new Intent(); intent.setClass(this, MyService.class);

 /** * 鏈接到service時觸發。 * name 鏈接到service組件的名稱 * service 在service中調用onBund時返回的IBinder,主要用來進行信息的交流 */ @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i("通知", "鏈接成功!"); MyBinder binder = (MyBinder)service; MyService myService = binder.getMyService(); int count = myService.getCount(); Log.i("通知", "count="+count); } 

使用Service的步驟:

第一步:繼承Service類,實作自己的Service。如果想訪問Service中的某些值,通常會提供一個繼承自Binder的內部類,透過onBind()方法返回給Service請求——這裡巧妙地利用了內部類能訪問外部類屬性的特點。

第二步:在AndroidManifest.xml中進行註冊,如:

 <!-- service配置開始 --> <service android:name="MyService"></service> <!-- service配置結束 --> 

第三步:在Activity中進行啟動、綁定、解綁或停止Service。

(很多書上說Service與使用者不能交互,其實這話並不準確——我們完全可以透過Activity與Service進行交互。我認為更確切的說法應該是:Service與使用者不能進行「直接」的交互。)

下面提供一個調用Service播放音樂的範例。

Activity程式碼:

 package cn.com.chenzheng_java; import cn.com.chenzheng_java.MyService.MyBinder; 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.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; /** * @description 對service進行簡單的應用 */ public class ServiceActivity extends Activity implements OnClickListener{ private Button button_start ; private Button button_bind ; private Button button_destroy ; private Button button_unbind; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.service); button_start = (Button) findViewById(R.id.button1_service); button_bind = (Button) findViewById(R.id.button2_service); button_destroy = (Button) findViewById(R.id.button3_service); button_unbind = (Button) findViewById(R.id.button4_service); button_start.setOnClickListener(this); button_bind.setOnClickListener(this); button_destroy.setOnClickListener(this); button_unbind.setOnClickListener(this); } private class MyServiceConnection implements ServiceConnection{ /** * 鏈接到service時觸發。 * name 鏈接到service組件的名稱 * service 在service中調用onBund時返回的IBinder,主要用來進行信息的交流 */ @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i("通知", "鏈接成功!"); MyBinder binder = (MyBinder)service; MyService myService = binder.getMyService(); int count = myService.getCount(); Log.i("通知", "count="+count); } @Override public void onServiceDisconnected(ComponentName name) { Log.i("通知", "鏈接未成功!"); } } private MyServiceConnection serviceConnection = new MyServiceConnection(); @Override public void onClick(View v) { if(v == button_start){ Intent intent = new Intent(); intent.setClass(getApplicationContext(), MyService.class); startService(intent); } if(v == button_bind){ Intent intent = new Intent(); intent.setClass(getApplicationContext(), MyService.class); bindService(intent,serviceConnection , BIND_AUTO_CREATE); } if(v==button_destroy){ Intent intent = new Intent(); intent.setClass(getApplicationContext(), MyService.class); stopService(intent); } if(v==button_unbind){ unbindService(serviceConnection); } } } 

繼承Service的類:

 package cn.com.chenzheng_java; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.Binder; import android.os.IBinder; import android.util.Log; /** * @description 實現自己的service * @author chenzheng_java * @since 2011/03/18 */ public class MyService extends Service { MediaPlayer mediaPlayer; /** * 當用戶調用bindService方法時會觸發該方法 返回一個IBinder對象,我們可以通過該對象,對service中 的某些數據進行訪問 */ @Override public IBinder onBind(Intent intent) { Log.i("通知", "service綁定成功!"); return new MyBinder(); } @Override public void onCreate() { Log.i("通知", "service創建成功!"); mediaPlayer = MediaPlayer.create(this, R.raw.aiweier); mediaPlayer.setLooping(false); super.onCreate(); } @Override public void onDestroy() { mediaPlayer.stop(); Log.i("通知", "service銷毀成功!"); super.onDestroy(); } @Override public void onRebind(Intent intent) { Log.i("通知", "service重新綁定成功!"); super.onRebind(intent); } @Override public void onStart(Intent intent, int startId) { mediaPlayer.start(); Log.i("通知", "service start成功!"); super.onStart(intent, startId); } @Override public boolean onUnbind(Intent intent) { mediaPlayer.stop(); Log.i("通知", "service解綁成功!"); return super.onUnbind(intent); } private int count = 100; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public class MyBinder extends Binder { /** * @return 返回一個個人的service對象 */ MyService getMyService() { return MyService.this; } } } 

service.xml程式碼:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:text="啟動" android:id="@+id/button1_service" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <Button android:text="綁定" android:id="@+id/button2_service" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <Button android:text="銷毀" android:id="@+id/button3_service" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <Button android:text="解綁" android:id="@+id/button4_service" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout> 

androidManifest.xml

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="cn.com.chenzheng_java" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name="ServiceActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- service配置開始 --> <service android:name="MyService"></service> <!-- service配置結束 --> </application> </manifest> 

最終效果圖:

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