什么情况下既使用startService,又使用bindService呢?
如果你只是想要启动一个后台服务长期进行某项任务,那么使用startService便可以了。如果你还想要与正在运行的Service取得联系,就可以使用bindService,那么取得联系肯定是要service里面的数据或调用里面的方法,总之是为了通讯,怎么用呢?看下面场景。
- 比如做下载功能需要启动一个Service来做后台下载,需要startService来保持长久运行。
- servicer运行当中肯定会有一些下载状态,要时时更新ui界面,通常可以使用broadcast处理,但是缺点是如果交流较为频繁,容易造成性能上的问题。
- 这时可在在service里定义一个内部类
public class DownloadService extends Service {
、 ………………………………………………省略
………………………………………………省略
public class DownloadBinder extends Binder {
//获得下载进度
public int getProgress(){
return progress;
}
}
}
…
public class DownloadingFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
service = new Intent(context, DownloadService.class);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//获得service里的binder对象
binder = (DownloadService.DownloadBinder) service;
}
};
//绑定服务
activity.bindService(service, serviceConnection, Context.BIND_AUTO_CREATE);
}
获取进度
int progress = binder.getProgress();
}
…
最后
以上就是傲娇酸奶最近收集整理的关于既使用startService,又使用bindService的全部内容,更多相关既使用startService内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复