gpt4 book ai didi

Android onCreate 死锁

转载 作者:行者123 更新时间:2023-11-30 03:14:40 24 4
gpt4 key购买 nike

我在弄清楚如何正确组织特定的 android 代码时遇到了一些问题。

这是代码的架构:在 Activity 的 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 函数才能完成。 onServiceConnected 函数在整个 onCreate 函数完成之前无法执行(因为它们是附加到主循环末尾的事件,并且在当前事件完成之前无法执行),因此系统死锁。

有没有办法强制处理 UI 线程上的其他事件,或者有更好的方法来编排代码?我试图避免每次同时调用这两段代码时都运行 AsyncTask,因为这需要向调用代码公开线程要求。然而,这很困难,因为您不能强制服务连接回调在它们自己的线程中执行。欢迎提出任何建议。

最佳答案

看起来您需要的是在第一个和第二个函数都完成后立即在 UI 线程上执行第三个函数。那么为什么不使用 AsyncTask 并将第一个和第二个例程放在 doInBackground() 而将第三个例程放在 onPostExecute()

关于Android onCreate 死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20335499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com