我在弄清楚如何正确组织特定的android代码方面遇到一些问题。
这是代码的体系结构:在活动的onCreate内,addService通过bindService进行一些工作,只有在onServiceConnected方法成功完成后才能运行getServices:
public class MyClass{
List<IBinder> binders = new ArrayList<IBinder>;
int stillSettingUp = 0;
public void addService(Class<?> cls) {
//Adds a binder via bindService
ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
//Callback for service being successfully started
binders.add(service);
stillSettingUp--;
}
};
//Increment count of the number of services being set up
stillSettingUp++;
Intent intent = new Intent(context, cls);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
public List<IBinder> getServices(){
while (stillSettingUp != 0) {
Log.w("", "Waiting for services to successfully connect... " + stillSettingUp);
Thread.sleep(1000);
}
return binders;
}
}
困难在于:第二种方法需要onServiceConnected函数来完成。在整个onCreate函数完成之前,onServiceConnected函数无法执行(因为它们是固定在主循环末尾的事件,在当前事件完成之前无法执行),因此系统死锁。
有没有一种方法可以强制处理UI线程上的其他事件,或者是更好的协调代码的方法?我试图避免每次我一起调用这两段代码时都运行AsyncTask,因为这需要向调用代码公开线程要求。但是,这很困难,因为您不能强制服务连接回调在其自己的线程中执行。欢迎任何建议。
这是我的问题要点:
1)如果您必须依赖Android回调中的数据,则不应阻塞,因为Android回调不会像其他编程范例中那样发布到单独的线程中。相反,您应该优雅地移到需要数据的位置,可能会重新尝试通过轮询线程进行数据访问。
2)您也可以传递一个可运行的内容,以在连接服务后执行。但是,这可能会变得非常混乱。
3)不要使用太多服务。通常,仅使用一个或两个服务比使用一堆相互通信的服务要容易得多。我重写了这组代码,由于我不经常处理绑定服务,因此可维护性提高了20倍。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句