Background Service Example Android

Use a Android Service to run code in the background even when the app is killed. Use a BroadcasteReceiver to restart the service when app is killed by user and Android JobService to run your location gathering code at specified intervals.

Try This its working for me getting the location when app is in killed state

Android-Background-Services-Exmaple

https://github.com/surenderkhowal/Android-Background-Services-Exmaple

Answer from Surender Kumar on Stack Overflow
Top answer
1 of 2
1

You should use a Foreground Service with a partial wakelock, in order to prevent the phone from sleeping. Here below an example of Foreground Service Class that implements a Wakelock:

public class ICService extends Service {
    
    private static final int ID = 1;                        // The id of the notification
    
    private NotificationCompat.Builder builder;
    private NotificationManager mNotificationManager;
    private PowerManager.WakeLock wakeLock;                 // PARTIAL_WAKELOCK
    
    /**
     * Returns the instance of the service
     */
    public class LocalBinder extends Binder {
        public ICService getServiceInstance(){
            return ICService.this;
        }
    }
    private final IBinder mBinder = new LocalBinder();      // IBinder
    
    @Override
    public void onCreate() {
        super.onCreate();
        // PARTIAL_WAKELOCK
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"INSERT_YOUR_APP_NAME:wakelock");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        startForeground(ID, getNotification());
        return START_NOT_STICKY;
    }
    
    @SuppressLint("WakelockTimeout")
    @Override
    public IBinder onBind(Intent intent) {
        if (wakeLock != null && !wakeLock.isHeld()) {
            wakeLock.acquire();
        }
        return mBinder;
    }
    
    @Override
    public void onDestroy() {
        // PARTIAL_WAKELOCK
        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
        }
        super.onDestroy();
    }

    private Notification getNotification() {
        final String CHANNEL_ID = "YOUR_SERVICE_CHANNEL";

        builder = new NotificationCompat.Builder(this, CHANNEL_ID);
        //builder.setSmallIcon(R.drawable.ic_notification_24dp)
        builder.setSmallIcon(R.mipmap.YOUR_RESOURCE_ICON)
            .setColor(getResources().getColor(R.color.colorPrimaryLight))
            .setContentTitle(getString(R.string.app_name))
            .setShowWhen(false)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .setOngoing(true)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setContentText(composeContentText());

        final Intent startIntent = new Intent(getApplicationContext(), ICActivity.class);
        startIntent.setAction(Intent.ACTION_MAIN);
        startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        startIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 1, startIntent, 0);
        builder.setContentIntent(contentIntent);
        return builder.build();
    }
}

Obviously you still have also to disable battery optimization for your app. You can browse a real working example of this service on a GPS Logging app here.

Don't forget to declare your service type as "location" into your AndroidManifest.xml, in order to allow your application to receive the GPS updates also after a momentary signal loss when running in background, and to add the FOREGROUND_SERVICE and WAKE_LOCK permissions:

In your manifest you should declare:

    ...
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    ...
    <!-- Recommended for Android 9 (API level 28) and lower. -->
    <!-- Required for Android 10 (API level 29) and higher. -->
    <service
        android:name="MyGPSService"
        android:foregroundServiceType="location" ... >
    </service>
    ...

As a note, if the location requests start when the app is in the foreground, you don't need to request the android.permission.ACCESS_BACKGROUND_LOCATION permission to continue to receive locations in background, also in case of momentary signal loss.
the android.permission.ACCESS_FINE_LOCATION (and, if you target API31, also android.permission.ACCESS_COARSE_LOCATION) is enough for your use.

2 of 2
0

You need to keep a foreground service always running. You need to start it when the app is in the foreground and then keep it running all the time even when the app is in the background.

