libro
www.tuyano.com
Google androidプログラミング入門

サービスを作成する (4/5)

作成:2010-11-01 22:29
更新:2010-11-01 22:44

■アプリからサービスを利用する

では、アプリ側の処理を作成しましょう。ここでは、アプリの起動時にサービスを起動し、サービスから必要に応じて値を受け取って表示させる、といったことを行ないます。jp.tuyano.sampleパッケージに用意される「MySample.java」ソースコードファイルを開き、以下のリストのように記述をしましょう。

今回は、サービスの起動は「startMyService」というメソッドとして定義してあります。ここでサービスを実行し、このアプリと関連付けるための処理が行われています。この他、サブクラスとして「MyServiceConnection」「MyServiceReceiver」といったクラスが定義されています。――では、順に見ていきましょう。

○フィールドの準備
private ServiceConnection serviceConnection;
private final MyServiceReceiver receiver = new MyServiceReceiver();
サービスとの接続を管理するServiceConnection と、レシーバーであるMyServiceReceiverを保管します。なお、MyServiceReceiverは内部クラスで使用する関係上、finalにしてあります。このため、最初にnewでインスタンスを用意しておきます。

○startMyServiceによるサービスの起動

.ServiceConnectionの用意
serviceConnection = new MyServiceConnection();
まず、MyServiceConnectionインスタンスを用意します(このクラスについては後述)。
        
2.インテントの作成
Intent intent = new Intent(this, MySampleService.class);
Intentインスタンスを作成します。これは引数にアプリ自身(this)と、起動するサービス(MySampleService)のclassを指定します。

3.サービスの起動
ComponentName component = startService(intent);
サービスの起動は、「startService」で行ないます。引数に、先ほど用意したMySampleService起動用のIntentを渡して呼び出します。返値にはComponentNameクラスのインスタンスが返されます(今回は特に使っていません)。

4.フィルターの用意
IntentFilter filter = new IntentFilter(MySampleService.ACTION);
ブロードキャストされたときに特定のアクションによるIntentだけを受診するようにするフィルターを作成します。これはIntentFilterクラスとして用意されています。ここでは、MySampleServiceに用意してあるACTIONクラスフィールドの値がアクションとして送られた場合のみ受け取るようにフィルタリングします。

5.レシーバーに登録する
registerReceiver(receiver, filter);
レシーバーにフィルターを登録します。ここでは、あらかじめreceiverフィールドとしてレシーバーを用意してありますので、これとIntentFilterを引数にして、「registerReceiver」を呼び出します。

6.サービスにバインドする
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
用意したIntentServiceConnectionを引数に指定して「bindService」を呼び出し、サービスにバインドをします。第3引数には、BIND_AUTO_CREATEを指定してバインドを自動生成するようにしておきます。これは、ゼロBIND_AUTO_CREATEのいずれかを指定すると考えてください。

○onDestroyによるサービスの停止
最後に、アプリを終了するとき、サービスを停止する処理も触れておきましょう。これは以下のように行なっています。
unbindService(serviceConnection);
unregisterReceiver(receiver);
まず、unbindServiceでサービスとの接続を切り、それからunregisterReceiverでレシーバーの登録を解除します。これでサービスとアプリとの関連が消えます。

――これで、サービスを起動し、アプリとサービスの間をバインドして関連付ける処理ができました。ただし、そのためには別途2つのクラスを用意する必要があります。

※プログラムリストが表示されない場合

AddBlockなどの広告ブロックツールがONになっていると、プログラムリスト等が表示されない場合があります。これらのツールをOFFにしてみてください。

●プログラム・リスト●

package jp.tuyano.sample;

import java.util.Calendar;

import android.app.Activity;
import android.content.*;
import android.os.*;
import android.widget.TextView;

public class MySample extends Activity {
	private ServiceConnection serviceConnection;
	private final MyServiceReceiver receiver = new MyServiceReceiver();
	public TextView textview01;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textview01 = (TextView)findViewById(R.id.TextView01);
        startMyService();
    }

	public void startMyService(){
		// ServiceConnectionの用意
		serviceConnection = new MyServiceConnection();
		
		// サービスを開始
		Intent intent = new Intent(this, MySampleService.class);
		ComponentName component = startService(intent);
		IntentFilter filter = new IntentFilter(MySampleService.ACTION);
		registerReceiver(receiver, filter);
		
		// サービスにバインド
		bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onDestroy() {
		// サービス終了		
		unbindService(serviceConnection); // バインド解除
		unregisterReceiver(receiver); // レシーバー解除
		super.onDestroy();
	}
	
}

// ServiceConnectionクラス
class MyServiceConnection implements ServiceConnection {
	private MySampleService myservice;
	
	@Override
	public void onServiceConnected(ComponentName className, IBinder service) {
		myservice = ((MySampleService.MySampleBinder)service).getService();
	}
	
	@Override
	public void onServiceDisconnected(ComponentName className) {
		myservice = null;
	}
		
}

// Receiverクラス
class MyServiceReceiver extends BroadcastReceiver {
	
	@Override
	public void onReceive(Context context, Intent intent) {
		int counter = intent.getIntExtra("counter", 0);
		((MySample)context).textview01.setText("count: " + counter);
	}
	
}
※関連コンテンツ

「Google androidプログラミング入門」に戻る