2

I have a service and I need to check if it's still running after some time from a static context. [I noticed this happens only on Android KitKat]

What I did:

My service:

public class Servizio extends Service {

   public static Service servizio;

   [...Other things...]

   @Override
   public void onCreate() {
   super.onCreate();
   servizio = this;
      scheduleMyAlarmToDoSomethingAfterSomeTime();

   }

[...Other things...]
}

Then I launch the service from the main Activity in onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    [...]
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ServizioUtility.toggleService(this, true);
    [...]
}

Then I check if it's null after a minute (with an alarm receiver whose alarm was launched by the service. Note that the receiver works fine and the following code is called):

if (Servizio.servizio!=null) {// FIXME
    [...]
    //THIS IS NOT CALLED IN THE 2ND SCENARIO
}

There are 2 scenario:

  1. I run the activity, wait for the alarm to be launched and Servizio.servizio is not null.
  2. I run the activity, "kill" it using the enter image description here , wait for the alarm receiver to be called, Servizio.servizio is now null. Note that the service, on the other hand, is still running (checked from Settings->App->Running menu).

What's happening in the 2nd scenario?

Angelo Tricarico
  • 1,333
  • 1
  • 19
  • 36
  • See similar question (with solution) http://stackoverflow.com/q/20636330/624109 – Muzikant Jan 20 '14 at 13:15
  • Service may appear to be running in Settings->Apps->Running, but it's actually not running. You can check by having service write a file to SD or actually check running processes. Its not running. – 3c71 Jan 20 '14 at 13:16
  • Yes, it appears but it isn't, in fact the service singleton is null. – Angelo Tricarico Jan 20 '14 at 14:53

2 Answers2

2

I found out this is an issue with Android KitKat, if you want to check it out:

https://code.google.com/p/android/issues/detail?id=63793

https://code.google.com/p/android/issues/detail?id=63618

Angelo Tricarico
  • 1,333
  • 1
  • 19
  • 36
2

My simple workaround:

It sets the alarm with a 1 sec delay and stops the service by calling stopForeground().

@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
    if (Build.VERSION.SDK_INT >= 19) {
        Intent serviceIntent = new Intent(this, MessageHandlerService.class);
        serviceIntent.setAction(ACTION_REFRESH);
        serviceIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        manager.set(AlarmManager.RTC, System.currentTimeMillis()+1000, PendingIntent.getService(this, 1, serviceIntent, 0)); //1 sec delay
        stopForeground(true); 
    }
}