Search code examples
androidandroid-servicerunnable

Runnable vs Service; Lifespan explained with use-cases


As I understand - both Runnable and Service are intended to run piece of code in background. My code structure is this:

  1. BaseManager.class which is implemented as Singleton and using BaseManager.getInstance() will return single instance in application. Also, when first initialized it automatically creates SmallerAndCompletelyDifferentManager.class - has a dependency.

  2. SmallerAndCompletelyDifferentManager.class - creates a Runnable that runs every 2 seconds.

Now, I've two scenerios:

SCENERIO A: I create initialize BaseManager.class in Activity first and use it wherever I need. The Runnable that is inside SmallerAndCompletelyDifferentManager.class runs okay, but as I understand is attached to Activity - if Activity dies, so will the Runnable which I can not afford.

SCENERIO B: I create a foreground service and initialize BaseManager.class. Does this mean that now the Runnable will work as intended - even if application is in background and Activity has been destroyed?

Am I getting this right or no? The overall plan is to make sure that Runnable survives in background at all costs.


Solution

  • As I understand - both Runnable and Service are intended to run piece of code in background

    This is not correct.

    Service is an application component that can be perform long-running operations in the background. Here background means you do something behind the scene (or background) when users interact with the app, or when users switch to another apps.

    Runnable is a block of code that can be run, that why it has the name "Runnable", it means something can be run/execute. The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

    In Android there a two types of thread, the first one is main/UI thread and another one is background thread. Here background means when you do something in a thread rather than main/UI thread.

    Back to your case

    In scenario 1: The Activity creates Runnable and keep a reference to it. When you destroy the activity (by press Back button or call finish() method), the activity will be destroyed, and the runnable will be released.

    In scenario 2: The foreground service creates Runnable and keep a reference to it. When you destroy activity or switch to another apps, the service is still alive (and runnable as well) until you kill service by calling (stopSelft() or stopService() method). Because when using a foreground service, it will tell the system that the app is doing something important and it shouldn’t be killed.