Blind Despair
Blind Despair

Reputation: 3295

Application starts new service when app is closed

I have an android app with service that has to track user's location even with closed application only if user set flag in app. So I start service in code after user clicks button and stop when he clicks it again with following code

alarm.changeAlarmStatus();
            if(alarm.getAlarmStatus()) {
                SharedPreferences.Editor ed = alarmPreferences.edit();
                ed.putFloat("MARKER_LATITUDE", (float) theMarker.getPosition().latitude);
                ed.putFloat("MARKER_LONGITUDE", (float) theMarker.getPosition().longitude);
                ed.commit();
                startService(myIntent);
            }
            else{
                stopService(myIntent);
            }

It seems to work fine. Service works and does what it should. But problem is if I close application through the task manager I see in logcat that Service starts again(but only if service is already working) and it causes nullPointerException because intent is null. You can see in this code why it happens

public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    Bundle bundle = intent.getExtras();
    alarm = (Alarm) bundle.getSerializable("alarm");
    Log.d("service","On Start Command is called ");
    serviceIntent = intent;
    return START_STICKY;
}

However I need to start my service only by pressing button and no other way. Does anyone know how to fix that?

Upvotes: 0

Views: 1717

Answers (1)

L. Kolar
L. Kolar

Reputation: 555

Return START_NOT_STICKY in onStartCommand instead of START_STICKY.

If START_STICKY is returned, system will try to re-create service after it is killed.

If START_NOT_STICKY is returned, system will not try to re-create service after it is killed.

Upvotes: 3

Related Questions