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

Android總結篇系列:Service详解

編輯:關於 Android 程式設計

Service通常被稱為「後台服務」,其中「後台」是相對於前台而言,指其運行並不依賴於用戶可視的UI界面。從實際業務需求來理解,Service的適用場景應具備以下條件:

1. 並不依賴於用戶可視的UI界面(當然這條也不是絕對的,如前臺Service就與Notification界面結合使用);

2. 具有較長時間的運行特性。

1. Service在AndroidManifest.xml中的聲明

從啟動方式上,可將Service分為Started Service和Bound Service。無論哪種類型,都是通過繼承Service基類自定義而來。要想系統能夠找到自定義Service,都需要在AndroidManifest.xml中聲明,語法格式如下:

 1  9 . . . 10 

其中android:name對應Service類名,android:permission是權限聲明,android:process設置具體的進程名稱。需要注意Service能否單獨使用一個進程與其啟動方式有關,下文會給出具體說明。

注:如果自定義Service沒有在AndroidManifest.xml中聲明,使用時不會像Activity那樣直接崩潰報錯,對於顯式Intent啟動的Service,此時也會給出warning信息「IllegalArgumentException: Service not registered」,有時不容易發現是忘了聲明。

2. Started Service

Started Service相對簡單,通過context.startService(Intent serviceIntent)啟動,context.stopService(Intent serviceIntent)停止;在Service內部也可通過stopSelf(...)停止其本身。

1)Started Service自定義:下面是一個最基本的Started Service自定義方式:

 1 public class MyService extends Service { 2 3 public static final String TAG = "MyService"; 4 5 @Override 6 public IBinder onBind(Intent intent) { 7 return null; 8 } 9 10 @Override 11 public void onCreate() { 12 super.onCreate(); 13 Log.w(TAG, "in onCreate"); 14 } 15 16 @Override 17 public int onStartCommand(Intent intent, int flags, int startId) { 18 Log.w(TAG, "in onStartCommand"); 19 Log.w(TAG, "MyService:" + this); 20 String name = intent.getStringExtra("name"); 21 Log.w(TAG, "name:" + name); 22 return START_STICKY; 23 } 24 25 @Override 26 public void onDestroy() { 27 super.onDestroy(); 28 Log.w(TAG, "in onDestroy"); 29 } 30 }

其中onBind(...)是Service基類中唯一的抽象方法,子類必須重寫實現,其返回值只針對Bound Service有用,在Started Service中直接返回null即可。onCreate(...)、onStartCommand(...)和onDestroy()都是Started Service相應生命周期階段的回調函數。

2)Started Service使用:

 1 public class MainActivity extends Activity { 2 3 public static final String TAG = "MainActivity"; 4 5 private Button startServiceBtn; 6 private Button stopServideBtn; 7 private Button goBtn; 8 9 private Intent serviceIntent; 10 11 @Override 12 protected void onCreate(Bundle savedInstanceState) { 13 super.onCreate(savedInstanceState); 14 setContentView(R.layout.activity_main); 15 16 startServiceBtn = (Button) findViewById(R.id.start_service); 17 stopServideBtn = (Button) findViewById(R.id.stop_service); 18 goBtn = (Button) findViewById(R.id.go); 19 20 startServiceBtn.setOnClickListener(new View.OnClickListener() { 21 @Override 22 public void onClick(View v) { 23 serviceIntent = new Intent(MainActivity.this, MyService.class); 24 startService(serviceIntent); 25 } 26 }); 27 28 stopServideBtn.setOnClickListener(new View.OnClickListener() { 29 @Override 30 public void onClick(View v) { 31 stopService(serviceIntent); 32 } 33 }); 34 35 goBtn.setOnClickListener(new View.OnClickListener() { 36 @Override 37 public void onClick(View v) { 38 Intent intent = new Intent(MainActivity.this, BActivity.class); 39 startActivity(intent); 40 } 41 }); 42 43 } 44 45 @Override 46 protected void onDestroy() { 47 super.onDestroy(); 48 Log.w(TAG, "in onDestroy"); 49 } 50 }

當Client調用startService(Intent serviceIntent)後,如果MyService是第一次啟動,會先執行onCreate()回調,然後執行onStartCommand(...);當Client再次調用startService(...),將只執行onStartCommand(...),因為此時Service已經創建,無需執行onCreate()。無論多少次startService,只需一次stopService()即可將Service終止並執行onDestroy()(onDestroy()與onCreate()相對應)。

