Search code examples
androidservicebroadcastreceiverandroid-serviceandroid-background

Android is killing my service?


with a BroadCastReceiver, I execute a service at the smartphone boot:

public class BootReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    Intent startServiceIntent = new Intent(context, MyService.class);
    context.startService(startServiceIntent);
}
}

MyService:

private Runnable myRunnable = new Runnable() {
    public void run() {
        parsing.cancel(true);
        parsing = new Parsing();
        parsing.execute();
        handler.postDelayed(this, timeoutUpdate);
    }
};

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handler.removeCallbacks(myRunnable);
    handler.postDelayed(myRunnable, 1000); 
   return Service.START_STICKY;
}

The service is really executed at the boot, but if I set a timeout of 1 hour between executions, service is not executed (maybe the system is killing it). Otherwise, if I set 60 sec between repetition, all works. How can I do it? Thanks.


Solution

  • You may run the service in the foreground using startForeground().

    A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory.

    But bear in mind that a foreground service must provide a notification for the status bar (read here), and that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.

    Note: This still does not absolutely guarantee that the service won't be killed under extremely low memory conditions. It only makes it less likely to be killed.

    OR

    If you dont want to run the service in the foreground then you can run service in a periodic intervals using AlarmManager

    Intent intent = new Intent(context, MyService.class);
    PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
    AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pintent);
    

    Update

    Cancel the registered event by using

        Intent intent = new Intent(context, MyService.class);
        PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
        AlarmManager alarm =     (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
       alarmManager.cancel(pintent);