KitKat: Service is null after exiting main activity

我的梦境 提交于 2019-12-11 03:43:53

问题


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

    , 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?


回答1:


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




回答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); 
    }
}


来源:https://stackoverflow.com/questions/21073136/kitkat-service-is-null-after-exiting-main-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!