使用绑定服务的自定义适配器-何时取消绑定? [英] Custom adapter using bound service - when to unbind?
问题描述
将数据馈送到ListView
的设置:自定义适配器.数据基于外部服务计算的一些数字.我正在使用AIDL绑定服务并获取所需的数据.
The setup: custom adapter that feeds data into ListView
. Data is based on some numbers calculated by external service. I am using AIDL to bind the service and get the data I need.
问题:如何知道何时取消服务绑定?连接是适配器本身专用的,并且检测到整个应用程序正在关闭的唯一方法是覆盖unregisterDataSetObserver
.或者至少我没有找到其他方法,并且该方法与使用内容提供者+内容观察器的同一适配器一起使用时效果很好.不过不适用于AIDL-我收到了ServiceConnectionLeaked
错误.
Problem: How do I know when to unbind the service? Connection is private to adapter itself and the only way to detect that whole application is shutting down is overriding unregisterDataSetObserver
. Or at least I didn't find another way and this one worked well with same adapter using content provider+content observer. Does not work with AIDL though - I'm getting the ServiceConnectionLeaked
error.
我知道我可以在适配器中添加一个"unbindFromService"方法,并从我的活动的onDestroy()中调用它,但这对我来说还不够优雅.如果可能的话,我更喜欢一些诚实"的触发器.
I know I can add a "unbindFromService" method to my adapter and call it from onDestroy() of my activity but that isn't elegant enough for me. I'd prefer some "honest" trigger if possible.
推荐答案
在CustomAdapter中实现ActivityLifecycleCallbacks
,然后从您的活动调用中实现
Implement ActivityLifecycleCallbacks
in your CustomAdapter and then from your activity call
mAdapter.setActivity(this);
适配器类
public class CustomAdapter extends ArrayAdapter<String> implements ActivityLifecycleCallbacks{
Activity mActivity;
public void setActivity(Activity activity) {
/* or you could remove setactivity and do below operation in Constructor */
mActivity = activity;
mActivity.getApplication().registerActivityLifecycleCallbacks(this);
}
@Override
public void onActivityDestroyed(Activity activity) {
/*unregister so that you do not get callbacks after activity is destroyed*/
if(activity instanceof MainActivity)
mActivity.getApplication().unregisterActivityLifecycleCallbacks(this);
/*unregister your activity or in any other callbacks*/
}
/* skipped other dummy functions*/
}
这篇关于使用绑定服务的自定义适配器-何时取消绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!