-1

I have a activity that start and stop a service. It seems to be simple but if i start service and stop it it is ok.
But when I restart the service I found two instances of the service.
Why?

 public class Test extends AppCompatActivity implements View.OnClickListener {
       @Override
public void onClick(View v) {
    switch ( v.getId() ) {

        case R.id.InitButton:
        {
            startMonitor();
        }
        break;
        case R.id.EndButton:
        {
            stopMonitor();
        }
        break;
        case R.id.SendData:
        {
            sendData();
        }
        break;
        default:
            break;
    }
}

    ...

  private void startMonitor(){

    Intent intent = new Intent( this, MyService.class );
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |  Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);


    startService( intent );

}

private void stopMonitor(){

    Intent intent = new Intent( this, MyService.class );
    stopService( intent );

}

If I click "initButton" Service start
Then I click "EndButton" and Service end
Then I click "initButton" again and start two services

I see the post suggested but my service is not in running when i stop it in activity

mrpep
  • 131
  • 3
  • 12
  • Possible duplicate of [How to check if a service is running on Android?](https://stackoverflow.com/questions/600207/how-to-check-if-a-service-is-running-on-android) – Zoe Dec 20 '17 at 14:32
  • And for the record, there are two instances because you don't check whether or not an existing is running. There's no limit to the amount of services of a given type you can have (except hardware limits, obviously) – Zoe Dec 20 '17 at 14:34
  • If I stop the service before start it why there is a running services? – mrpep Dec 20 '17 at 14:45
  • The problem persist....I use isMyServiceRunning(Class> serviceClass) and it say NOT RUNNING, but in some way someone instantiate two instance – mrpep Dec 20 '17 at 14:54

1 Answers1

0

I highly suggest to any developer they read about "gang of four". In your case a singleton design ensures only a single instance of a class runs at a time. By defult a started service should only have one instance regardless of how many times it is started. This flag Intent.FLAG_ACTIVITY_NEW_TASK it would appear starts another task even if one is running already. Try removing the flag before making it a singleton, however making the service a singleton would not hurt anything(assuming you want one instance)

Pomagranite
  • 696
  • 5
  • 11