9.3.3活动和服务进行通信
案例:比如说目前我们希望在MyService里提供一个下载功能,然后再活动中可以决定何时开始下载,以及随时查看下载进度。
实现的思路:创建一个专门的Binder对象来对下载功能进行管理。
步骤:
在服务里:
1、现在服务里创建一个关于下载的类DownloadBinder,并让它继承自Binder类,在里面提供一个开始下载的方法startDownload()和一个获取下载进程的方法getProgress()方法;
2、在创建DownloadBinder类的对象mBinder,并在onBind()方法中将该对象return到活动中;
代码示例:
public class MyService extends Service {
private DownloadBinder mBinder= new DownloadBinder();
class DownloadBinder extendsBinder{
public voidstartDownload(){ //这是开始下载的功能
Log.d(“MyService”,”startDownload executed”);
}
public intgetProgress(){ //这是获取下载进度的功能
Log.d(“MyService”,”getProgress executed”);
return 0;
}
}
@Override
public IBinder onBind(Intentintent){
return mBinder;
}
…
}
在活动中:
3、创建ServiceConnection对象,使用匿名内部类的方式实现,复写其onServiceConnected()方法和onServiceDisconnected()方法;
代码示例:
private MyService.DownloadBinderdownloadBinder;
private ServiceConnection connection = newServiceConnection(){
@Override
public voidonServiceConnected(ComponentName name,IBinder service){
downloadBinder =(MyService.DownloadBinder)service;
downloadBinder.startDownload(); //对象调用方法
downloadBinder.getProgress(); //对象调用方法
}
@Override
public voidonServiceDisconnectd(ComponentName name){
}
};
4、绑定服务:构建一个绑定服务的Intent对象,然后调用bindService()方法即可。
public abstract boolean bindService(Intent service,
ServiceConnection conn,
int flags)
该方法接收三个参数:
第一个参数Intent service:Identifiesthe service to connect to. The Intent may specify either an explicit componentname, or a logical description (action, category, etc) to match an IntentFilter
published by a service.
第二个参数ServiceConnection conn: Receives information as the service isstarted and stopped.
第三个参数int flags:Operation options for the binding. May be 0 or BIND_AUTO_CREATE
(表示在活动和服务进行绑定后自动创建服务).
注意:当这里绑定服务之后,就会调用onServiceConnected()方法;
代码示例:
Intent bindIntent = newIntent(this, MyService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE);
5、解绑服务:调用unbindService()方法即可。
public abstract void unbindService(ServiceConnection conn):把刚刚的connection传入即可。
注意:当这里解绑服务之后,就会调用onServiceDisconnected()方法。
代码示例:
unbindServie(connection);
9.4服务的生命周期
onCreate()————服务没有创建的时候调用。
onStartCommand()————一旦在项目的任何位置调用了Context的startService()方法,相应的服务就会调动起来,并回调onStartCommand()方法(服务创建没创建都调用);如果服务之前没有创建,则先执行OnCreate()方法。
onBind()————可以调用Context的bindService()来获取一个服务的持久连接,这时就会回调服务中的onBind()方法,可返回一个IBinder对象。如果服务之前没有创建,则先执行OnCreate()方法。
onDestroy()————·当调用了startService()方法后,又去调用stopService()或stopSelf()方法,服务中的onDestroy()方法就会执行;
· 当调用了bindService()方法后,又去调用unbindService()方法,onDestroy()方法也会执行;
·当一个服务既调用了startService()方法,又调用了bindService()方法,此时要销毁服务,就得同时调用stopService()方法和unbindService()方法,onDestroy()方法才会执行。