Search code examples
androidandroid-activityandroid-serviceaidl

How to get know when all services are ready


Currently I have an Activity in Android, In the onCreate() I have a function that creates a list of all available MyServices (using aidl) that i have and insert the names etc in an Arraylist.

Still in the Activity in the onStart() I bind all the services and connect to them using a separate class that implements ServiceConnection.

In the onPostCreate() that starts after onStart() and onRestoreInstanceState(Bundle) is called, I immediately (this goes automatic) submit a searchquery to a Class that extends AsyncTask. When connecting to one of the service that handles the searchquery, the service is not available at that moment, the servicelist is always empty in the few seconds when the application is started.

When attaching a debugger, the services are always load and I can't seem to solve the problem.

So my question would be, what method can I use to get notified when all services are loaded and or ready to get queried?


Solution

  • I have solved my problem with the following code, by using Thread.sleep() in in onPostCreate() and then check 5 times if my services are loaded by checking the size of the services Arraylist is not 0

    @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();
    }