0

My application run a service on startup (Service.java). I need to know when you start the application manually (in the Main.java) if my service is still running. Following my code on Main.java in onCreate:

if(isMyServiceRunning(Service.class)){
   System.out.println("Still running");
}

isMyServiceRunning function:

private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
}

The problem is that isMyServiceRunning returns false even if the service is still running! How to solve it?

Bob
  • 436
  • 5
  • 13

1 Answers1

1

Instead of using that approach, I'll create a boolean member in the application object with getter/setter. In service onCreate() you'll set the flag, and then you can query that flag from any point inside your activity.

In your application object class (assumed to be MyApplication.java):

private boolean serviceRunning = false;

public boolean isServiceRunning() {
    return serviceRunning;
}

public void setServiceRunning(boolean serviceRunning) {
    this.serviceRunning = serviceRunning;
}

Then, inside service's onCreate():

((MyApplication)getApplication()).setServiceRunning(true);

Then, to check the state of the service from any point in your activity:

if(((MyApplication)getApplication()).isServiceRunning()){
    //do the stuff here
}

Hope it helps.

Junior Buckeridge
  • 2,075
  • 2
  • 21
  • 27