下面重點關注onStartCommand(Intent intent, int flags, int startId)方法。其中參數flags默認是0(常量名START_STICKY_COMPATIBILITY)。startId是唯一整型,用於表示此次startService(...)的請求標識,多次調用時呈0,1,2...遞增。此函數的int返回值可選值及含義如下:

START_NOT_STICKY:當Service因內存不足被系統kill後,未來即使內存足夠,系統也不會嘗試重新創建,除非Client明確再次調用startService(...)。

START_STICKY:當Service因內存不足被kill後,未來內存足夠時系統會嘗試重新創建,創建成功後回調onStartCommand(...),但其中的Intent將是null(PendingIntent除外)。

START_REDELIVER_INTENT:與START_STICKY唯一不同的是,回調onStartCommand(...)時Intent非空,為最後一次調用startService(...)中的intent。

START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,不保證被kill後onStartCommand會再次被調用,一般不使用,注意前三種即可。

特別注意「當Service因內存不足被系統kill後」這一前提:此函數返回值設定只針對這種情況才有意義,若是人為kill掉Service進程,則無論返回值怎麼設,未來即使內存足夠,Service也不會重啟。

此外,小米手機針對此處做了修改:在「自啟動管理」中有一個自啟動應用列表,默認只有少數應用(如微信、QQ、YY、360等)可自啟動,其他應用默認禁止。用戶手動添加後,若Started Service的onStartCommand(...)返回START_STICKY或START_REDELIVER_INTENT,當用戶長按Home鍵結束App後,未來內存足夠時Service仍可按規定重啟;但若用戶在設置-應用中強制kill掉App進程,Service則不會重啟。(以上結論基於小米2S親測。)

3)Started Service生命周期及進程相關:

1. onCreate(Client首次startService)→ onStartCommand → onStartCommand(可選,多次)→ onDestroy(Client調用stopService)。注:onDestroy()與onCreate()相匹配,當用戶強制kill進程時onDestroy()不會執行。

2. 對於同一類型Service,其實例一次永遠只存在一個,無論Client是否相同組件或是否處於相同進程。

3. Service通過startService(...)啟動後,其生命周期與Client本身無關,只有Client調用stopService(...)或Service調用stopSelf(...)才能停止(用戶強制kill或系統內存不足也可能kill)。

4. Client A通過startService(...)啟動Service後,其他Client(B、C)也可通過stopService(...)結束它。

5. Client調用stopService(...)時若Service未啟動,也不會報錯,即stopService(...)無需判斷Service是否有效。

6. startService(...)中的intent既可以是顯式也可以是隱式,同一App內一般推薦顯式,不同App時只能用隱式。

當Service需要運行在單獨進程中,AndroidManifest.xml聲明時需通過android:process指明進程名,若需對其他App開放則android:exported需設為true(有intent-filter時默認即為true)。

 1  5  6 7  8 

4)Started Service Client與Service通信相關:Client調用startService(...)時可將參數通過Intent直接傳遞給Service;Service執行過程中若需將參數傳回Client,一般可借助發送廣播(此時Client需注冊該廣播)。

3. Bound Service

相對於Started Service,Bound Service有更多知識點。其主要特性在於Service的生命周期依附於Client的生命周期,當Client不存在時Bound Service將執行onDestroy,同時可通過Service中的Binder對象方便地進行Client-Service通信。Bound Service的一般使用過程如下:

1. 自定義Service繼承基類Service並重寫onBind(Intent intent),返回具體的Binder對象;

2. Client通過實現ServiceConnection接口自定義ServiceConnection,並通過bindService(Intent service, ServiceConnection sc, int flags)將Service綁定到此Client;

3. 在自定義ServiceConnection中實現onServiceConnected(ComponentName name, IBinder binder)獲取Service端Binder實例;

4. 通過獲取的Binder實例調用Service端其他公共方法,完成Client-Service通信;

5. 當Client在恰當的生命周期(如onDestroy)時,需調用unbindService(ServiceConnection sc)解綁之前已綁定的Service。

根據onBind(Intent intent)返回的Binder對象定義方式不同,Bound Service可分為以下三種,各有特点和適用場景:

1)Extending the Binder class

