创建Bound Service
关键类:
Binder:活动与服务通信的接口,在Service中定义
ServiceConnection:服务生命周期的回调接口,在服务创建和销毁时回调他的方法。
定义服务
public class MyService extends Service {
private DownloadBinder mBinder = new DownloadBinder();
//定义Binder接口
class DownloadBinder extends Binder {
public void startDownload() {
Log.d("MyService", "startDownload executed");
}
public int getProgress() {
Log.d("MyService", "getProgress executed");
return 0;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
……
}
启动服务
定义ServiceConnection
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name,IBinder service) {
//获取Service里面的binder接口实例,进行通信
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
绑定与解绑
绑定
Intent bindIntent = new Intent(this, MyService.class);
//第一个参数是Intent,第二个是ServiceConnection,第三个是标志位:
//这里表示在活动和服务进行绑定后自动创建服务,即会调用onCreate但不会调用startCommand
bindService(bindIntent, connection, BIND_AUTO_CREATE);
解绑
//只要一个参数就是ServiceConntion
unbindService(connection)