本文是记录做Activity与Service通信时候的一点心得。
Activity向Service通信就不做分析,很简单。主要是Service向Activity传递信息。
demo以模拟service中下载为例。
方式一:回调
①定义一个回调接口 监听下载进度。onDownloadListenner(int progress)
②在Service中创建对象继承Binder并且内部实现方法OnDownload(on DownloadListener listener){}
③在Activity中bindService 通过实现ServiceConnection获取Binder对象,进行onDownload并且通过重写回调方法,让Service中方法对其进行回调,实时修改。
Service中的Binder
public class MyBinder extends Binder{
public void onDownload(DownloadListener listener){
down(listener);
}
}
Activity中实现的
ServiceConnection @Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
myBinder = (MyBinder) service;
myBinder.onDownload(new DownloadListener() {
@Override
public void downloadProgress(int progress) {
// TODO Auto-generated method stub
//更新进度条
}
});
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
方法二:通过在Service中发送广播,在Activity中写内部类继承BroadcastReceiver接受服务中发送的广播实时更新数据。
①注册广播
②在Service中发送广播。