1

Hi I have one activity and one service class from activity am starting service in one point i want to start service but at same point i want to check that service is already running if yes then i dont want to call start service if not then i will strat but my problem is that how i will get to know that service is running or not?

i used below code but it not working for me is any other code which will help me out

  private boolean isServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager
            .getRunningServices(Integer.MAX_VALUE)) {
        if ("TimerService".equals(service.service.getClassName())) {
            Toast.makeText(getApplicationContext(), "running", 100).show();
            return true;

        }
    }
    Toast.makeText(getApplicationContext(), "not running", 100).show();
    return false;
}

this code always show me not tunning even if it is running

1 Answers1

1

You don't need to check whether it's running or not. Both startService() and stopService() will handle the corresponding states, so if you call startService() and your Service was already running, nothing will happen (it will just keep running). The same goes to stopService().

nKn
  • 13,691
  • 9
  • 45
  • 62
  • i need to check once again cause when am calling start service 2 times it restart the countdown timer from 60 sec (60 sec is my limit of counter) i called countdown timer code in my service – Android is everything for me Mar 24 '14 at 19:35
  • 1
    Have a look at this, this will probably help you: http://stackoverflow.com/questions/10739413/how-to-prevent-service-to-run-again-if-already-running-android – nKn Mar 24 '14 at 19:39
  • thanks i got conclusion from your provided link as well as i saw one more link http://stackoverflow.com/questions/8019899/starting-a-service-multiple-times from this link i get to know that we can call service as many time no worry only thing that the onStartCommand() from service will be call multiple time(i.e how many times we start the service) and unfortunatly my timer related code was in it so am moving that code from onStartCommand() to onCreate () method thanks for your help – Android is everything for me Mar 24 '14 at 19:44