2

I have written different flavors for my application and I have a service which I would like to run for just one of these.

How I could implement it?

guipivoto
  • 18,327
  • 9
  • 60
  • 75
  • Have you checked [this](https://stackoverflow.com/questions/24119557/android-using-gradle-build-flavors-in-the-code-like-an-if-case)? – Piyush Jun 17 '19 at 12:29

1 Answers1

2

Solution 1

if("debug".equals(BuildConfig.FLAVOR) {
    // Start service A
} else if ("release".equals(BuildConfig.FLAVOR) {
    // Start service B
}

Or

if("debug".equals(BuildConfig.FLAVOR) {
    // Start service A onfly if using "debug" flavor
}

Solution 2

You can also use the method above to abort the service for specific flavors:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if("debug".equals(BuildConfig.FLAVOR) {
        stopSelf();
    }
    ....
}

Solution 3

Also, you can have different AndroidManifest.xml for different flavors:

Base AndroidManifest.xml

Edit the file at: app/src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest>
    <application>
        ...
        <service android:name="com.test.Service" />
    </application>
</manifest>

Flavor Specific AndroidManifest.xml

Edit/Create file at app/src/FLAVOR_A/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest>
    <application>
        ...
        <service android:name="com.test.Service" android:enabled="true" tools:node="merge"/>
    </application>
</manifest>

This will add the flag android:enabled="true" to FLAVOR_A only.

You can find more info about mergin Manifest files here

guipivoto
  • 18,327
  • 9
  • 60
  • 75
  • when I define a service in manifest, the service starts from the application start and doesn't care to this code. – Mozhgan Hatami Jun 17 '19 at 12:35
  • Could you please share how do you start your service? I'm not sure but just adding it to the manifest does not means it is started automatically...But I'm not sure. For any case, you can use that code above inside your Service. Then, if the wrong flavor is being used, the service finish itself – guipivoto Jun 17 '19 at 12:40
  • *But I'm not sure* - indeed. Services are **not** started automatically – Tim Jun 17 '19 at 12:55