【问题标题】:How to get know when all services are ready如何知道所有服务何时准备就绪
【发布时间】:2013-09-19 01:10:22
【问题描述】:

目前我在 Android 中有一个 Activity,在 onCreate() 中我有一个函数可以创建我拥有的所有可用 MyServices(使用aidl)的列表,并将名称等插入到 Arraylist 中。

仍然在 onStart() 的 Activity 中,我绑定所有服务并使用实现 ServiceConnection 的单独类连接到它们。

在调用 onStart() 和 onRestoreInstanceState(Bundle) 之后开始的 onPostCreate() 中,我立即(这会自动)向扩展 AsyncTask 的类提交搜索查询。当连接到处理搜索查询的服务之一时,该服务此时不可用,服务列表在应用程序启动的几秒钟内始终为空。

附加调试器时,服务总是加载,我似乎无法解决问题。

所以我的问题是,当所有服务都已加载或准备好接受查询时,我可以使用什么方法来获得通知?

【问题讨论】:

    标签: android android-activity android-service aidl


    【解决方案1】:

    实际上,没有一种特殊的方法可以通知您所有服务连接事件。但是我希望您在绑定到服务时使用ServiceConnection.onServiceConnected()。向您的班级 waitForConnectingAllServices() 引入一个新方法,它将 wait() 直到有人 notify() 成为他。您可以使用 ServiceConnection 类中的onServiceConnected() 方法。保留一个静态变量,该变量将计算它已经连接到的服务数量。并且每当它连接到所有必需的服务时,它都会通知正在等待这种情况发生的函数。

    【讨论】:

    • 您好,感谢您的回答,但我使用了另一种解决方案,请参阅下面的帖子。
    • 我建议使用等待通知协议,该协议更适合此类任务。您使用了睡眠-唤醒检查,如果它符合您的目的,那就太好了:)
    【解决方案2】:

    我已经用下面的代码解决了我的问题,通过在onPostCreate() 中使用Thread.sleep(),然后通过检查服务的大小Arraylist 不是 0 来检查我的服务是否已加载 5 次

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        initDrawer();
        int count = 0;
        boolean mServicesReady = false;
        boolean mPluginAvailable = false;
        //to load the plugin correctly we have to let the thread sleep for 3 seconds
        do {
            if(count == 0){
                try{
                    Thread.sleep(3000);
                }catch(InterruptedException e){
                    Log.e(TAG, e.getMessage());
                }
            }
            if(services.size() > 0){
                mServicesReady = true;
                //do something more
            }else if(services.size() == 0){
                //there are no services, throw a dialog that there are no services available
                mServicesReady = false;
                if(!mPluginAvailable)
                noPluginAvailable();
    
                mPluginAvailable = true;
            }
    
            count++;
        }while((!mServicesReady) && (count < 5));
    
        mDrawerToggle.syncState();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 2012-07-31
      • 2023-03-11
      • 2019-09-01
      • 2015-11-07
      • 1970-01-01
      • 2018-03-11
      相关资源
      最近更新 更多