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 OverflowBackground 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
Use a Started service to run code in the background even when the app is killed. Use a Timer and Timer task to run your location gathering code at specified intervals.
Timer example
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {}
}, 0, 1000);
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.
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.
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.
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.
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.
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
Since Android 4.0, the OS has gotten much more agressive about killing off unnecessary processes. If you need to track the user's location even when your app is in the background, then you need to declare your service as a foreground service. This raises the priority of your service so that Android is unlikely to kill it unless it really needs the resources. See Running a service in the foreground for details about how to do this.
location processor code can be written as a service, so that the service will not be killed
There is nothing can guarntee that the service will never be killed, however you can increase the likelihood that your service will continue running by obtaining WakeLock and start it as Foreground service
I would recommend you check few open source projects such as Open GPS Tracker and Traceper
You can use the HyperTrack SDK to get the location updates in the background. Get more insight about the reliability of SDK here in different conditions.
First Setup the SDK
After setting up the SDK you just need to set the Callback to receive the location updates.
HyperTrack.setCallback(new HyperTrackEventCallback() {
@Override
public void onEvent ( @NonNull final HyperTrackEvent event){
switch (event.getEventType()) {
case HyperTrackEvent.EventType.LOCATION_CHANGED_EVENT:
Log.d(TAG, "onEvent: Location Changed");
HyperTrackLocation hyperTrackLocation = event.getLocation();
LatLng latLng = hyperTrackLocation.getLatLng();
updateCurrentLocationMarker(event.getLocation());
break;
}
}
}
(Disclaimer: I work at HyperTrack.)
/**Check out my Github post i did the same for Taxi clone**/
Link ---> https://github.com/yash786agg/GPS/
Note: Remember to remove or comment the below mentioned code if you want the latitude
and latitude even when the application is in background.
if(networkUtilObj != null)
{
networkUtilObj.disconnectGoogleApiClient();
}
Generally speaking, yes, it should be possible.
On Android, this is generally possible using a Broadcast Reciever (and see the information there regarding getting user's location up from API 28).
On iOS, this is specifically possible using the Standard Location Service (specifically refer to the section "Getting Location Events in the Background").
Focusing on React Native, then again - focusing on Expo, there is a recent post discussing just that:
The best way of tracking location in background using react-native + Expo in 2020. However, the comments there indicate that it doesn't work consistently.
Therefore, since I understand you don't specifically require using Expo (you just say "ideally in Expo" :), you can try following this React Native tutorial (June 2021): React Native background location (background & terminated app) (it uses react-native-location library).
It seems that this could be exactly what you're looking for:
React Native — Background Location Tracking without Timeout and with App killed
https://itnext.io/react-native-background-location-tracking-without-timeout-and-with-app-killed-3dbfbc80ad01