天天看點

Xamarin.Android Service進階教程

IntentService的使用

前面介紹Service時已經說過Service是運作在主線程中的,我們需要在一個單獨的線程中處理耗時的操作,在Service中自定義線程無疑增加了我們的代碼量且可能因為我們不适當的處理引起應用程式的ANR異常,Android為我們提供了IntentService來解決這個問題。IntentService繼承與Service提送了一個線程來處理我們的耗時操作,且不需要我們控制、結束Service。多次啟動IntentService,每個Service的操作會加入到一個工作隊列依次執行.

IntentService的使用與普通Service有些差別,就是在定義Service時,普通的Service必須重寫OnBind方法,IntentService則要重寫的是OnHandleIntent,在OnHandleIntent方法中編寫我們耗時操作的代碼。

Bound Service介紹

上一篇文章介紹了Service的兩種生命周期和常見的使用形勢,現在對Bound Service簡單的介紹一下。通過bindService方法啟動Service主要是為了實作應用應用程式的通信,可以是應用内的也可以是不同應用之間的通信。

Service相同程序内通信

通過一個簡單的例子介紹如何使用bindService方式啟動服務。

自定義Binder子類,實作自己的邏輯代碼,作為Service中OnBind的傳回。

1
2
3
4
5
6
7
           
class MyBinder:Binder
{
	public void Say ()
	{
		System.Console.WriteLine ("Say What!!!");
	}
}
           

實作Service代碼,在重寫的OnBind方法中傳回定義的Binder對象執行個體。

1
2
3
4
5
6
7
8
9
10
11
12
13
           
[Service]
class MyService:Service
{
	#region implemented abstract members of Service

	public override IBinder OnBind (Intent intent)
	{
		return new MyBinder ();
	}

	#endregion
		
}
           

此時我門可以嘗試調用BindService以綁定啟動我們的服務,會發現我們的工作并沒有完成,還需要定義一個實作了IServiceConnection接口的類,這個類将作為Service與Activity之通信的橋梁。IServiceConnection接口有兩個方法OnServiceConnected和OnServiceDisconnected,如果連結成功回調OnServiceConnected方法,如果異常終止或者其它原因導緻Service連接配接斷開則回調OnServiceDisconnected方法,調用UnBindService斷開Service不會回調該方法。

Xamarin.Android Service進階教程

此時就可以調用如下代碼啟動并綁定Service,第三個參數為Flag辨別。

Intent intent = new Intent (this, typeof(MyService));
BindService (intent, new MyServiceConnection (), 
              Bind.AutoCreate);
           

當Service不在需要時應調用UnbindService方法停止服務。該方法傳入一個IServiceConnection的對象,這個對象應與啟動時傳入的對象是同一個對象,否為會抛出Java.Lang.IllegalArgumentException Service not registered 異常

1
           
UnbindService (serviceConnection);
           

至此實作一個簡單的Bound Service例子結束。

有些情況下為了防止重複綁定服務應該有如下修改:

The BindService method should be called from the ApplicationContext rather than from the Activity.

The SerivceConnection instance should be returned from OnRetainNonConfigurationInstance .

The OnRetainNonConfigurationInstance method should set a flag that will only be used to unbind the service when the service is not stopped due to a configuration change.

Service不同程序内通信

這幾簡單的介紹Service➕Messenger實作不同程序間通信 inter-process communication (IPC) ,Android Interface Definition Language (AIDL)下一片文章中介紹。

服務端Service做如下修改,注冊Service支援隐式啟動并傳回Messenger提供的Binder:

Xamarin.Android Service進階教程

用戶端綁定Service也要做相應調整:

定義Intent

new Intent ("com.xamarin.MyService");           

實作IServiceConnection的OnServiceConnected方法内通過new Messenger (service)獲得Messenger發送消息。

這裡涉及到Message的使用,先不做過多介紹。

後續補充,Android 5.0之後會抛出 Service Intent must be explicit: Intent,對應解決辦法同時設定Intent的Action和PackageName即可。