androidkotlinforeground-service

how to run a service with a progress screen on top of main application screen in Kotlin


I need to run a Splash screen or Progress Bar Screen while the Main Application Loads.

And when ever the Main Application changes of screen show the Progress Bar Screen while it loads.

I looked around and found that I can not have two UI threads in the Kotlin Application so maybe I can call a service to run a parallel UI Thread. The regular Splash Screen does not suffice because is use only at the start of the application. Also found the Application can call own services but they appear to be background jobs only not a top Screen.

I do not need the user to interact with the Splash/Progress Screen only to appear at the top and close when the Main Screen finish loading.

Can you direct me to a code sample application with that or similar feature?


Solution

  • The idea of a splashscreen is to bridge the time that your app needs to load, so it only works up until the app is loaded (the splashscreen has no program code, only a configuration so it can be run by the Android system). Anything after that must be handled by your app code.

    You are right that there is only one UI thread, but you are wrong assuming that that poses a problem. The soluion is not to try some trickery with additional processes, the solution is to properly use the single UI thread as it is.

    Whenever your UI needs to wait for some data to be loaded, don't block the UI thread until the data is available, just suspend and launch a new coroutine on the main thread that displays the desired progress bar. When you use Compose it can be as simple as having a State object that you can use to differentiate the cases where you are still waiting for data (e.g. Loading) and when the data is loaded (e.g. Success). Then display a CircularProgressIndicator() (or whatever you want) for Loading and your regular screen for Success.

    The key here is to make sure all your code is main-safe, then you can easily run multiple things concurrently on the single UI thread.