I am working on a location tracking application. I need to fetch the user location on every 500-meter displacement or in every 30 minutes. I created a foreground service and returned START_STICKY on onStartCommand method. Tracking is working perfectly until the app is cleared from recent apps. If I cleared my app from recent apps section the foreground service also removing from the background. how can I make it sticky there forever?
Note: I am doing this location tracking with the knowledge of user .
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Temp.msg(TAG, "onStartCommand");
startMyOwnForeground();
return START_STICKY;
}
private void startMyOwnForeground() {
String NOTIFICATION_CHANNEL_ID = Temp.getNotificationChannelId();
String channelName = Temp.getNotificationChannelName();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel chan = null;
chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_push_notifications)
.setContentTitle("Checked In")
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(1, notification);
}
Note: I tried START_STICKY and START_NOT_STICKY on onStartCommand method but it both removed from the background when the app removed from recent apps
I found why the app is removing from the background. That was not my code's problem. It happened because the phone I used was Redmi. In Redmi phones, It requires additional permission (AutoStart permission) from Redmi phone settings. You can get more info about this from Foreground service getting killed from Oreo