• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Android service is not working after app is closed

I'd like to get the location data in the background.
So I used service. But it stopped when the app closed.

This is my code.
in the manifest.xml

<service
android:name=".services.MyService"
android:exported="true"
android : process=":MyLocationService" />

in the service.java

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

and the main activity I called the startservice.

Intent intent = new Intent(this, MyService.class);
startService(intent);


It works well in the background and foreground of the app, But it stopped when the app closed.
I wanna running service after app is closed.
Thank you.
Regards.

Li.
 
I'd like to get the location data in the background.
So I used service. But it stopped when the app closed.

This is my code.
in the manifest.xml

<service
android:name=".services.MyService"
android:exported="true"
android : process=":MyLocationService" />

in the service.java

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

and the main activity I called the startservice.

Intent intent = new Intent(this, MyService.class);
startService(intent);


It works well in the background and foreground of the app, But it stopped when the app closed.
I wanna running service after app is closed.
Thank you.
Regards.

Li.
The reason why it closes is because it's not needed for particular applications. So if you're trying to run it beyond its normal intent, you can obtain that function in your Android optimization settings. Like most apps it's optimized to run in conjunction with the battery and its usage. Go in onto Settings then battery optimization - Apps, scroll down until you see the service you want to continue to run by clicking on the App then Do not optimize. Note these settings may very on different devices.
 
Try this:

https://stackoverflow.com/questions/43310855/android-service-stops-after-the-app-is-killed/43310945

Code:
@Override
public void onTaskRemoved(Intent rootIntent){
   Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
   restartServiceIntent.setPackage(getPackageName());

   PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
   AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
   alarmService.set(
   AlarmManager.ELAPSED_REALTIME,
   SystemClock.elapsedRealtime() + 1000,
   restartServicePendingIntent);

   super.onTaskRemoved(rootIntent);
 }
 
Back
Top Bottom