🌐
ITNEXT
itnext.io › react-native-background-location-tracking-without-timeout-and-with-app-killed-3dbfbc80ad01
React Native — Background Location Tracking without Timeout and with App killed | by Sourav | ITNEXT
February 10, 2024 - Keep a service running when the app is killed — without disabling battery optimisation · Access the device GPS every 10 seconds even when the app is killed— The React-Native Geolocation Library kept timing out after every 30–45 seconds ...
🌐
Medium
medium.com › @jaypanchal4498 › fetching-location-even-after-app-killed-is-possible-using-flutter-this-is-how-i-did-it-ea9ecb738bdd
Fetching location even after app killed is possible using Flutter? This is how i did it.. | by Jay Panchal | Medium
June 27, 2024 - Where we will first take request all necessary permissions from the user and then we will call the method channel to start the service and our native code will do its magic!! And We are done…. And thats how we will be able to check the continuous updated notifications with live location updates even when our flutter app is killed. Anyone can checkout full code available here on given link: ... I am a motivated and enthusiastic Android and Flutter developer creating high-quality mobile applications.
🌐
Dactyl Group
dactylgroup.com › en › tips-for-android
Android: How to track location in the background and not to get killed?| Dactyl Group | DactylGroup
September 14, 2021 - Thanks to the combination of more than one position provider was the positioning process much faster and even more stable and more accurate. The settings of LocationRequest for the Provider gives you many parameters. The Provider provides you four modes. After their definition will the location be distributed to the onLocationResult callback. There were interesting results from a power-saving PRIORITY_LOW_POWER in the cities. It provides, thanks to using mobile BTS positions, satisfactorily determine the position of a user.
🌐
Stack Overflow
stackoverflow.com › questions › 58439891 › how-to-get-frequent-location-in-android-even-when-the-app-is-in-background-or-ki
How to get frequent location in Android even when the App is in background or killed? - Stack Overflow
can you try something like this Location locationGPS = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Location locationNet = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); instead of the broadcast ...
🌐
Microsoft
social.msdn.microsoft.com › Forums › en-US › bf9d956b-2704-4038-9a63-6cf7a4d16fb2 › will-i-get-current-location-of-user-when-app-is-killed
Will I get current location of user when app is killed? | Microsoft Learn
August 22, 2020 - send the remote notification(such as firebase, you know firebase just depend on the Google play service, if Google play service is stop, you still cannot get the firebase message) in your android OS, when you push this notification, you application ...
Top answer
1 of 3
11

Oppositely to what @sven-menschner said, I think an unbound Service is exactly what you need, as bound services are subject to bind/unbind mechanisms that would kill your service. That's what I would do:

In your Manifest file, define your service:

<service
  android:name=".YourService"
  android:enabled="true"
  android:exported="true"
  android:description="@string/my_service_desc"
  android:label="@string/my_infinite_service">
  <intent-filter>
    <action android:name="com.yourproject.name.LONGRUNSERVICE" />
  </intent-filter>
</service>

Note: There's a list of already implemented actions, but you can define your own actions for the intent to launch the service. Simply create a singleton class and define the strings assigning them a String that should be unique. The "enabled" set to true is just to instantiate the service, and exported set to true is just in the case you need other applications sending intents to your Service. If not, you can safely set that last to false.

The following step would be starting your service from your activity. That can be easily done by:

public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent servIntent = new Intent("com.yourproject.name.LONGRUNSERVICE");
    startService(servIntent);

    ...
  }
}

The final step is to define your Service initializations. Keep an eye on the onBind() method. Since you don't want it to be bound, simply return null. It would be something like this:

public class MyService extends Service {
  @Override
  public IBinder onBind(Intent intent) {
    // This won't be a bound service, so simply return null
    return null;
  }

  @Override
  public void onCreate() {
    // This will be called when your Service is created for the first time
    // Just do any operations you need in this method.
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
  }
}

