Serviceスニペット

何か→Service

何かのメソッド内

Context context;//なんらかの方法でContextを得る

context.bindService(
	new Intent(context, SnippetService.class),
	new ServiceConnection(){
		@Override
		public void onServiceConnected(ComponentName arg0, IBinder binder) {
			//ServiceのonBindで返される値が第二引数に入っているので、キャストして使う
		}
		
		@Override
		public void onServiceDisconnected(ComponentName arg0) {}
	},
	Context.BIND_AUTO_CREATE);


Service

public class SnippetService extends Service {
	@Override
	public IBinder onBind(Intent intent) {//bindServiceのIntentが来る
		return new Binder(){};//Binderは継承して使う
	}
}

bindService→Service.onBind→bindServiceの第二引数ServiceConnection.onServiceConnectedの順で実行される。
unbindServiceを実行しなかった場合、Serviceを停止する事が出来ないので注意。bindService内でunbindServiceを行うのも手だと思う。



Service→何か

ServiceのonStartあたり?

Intent intent = new Intent("適当な文字列。Serviceに定数として持たせると便利");
sendBroadcast(intent);
Context context;//なんらかの方法でContextを得る

context.startService(new Intent(context, SnippetService.class));
IntentFilter filter = new IntentFilter("適当な文字列。Serviceに定数として持たせると便利");

context.registerReceiver(new BroadcastReceiver(){
	@Override
	public void onReceive(Context arg0, Intent intent) {
		
	}
}, filter);

Context.registerReceiverで登録→Service.sendBroadcast→Context.registerReceiverの第一引数BroadcastReceiver.onReceiveでIntentを受け取る
Serviceからデータを受け渡したい場合はIntentのputExtraで行う。