Search code examples
androidandroid-servicesplash-screen

How to wait until services stops in Android


Can I wait until my all services stops? I try to make a splashscreen in my android application and I want it to wait until all my services stopped.

ActivityManager manager = (ActivityManager) this
            .getSystemService(ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager
                .getRunningServices(Integer.MAX_VALUE)){
        }

I try this example of code...My problem is that I do not know how to continuously checking this in my splashscreen activity. Or maybe it is not a good solution.


Solution

  • Instead of a normal Service, Use an Intent service, as it automatically stops itself after completing its task.

    Now when this service stops, you may send a Local Broadcast, and receive this Broadcast in your Splash Activity.

    Keep a track of running services, and one which have stopped, you may use flags for this.

    So for example if service A stops itself and sends a broadcast set its flag to true.

    Now on each Broadcast receive check if all flags are true, if Yes, stop the Splash screen and move to next step or else wait for other services to stop.

    Example

    We have three services A, B, C running and corresponding to them we have three flag stopA, stopB, stopC in our Splash Activity.

    Now when A finishes, it sends a local broadcast, which is then received in Splash Activity, now we set the flag of A i.e stopA = true; and check if flags for services B & C are true or not (i.e. if other services have stopped or running)

    If true finish this activity, else wait for other broadcasts.