Now your service will run even if you close your main Activity. There's just one step left: To help your Service not being finished, run it as a foreground service (do that within your Service). This will basically create a notification icon in the status bar. This doesn't mean your main Activity is running too (this is why you don't want a bound service), as Activities and Services have different life-cycles. In order to help that Service run for so long, try keeping your heap as low as possible so it will avoid the Android SO killing it.

One more acclaration: You cannot test whether the Service is still running killing the DVM. If you kill the DVM, you'll killing everything, thus also the Service.

2 of 3
2

There are two kinds of Android Services: started and bound. You need to use the first one(started Service). The documentation shows how to use it, there is a nice lifecycle diagram below.

Instead of starting and binding the service in one step using bindService() you need to call startService() first. However startService() won't help you starting from Oreo. You need to usestartForegroundService() from there. Then it runs until you stop it, even if the app is closed.

Start Sticky Service if you want Android OS to pick your service again if it killed it.

Find elsewhere
Top answer
1 of 2
1

Oppositely to what @sven-menschner said, I think an unbound Service is exactly what you need, as bound services are subject to bind/unbind mechanisms that would kill your service. That's what I would do:

In your Manifest file, define your service:

<service
  android:name=".YourService"
  android:enabled="true"
  android:exported="true"
  android:description="@string/my_service_desc"
  android:label="@string/my_infinite_service">
  <intent-filter>
    <action android:name="com.yourproject.name.LONGRUNSERVICE" />
  </intent-filter>
</service>

Note: There's a list of already implemented actions, but you can define your own actions for the intent to launch the service. Simply create a singleton class and define the strings assigning them a String that should be unique. The "enabled" set to true is just to instantiate the service, and exported set to true is just in the case you need other applications sending intents to your Service. If not, you can safely set that last to false.

The following step would be starting your service from your activity. That can be easily done by:

public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent servIntent = new Intent("com.yourproject.name.LONGRUNSERVICE");
    startService(servIntent);

    ...
  }
}

The final step is to define your Service initializations. Keep an eye on the onBind() method. Since you don't want it to be bound, simply return null. It would be something like this:

public class MyService extends Service {
  @Override
  public IBinder onBind(Intent intent) {
    // This won't be a bound service, so simply return null
    return null;
  }

  @Override
  public void onCreate() {
    // This will be called when your Service is created for the first time
    // Just do any operations you need in this method.
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
  }
}

Now your service will run even if you close your main Activity. There's just one step left: To help your Service not being finished, run it as a foreground service (do that within your Service). This will basically create a notification icon in the status bar. This doesn't mean your main Activity is running too (this is why you don't want a bound service), as Activities and Services have different life-cycles. In order to help that Service run for so long, try keeping your heap as low as possible so it will avoid the Android SO killing it.

One more acclaration: You cannot test whether the Service is still running killing the DVM. If you kill the DVM, you'll killing everything, thus also the Service.

2 of 2
0

You can use foreground service instead of service.

https://www.truiton.com/2014/10/android-foreground-service-example/

or You can use WorkManager instead of Service.

https://medium.com/@prithvibhola08/location-all-the-time-with-workmanager-8f8b58ae4bbc

🌐
Android Developers
developer.android.com › core areas › sensors and location › request location updates
Request location updates | Sensors and location | Android Developers
June 2, 2023 - This document explains how to request regular updates about a device's location using the Fused Location Provider's requestLocationUpdates() method in Android.
🌐
Stack Overflow
stackoverflow.com › questions › 75209560 › running-a-location-service-in-the-background-even-when-the-app-is-killed-and-res
android - Running a Location Service in the Background even when the app is killed and restarting when device location changes - Stack Overflow
How can I create a location tracking service in Android that runs in the background, even when the app is completely killed? The service should start whenever the device's location changes by 100 meters and should stop if the device is stationary.
🌐
GitHub
github.com › intuit › LocationManager › issues › 86
Will I get current location even if the app is killed or terminated ? · Issue #86 · intuit/LocationManager
October 27, 2016 - Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Author   intuit
🌐
Stack Overflow
stackoverflow.com › questions › 48878714 › gps-location-not-getting-updates-when-app-is-killed
android - GPS location not getting updates when app is killed - Stack Overflow
February 20, 2018 - Job scheculer is running successfully even if the app is killed and it gets the location coordinates , but problem is they remain the same even if the location has changed , but if app is running and is not killed then location is updated even ...
🌐
GitHub
github.com › codepath › android_guides › issues › 220
A good example of background service getting location updates · Issue #220 · codepath/android_guides
September 29, 2016 - Please I really need help. I'm facing a problem here. It is impossible to find A GOOD EXAMPLE of how create a service that must run in background and receive location updates. Also, all example...
Author   codepath
🌐
Stack Overflow
stackoverflow.com › questions › 69885435 › how-can-i-get-users-location-when-app-is-in-background-or-killed-in-android-and
How can I get user's location when app is in background or killed in android and ios both platforms using react native? - Stack Overflow
I am working on an app that tracks driver's location to show on user's map but I am having some difficulties in tracking driver's location when app is in background or killed. I have tried: https://