mapodev
mapodev

Reputation: 988

Android: Running service in background forever

I don't know why, but my Service ( started with startService(Intent...) ) keeps closing after a while. I want my Service to check every 2 minutes the position with WiFiSLAM, therefore a TimerTask is running in the Service. I realized that my Service is shutting down after the App is closed (onDestroy) and the screen turned off.

I've read about the WakeLock and tried this:

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakeLock.acquire();

But it still does not work. I don't know what to do. I just want to have my Wifi Positioning Framework to update the position in the background every two minutes.

I also set the return value of onStartCommand() to START_STICKY. Maybe it is running in the background, but I can't see the Logs in the LogCat when it is running for a while, which gives me signals that the indoorLocationManager is still catching new positions.

Someone has an idea?

Upvotes: 4

Views: 4026

Answers (3)

Patrick Jackson
Patrick Jackson

Reputation: 19446

One solution is to use an alarm that launches you service at two minute intervals, or whatever you decide. However doing this will drain the battery, so keep that in mind.

Upvotes: 0

Luis
Luis

Reputation: 12058

Android automatically kills applications running in background for long periods (between 30 minutes and 1 hour).

The only way to prevent this is setting your service as foreground service.

To do that, you use the following:

    startForeground(messgae, notification);

This will show a permanente notification informing the user that your service is running.

Other option, is to use AlarmManager to start an IntentService every 2 minutes.

Regards.

Upvotes: 4

Matt Clark
Matt Clark

Reputation: 28629

I have in the past had the ame problem, and you may not want to do this, however it does work for me. I set up 2 Services, the main worker, and a helper. The helper, every so often will make sure the worker is running, and the worker will ensure that the helper stays running. In this example, if one of them happens to get killed by the system, it will be relaunched by the other. I have never had both of them die at the same time.

Again, this is my solution that may not be something that you would like to do.

Upvotes: 0

Related Questions