Can Android stop a service while app is in foreground?

foreground service
android stop service
android background service example
android background service is restarting when application is killed
android keep service running after app killed
how to run background service continuously in android
android background service always running
android run service in background forever

In my app there is a service started in the first activity's onCreate and I would like to make sure that the service is running as long as the app remains in foreground.

Is it possible that the system stops the service while the app is in the foreground?

I don't think the system is going to unilaterally destroy your Service in this circumstance. That is, I've never seen it do that (but I don't have any references to back that up).

If you had said, "...and the Service is bound to the Activity", I would go even further: "The Service is not going to be destroyed while it is bound," because that would imply sudden calls to onServiceDisconnected(), not prompted by an unbindService().

Services overview, How would you make a service persist even after application is killed? Here, the trick is to create two services that start in the foreground with the same foreground id, then to stop one of the services requesting to remove the notification. The notification will disappear, but the remaining service will continue to run and will remain flagged as a foreground process.

According to the documentation that is a possibility sometimes:

A service process is one holding a Service that has been started with the startService() method. Though these processes are not directly visible to the user, they are generally doing things that the user cares about (such as background network data upload or download), so the system will always keep such processes running unless there is not enough memory to retain all foreground and visible processes. Services that have been running for a long time (such as 30 minutes or more) may be demoted in importance to allow their process to drop to the cached LRU list described next. This helps avoid situations where very long running services with memory leaks or other problems consume so much RAM that they prevent the system from making effective use of cached processes.

(source)

Service class, continue running even when the user isn't interacting with the app. Since the app is already running in foreground, we need not launch the service as a foreground service to prevent itself from being terminated. Note that in onDestroy() we are dedicatedly calling stopService() , so that our overridden method gets invoked.

Best practice here is to use ForegroundService. It is a regular service which calls startForeground() method that ensures the service to be running. It is widely used for example by music players...so as you can figure, nobody likes when system kills music service in middle of a song playing. This should do. More in Service Overview

Pitfalls of a foreground Service lifecycle, A Service is an application component that can perform long-running If you implement this, it is your responsibility to stop the service when its work is complete  The Foreground Service in Android cannot be started without passing a Notification to it! (Creating a Notification is very very important to let the user know there is a service run by the App) Service Lifecycle decides if a Service should be running or not.

First you need to know when to start and stop the service.

Create AppLifeCycleHandler Class

public class AppLifeCycleHandler implements Application.ActivityLifecycleCallbacks, ComponentCallbacks2 {

    private AppLifeCycleCallback appLifeCycleCallback;

    private boolean appInForeground;

    public AppLifeCycleHandler(AppLifeCycleCallback appLifeCycleCallback) {
        this.appLifeCycleCallback = appLifeCycleCallback;
    }

    @Override
    public void onActivityResumed(Activity activity) {
        if (!appInForeground) {
            appInForeground = true;
            appLifeCycleCallback.onAppForeground();
        }
    }

    @Override
    public void onTrimMemory(int i) {
        if (i == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
            appInForeground = false;
            appLifeCycleCallback.onAppBackground();
        }
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle bundle) {

    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }

    @Override
    public void onConfigurationChanged(Configuration configuration) {

    }

    @Override
    public void onLowMemory() {

    }

    interface AppLifeCycleCallback {

        void onAppBackground();

        void onAppForeground();
    }
}

Now inside your public class MyApplication extends Application

Add the following code implements AppLifeCycleHandler.AppLifeCycleCallback

@Override
    public void onCreate() {
        super.onCreate();

        AppLifeCycleHandler appLifeCycleHandler = new AppLifeCycleHandler(this);
        registerActivityLifecycleCallbacks(appLifeCycleHandler);
        registerComponentCallbacks(appLifeCycleHandler);
}

And finally :

    @Override
    public void onAppBackground() {
        Log.d("LifecycleEvent", "onAppBackground");
    }

    @Override
    public void onAppForeground() {
        Log.d("LifecycleEvent", "onAppForeground");
    }

Now last thing you need to do is to create the service,Follow this link create-start-stop-android-background-service And put your start intent and stop intent in the method we just created inside your application class

Building an Android service that never stops running, When running low on memory and needing to kill existing processes, the priority of a process hosting the service will be the higher of the following possibilities:. A service process is one holding a Service that has been started with the startService() method. Though these processes are not directly visible to the user, they are generally doing things that the user cares about (such as background network data upload or download), so the system will always keep such processes running unless there is not enough memory to retain all foreground and visible processes.

Android Services - Tutorial, A Service is an application component that can perform long-running If you implement this, it is your responsibility to stop the service when its  It’s a rule: every Android app has its own logic, context, and behaviors. And the solutions that may apply successfully to certain cases, may not work to others. One of the particular situations

Foreground Service, So what happens when startForeground() isn't called at all? If the ANR interval passed and the app is in the foreground, it will (after ~10 seconds in my android.app. Sometimes we need to stop the Service from within. While an app is in the foreground, it can create and run both foreground and background services freely. When an app goes into the background, it has a window of several minutes in which it is still allowed to create and use services. At the end of that window, the app is considered to be idle.

Hiding foreground services notifications in Android | Blog, Use Android foreground services to build a service that never stops Essentially, they are killed once the app is in background for a while In our case, we want our service to run at a very specific frequency and never be stopped, I'm using Kotlin for this example, so we will be leveraging coroutines and  Due to Android battery optimizations introduced in Android 8.0 (API level 26), background services have now some important limitations. Essentially, they are killed once the app is in background for a while making them worthless for our purpose of running an always-running service.

Comments
  • A service runs on the same thread as the ui, so I don't see a reason to do that.
  • Question: Has the OS ever terminated your service? I doubt it would, as long as the app is in foreground.
  • i was looking for something similar, i will link you my code tomorrow
  • But in my case this process is not a "service process" but a "foreground process" since the app is in foreground, right ? (I assume that the app and the service are running in the same process)
  • how are you starting your service? It could be just semantics, but a Service is held in service processes and those can be foreground or background.