這是Bound Service中最常見、最簡單的一種使用方式。局限:Client與Service必須同屬同一進程,不能實現進程間通信(IPC),否則會出現類似「android.os.BinderProxy cannot be cast to xxx」的錯誤。具體使用見下:

 1 public class MyBindService extends Service { 2 3 public static final String TAG = "MyBindService"; 4 5 private MyBinder mBinder = new MyBinder(); 6 7 public class MyBinder extends Binder { 8 MyBindService getService() { 9 return MyBindService.this; 10 } 11 } 12 13 @Override 14 public void onCreate() { 15 super.onCreate(); 16 Log.w(TAG, "in onCreate"); 17 } 18 19 @Override 20 public IBinder onBind(Intent intent) { 21 Log.w(TAG, "in onBind"); 22 return mBinder; 23 } 24 25 @Override 26 public boolean onUnbind(Intent intent) { 27 Log.w(TAG, "in onUnbind"); 28 return super.onUnbind(intent); 29 } 30 31 @Override 32 public void onDestroy() { 33 super.onDestroy(); 34 Log.w(TAG, "in onDestroy"); 35 } 36 }
 1 public class BActivity extends Activity { 2 3 public static final String TAG = "BActivity"; 4 5 private Button bindServiceBtn; 6 private Button unbindServiceBtn; 7 8 private Button startIntentService; 9 10 private Intent serviceIntent; 11 12 private ServiceConnection sc = new MyServiceConnection(); 13 private MyBinder mBinder; 14 private MyBindService mBindService; 15 private boolean mBound; 16 17 private class MyServiceConnection implements ServiceConnection { 18 19 @Override 20 public void onServiceConnected(ComponentName name, IBinder binder) { 21 Log.w(TAG, "in MyServiceConnection onServiceConnected"); 22 mBinder = (MyBinder) binder; 23 mBindService = mBinder.getService(); 24 25 mBound = true; 26 } 27 28 @Override 29 public void onServiceDisconnected(ComponentName name) { 30 // This is called when the connection with the service has been 31 // unexpectedly disconnected -- that is, its process crashed. 32 Log.w(TAG, "in MyServiceConnection onServiceDisconnected"); 33 mBound = false; 34 } 35 36 } 37 38 @Override 39 protected void onCreate(Bundle savedInstanceState) { 40 super.onCreate(savedInstanceState); 41 setContentView(R.layout.b); 42 43 bindServiceBtn = (Button) findViewById(R.id.bind_service); 44 unbindServiceBtn = (Button) findViewById(R.id.unbind_service); 45 startIntentService = (Button) findViewById(R.id.start_intentservice); 46 47 bindServiceBtn.setOnClickListener(new View.OnClickListener() { 48 @Override 49 public void onClick(View v) { 50 Intent intent = new Intent(BActivity.this, MyBindService.class); 51 bindService(intent, sc, Context.BIND_AUTO_CREATE); 52 } 53 }); 54 55 unbindServiceBtn.setOnClickListener(new View.OnClickListener() { 56 @Override 57 public void onClick(View v) { 58 excuteUnbindService(); 59 } 60 }); 61 62 startIntentService.setOnClickListener(new View.OnClickListener() { 63 @Override 64 public void onClick(View v) { 65 Intent intent = new Intent(BActivity.this, MyIntentService.class); 66 startService(intent); 67 } 68 }); 69 70 } 71 72 private void excuteUnbindService() { 73 if (mBound) { 74 unbindService(sc); 75 mBound = false; 76 } 77 } 78 79 @Override 80 protected void onDestroy() { 81 super.onDestroy(); 82 Log.w(TAG, "in onDestroy"); 83 excuteUnbindService(); 84 } 85 }

首次點擊bindServiceBtn進行bindService(...)時,依次回調順序為:

 1 MyBindService(13457): in onCreate 2 MyBindService(13457): in onBind 3 BActivity(13457): in MyServiceConnection onServiceConnected

再次點擊bindServiceBtn按鈕時沒有任何輸出,說明MyBindService沒有進行任何回調。

點擊unbindServiceBtn進行unbindService(...)時,回調順序為:

 1 MyBindService(13457): in onUnbind 2 MyBindService(13457): in onDestroy

注:在四大基本組件中,需要注意的是BroadcastReceiver不能作為Bound Service的Client,因為BroadcastReceiver的生命周期很短,當執行完onReceive(...)回調時其生命周期即完結,而Bound Service又與Client的生命周期相關,因此Android不允許BroadcastReceiver去bindService(...);有此類需求時可考慮通過startService(...)替代。

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