Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Running service in background forever

Tags:

android

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?

like image 696
mapodev Avatar asked Sep 13 '25 10:09

mapodev


1 Answers

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.

like image 77
Luis Avatar answered Sep 15 '25 00:09

Luis