Q:

Android - Background service stops when its invoker activity is destroyed

I have an always-running background service, started on my MainActivity. The problem is, when MainActivity is destroyed, my service gets restarted. This scenario is the only one in which the service stops, so the "always-running" thing is working well.
I would like to know why this is happening, and what I could do to prevent it.
My service is not bound to my activity, because I don't need it.
The service:
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener {

    ...
    public LocationService() {

    }

    @Override
    public void onCreate() {

        // Some initialization logic here
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return START_STICKY;
    }

    ...
}

MainActivity:
public class MainActivity extends BaseActivity {

    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Start location service in background
        Intent intent = new Intent(this, LocationService.class);
        startService(intent);
    }
}

Thanks in advance! :D

A:

I'm guessing because I don't have enough data. When your MainActivity is destroyed, the OS process hosting your application has no active activities in it, just your Service. Android recognizes that the process isn't hosting any live activities, so it kills the process to free resources. Since your Service returned START_STICKY, Android then schedules your Service for a restart. The Service gets reinstantiated in a new OS process.
You could run your Service in a separate OS process to test this theory. Just add
android:process=":remote"

to the manifest entry for the <service>. This may have other implications on your application, so be sure you understand that.
In any case, Android will randomly kill OS processes that host only services, even if they returned START_STICKY. There isn't any way to prevent that, especially on low-end devices with limited resources. It is Android's way of cleaning house ;-)

