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?

有帮助吗?

解决方案 2

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

其他提示

Actually there is no special single method to get you notified about all of your service connection event. However I hope you are using ServiceConnection.onServiceConnected() in you binding to services. Introduce a new method to your class waitForConnectingAllServices() which will wait() until someone notify()'s him. You can use onServiceConnected() method from ServiceConnection class. Keep an static variable which will count how many services it is already connected to. And whenever it gets connected to all required services, it will notify the function that is waiting for this happen.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top