user2582992
user2582992

Reputation: 69

Service restart on starting activity

I'm trying to get Services working in Android. My application can start my service now, but when the service is running in the background and I start my (Main)Activity, the service will restart (the onCreate() and onStartCommand() commands will be called). In my MainActivity I check if the service is already running via the following code:

    if (isServiceRunning()){
        System.out.println("De serice is running");
    }
    else{
        System.out.println("De service is niet running");
        startService(new Intent(this, YourService.class));
    }
...
private boolean isServiceRunning() {
    ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        Log.d("services", service.service.getClassName());
        if ("com.vandervoorden.mijncijfers.YourService".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

When my service is running "De serice is running" is shown in my console.

Why is onCreate() and onStartCommand() called while I didn't restart the service myself? How can I make sure the service isn't start twice when it is already started?

EDIT 1 2013-10-07 8:54 PM:

My service class:

public class YourService extends Service
{
    Alarm alarm = new Alarm();

    public void onCreate()
    {
        super.onCreate();
        System.out.println("service: onCreate");
    }


    public int onStartCommand(Intent intent, int flags, int startId) {
        //alarm.SetAlarm(this);
        System.out.println("service: onStartCommand");
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
}

Upvotes: 1

Views: 768

Answers (1)

Martin Cazares
Martin Cazares

Reputation: 13705

This behavior looks weird only if you are sure you are not destroying your service somewhere in the activity, even so what I usually do to make sure that only one instance of my service is running, is flagging the service itself using a static flag that keeps track of "onCreate" and "onDestroy", this way independently if the activity would like to start my service I have the validations in the service itself.

Hope this Helps.

Regards!

Upvotes: 2

Related Questions