Xamarin.Android サービス
1 サービスの基本
サービスは、Serviceクラスを継承して作成し、マニュフェストへ記述することでシステムへ登録されます。
Xamarinでは、このマニュフェストへの追加を属性[Service]で指定します。
サービスが起動するとOnStartCommandイベントが発生し、停止するとOnDestroyイベントが発生します。また、処理中に、StopSelf()を呼び出すことで、自らサービスを停止することができます。
[Service] //属性指定 public class MyService : Service{ public override IBinder OnBind(Intent intent){ return null; } private bool _life; public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId){ Log.Debug("MyService", "OnStartCommand"); //ログ //サービスの処理本体 _life = true; var t = new Thread(() =>{ var i = 0; while (_life && i<5){ Log.Debug("MyService", string.Format("JOB {0}", i++));//ログ Thread.Sleep(1000); } StopSelf(); //自らサービスを停止する }); t.Start(); return StartCommandResult.Sticky; } public override void OnDestroy(){ base.OnDestroy(); Log.Debug("MyService", "OnDestroy");//ログ _life = false; } }
Serviceは、抽象クラス(abstract)であり、OnBind()のオーバーライドは必須です。
属性指定でマニュフェストに追加されるタグは下記のとおりです。
<service android:name="androidapplication1.MyService" />
2 サービスの起動停止
定義したサービスの起動停止は、StartService()及びStopService()で行います。
private void Start(){ //サービスの起動 StartService(new Intent(this,typeof (MyService))); } private void Stop(){ //サービスの停止 StopService(new Intent(this, typeof(MyService))); }
3 IntentServiceServiceクラスではなく、IntentServiceクラスを継承すると、ワーカースレッドでOnHandleIntent()が呼び出され、その処理が全部終了すると自動的にサービスが停止します。StopService()やStopSelf()は必要ありません。
軽易にサービスを記述する場合、こちらがお勧めとの事でした。
[Service] public class MyIntentService : IntentService{ public MyIntentService():base("MyIntentService"){ //基底クラスのパラメータは、ワーカースレッド名になる } protected override void OnHandleIntent(Intent intent){ Log.Debug("MyIntentService", "OnHandleIntent"); var i = 0; while (i < 5) { Log.Debug("MyIntentService", string.Format("JOB {0}", i++)); Thread.Sleep(1000); } //この後、サービスは終了し、OnDestroy()が呼ばれる }