[ZZ][Android]bindServiceでサービスを開始
一般的にstartService(Intent service)を使用してサービスを開始しますが、この場合、サービスオブジェクトの参照は得られません.bindServiceメソッドでサービスを開始すると、この機能を実現できます.次の例を示します.
1.呼び出し元
2:Service
1.呼び出し元
package com.zhf.local;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
/**
* MyService ,
* @author Administrator
*
*/
public class LocalServiceActivity extends Activity {
/** Called when the activity is first created. */
private MyService myService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, MyService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
myService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myService = ((MyService.MyBinder) service).getService();
System.out.println("Service ");
// Service
myService.excute();
}
};
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
};
}
2:Service
package com.zhf.local;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class MyService extends Service {
private final IBinder binder=new MyBinder();
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public class MyBinder extends Binder{
MyService getService(){
return MyService.this;
}
}
public void excute(){
System.out.println(" Binder Service Service ");
}
@Override
public void onDestroy() {
// ( unbindService)
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent) {
// ( unbindService)
System.out.println(" ");
return super.onUnbind(intent);
}
}
転載先http://que2010.iteye.com/blog/1339791