Bart Friederichs
Bart Friederichs

Reputation: 33511

Start a service once for two apps

I create an app, with two flavors, "full" and "demo". Both define and start a service with a non-cancelable Notification. When I both start "full" and "demo", the service is started twice, which clogs the notification bar.

The service is started like this:

startService(new Intent(this, MyService.class));

Is there a way to not start the service if it was already started by the 'other' app?

Upvotes: 2

Views: 49

Answers (2)

Jaiprakash Soni
Jaiprakash Soni

Reputation: 4112

You can manage it in ways :

  • Check in demo app if service is already start by full, start it if not started by full app and vice versa (Check Katerina's answer).
  • Use Broadcast: Use a Boolean variable(either in shared preference or any static available ) by default make it false. When you are going to start service check this Boolean and send broadcast (from demo to full and vice versa) so that and make this boolean as true in both of your app

Upvotes: 0

Virginia Woolf
Virginia Woolf

Reputation: 1268

You should configure your demo app not to start the service by disabling it in the manifest android:enabled=["true" | "false]" and then define your service as exported android:exported=["true" | "false]" so that it can also be started by your demo app. This way it can be started by both but instantiated only in the full version.

If you want the demo app to also be able to run as a standalone app, you should probably do something different. Check if the service is running already before starting it:

ActivityManager manager=(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);

  for (  RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
    if ("your.package.name".equals(service.service.getClassName())) {
      return true;
    }

Upvotes: 2

Related Questions