I am using Gradle with Product flavors where I set a different package name for each one.
productFlavors {
appone {
packageName "com.dg.app1"
}
apptwo {
packageName "com.dg.app2"
}
appthree {
packageName "com.dg.app3"
}
appfour {
packageName "com.dg.app4"
}
}
I need to be able to replace the package name inside the manifest for each corresponding app.
My manifest has this:
<receiver android:name="com.parse.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.dg.example" />
</intent-filter>
</receiver>
So I need to replace com.dg.example for each app flavor's package name. What is the best way to do this?
Gradle Plugin v0.12 and higher:
Use ${applicationId} instead of ${packageName}.
Gradle Plugin v0.11 and higher:
As of v0.11, you no longer need to specify not to use the old manifest merger.
Gradle Plugin v0.10 and higher:
Assuming you're using version 0.10 or higher, this is now officially supported:
buildscript {
repositories {
mavenCentral()
}
dependencies {
// Make sure this is at least 0.10.+
classpath 'com.android.tools.build:gradle:0.10.+'
}
}
As of v0.10, you'll also have to manually enable the new manifest merger, although I'd expect that requirement to go away in a version or two whenever the new merger becomes the default:
android {
useOldManifestMerger false
}
Then, just use ${packageName} anywhere in AndroidManifest.xml that you would normally hardcode the package name. For example:
<category android:name="my.package.name"/>
would become
<category android:name="${packageName}"/>
Gradle Plugin v0.9 and below:
So, referencing this post, it appears this is not yet officially supported through Gradle. A simple workaround is the following:
Replace the package name with a custom tag (e.g. <category android:name="my.package.name"/> becomes <category android:name="_PACKAGENAME_"/>
Add the following to your build.gradle, under the android scope:
applicationVariants.all { variant ->
// After processing the manifest, replace all instances of your tag
// with the variant's actual package name.
variant.processManifest << {
def manifestOutFile = variant.processManifest.manifestOutputFile
def newFileContents = manifestOutFile.getText('UTF-8').replace("_PACKAGENAME_", variant.packageName)
manifestOutFile.write(newFileContents, 'UTF-8')
}
}
To do something like this, I use buildTypes in my gradle file but I am pretty sure this will work with flavours as well. For me I am trying to set the label field in the activities.
I have a strings xml file for each of my buildTypes.
Then I have a sourceSet for each buildType which includes the correct strings file.
Then in the manifest I do not use a hard coded string but rather "#string/my_var" which will pull the correct string depending on how the sourceSets are defined.
This google+ post and related gist may help.
Something else to do is to put a AndroidManifest.xml file into the src/flavour which only contains the bits which are relevant to each flavour. Then take those bits out of the main manifest file. At build time the Manifest files will be merged into one file. You can see the result all of the merged manifests in build/manifests.
I had the same problem and implemented a placeholder replace method in Gradle. It does exactly what you'd expect but also takes care about packageNameSuffix attributes so you can have debug and release as well as any other custom builds on the same device.
applicationVariants.all { variant ->
def flavor = variant.productFlavors.get(0)
def buildType = variant.buildType
variant.processManifest.doLast {
println '################# Adding Package Names to Manifest #######################'
replaceInManifest(variant,
'PACKAGE_NAME',
[flavor.packageName, buildType.packageNameSuffix].findAll().join()) // ignores null
}
}
def replaceInManifest(variant, fromString, toString) {
def flavor = variant.productFlavors.get(0)
def buildtype = variant.buildType
def manifestFile = "$buildDir/manifests/${flavor.name}/${buildtype.name}/AndroidManifest.xml"
def updatedContent = new File(manifestFile).getText('UTF-8').replaceAll(fromString, toString)
new File(manifestFile).write(updatedContent, 'UTF-8')
}
I have it up on a gist too if you want to see if it evolves later.
I found to be a more elegant approach than the multiple resources and XML parsing approaches.
Option Gradle:
Use grade attributes API. Some thing like this
manifest.attributes(["attr1":"value1", "attr2":"value2"])
Option 1
How about converting your project to Android - library project, and making extra project for each company. Than you can edit the Manifest file as you wish.
Option 2
Write a batch file.
Related
I do have a structure like below. I wanna use different manifestPlaceHolder like this, projectXTest, projectXDev, projectXProd all use different manifestPlaceHolder while projectYTest,Prod,Dev uses the same manifestPlaceHolder. What I can do besides putting that values to string.xml for all different flavors
android {
buildTypes{
debug{
// Some debug setup
}
release{
// Some release setup
}
}
flavorDimensions "project" , "default"
productFlavors {
projectX{
dimension 'project'
}
projectY{
dimension 'project'
}
Test{
dimension 'default'
}
Dev{
dimension 'default'
}
Prod{
dimension 'default'
}
}
}
Since I could find an out of this. I followed this steps. I hope, If somebody find her/himself in this situation, this helps.
Firstly
Put a manifest to desired flavors directory, for my example I've put android manifest to src/projectY and src/projectX
Beware these not to be full manifest. It should be layered like below
<manifest>
<application>
<activity>
android:name=".x.loginActivity"
tools:node="merge" // this is must
// your flavor spesific code
</activity>
</application>
</manifest>
Secondly
Delete your code to minimum in main XML. What i mean that manifest you've created in src/flavor will be merged with main one. so that delete what you want to seperate and leave what you want to used common in main.
Thirdly
Give different manifestPlaceholder name if you need to seperate prod,dev and staging.
For example,
src/projectX/manifest.xml
<activity>
.
.
android:host='${projectXHost}'
.
</activity>
src/projectY/manifest.xml
<activity>
.
.
android:host='${projectYHost}'
.
</activity>
in gradle
productFlavors{
prod {
manifestPlaceholders = [projectXHost : 'xxx' , projectYHost : 'yyy']
}
}
Since this is my first answer, I'm sorry with layout and expressions. I hope you can understand what I mean. Have a good day
Is there way to conditionally include meta-data element in Android manifest file based on value set in Gradle. I am able to do following (using resValue to set <some_value> in build.gradle) but haven't been able to find way to include/exclude complete meta-data element.
<meta-data
android:name="<some_setting>"
android:value="#string/<some_value>" />
Somewhat of a hack but only way I've been able to address this is by having something like following (have changed names in example) in build.gradle (am using this in context of having different build flavors as well but isn't dependent on that)...I think there's probably some additional smarts that can be done around manifest merging that would make this a bit cleaner as well. myFlag is coming from a project.hasProperty() value I'm passing in as part of Fastlane script
sourceSets {
flavor1 {
if (myFlag == "true") {
manifest.srcFile "src/flavor1_flag/AndroidManifest.xml"
} else {
manifest.srcFile "src/flavor1/AndroidManifest.xml"
}
}
}
<meta-data android:name="string"
android:resource="resource specification"
android:value="string" />
This is self-answered question to share my knowledge.
I have a project with multiple product flavors and I want to integrate Fabric using separate organizations for each product flavor.
I tried to integrate Fabric using Android Studio Fabric Plugin. It adds
<meta-data
android:name="io.fabric.ApiKey"
android:value="DEFAULT_ORGANIZATION_API_KEY" />
entry to AndroidManifest.xml of main source set.
I decided to rewrite this entry in application variant specific source sets:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application>
<meta-data
android:name="io.fabric.ApiKey"
android:value="SECOND_ORGANIZATION_API_KEY"
tools:replace="android:value" />
</application>
</manifest>
Then I discovered that Fabric Gradle plugin generates crashlytics.properties file with fabric api secret (AKA build secret) during build and I should include this file to source control. But this file is overwritten each time I build specific application variant because api secret is unique for each application.
How can I integrate Fabric using separate organizations for each application variant?
During the build fabricGenerateResources task is called and it looks for a file named fabric.properties with following content:
apiSecret=YOUR_BUILD_SECRET
apiKey=YOUR_API_KEY
So all we need is to generate fabric.properties file before this.
I found this solution and slightly modified it to fully support application variants not only build types.
Add this code to android section of build.gradle:
File crashlyticsProperties = new File("${project.projectDir.absolutePath}/fabric.properties")
applicationVariants.all { variant ->
variant.productFlavors.each { flavor ->
def variantSuffix = variant.name.capitalize()
def generatePropertiesTask = task("fabricGenerateProperties${variantSuffix}") << {
Properties properties = new Properties()
properties.put("apiKey", flavor.fabricApiKey)
properties.put("apiSecret", flavor.fabricApiSecret)
properties.store(new FileWriter(crashlyticsProperties), "")
}
def generateResourcesTask = project.tasks.getByName("fabricGenerateResources${variantSuffix}")
generateResourcesTask.dependsOn generatePropertiesTask
generateResourcesTask.doLast {
println "Removing fabric.properties"
crashlyticsProperties.delete()
}
}
}
It iterates over application variants and for each application variant creates task that generates fabric.properties file and task that deletes this file after Fabric Gradle plugin generates application resources.
All you need now is to define product flavor or build type specific fabricApiKey and fabricApiSecret:
productFlavors {
flavor1 {
ext.fabricApiKey = "FLAVOR1_API_KEY"
ext.fabricApiSecret = "FLAVOR1_API_SECRET"
}
}
ext is an ExtraPropertiesExtention object provided by every ExtensionAware object. It allows new properties to be added to existing object. In my case flavor1 is ExtensionAware object and it can be extended with new properties by using ext.someProperty = "value" syntax and later these properties can be used as flavor.someProperty, flavor.fabricApiKey.
Also it's better to include fabric.properties to .gitignore.
And do not forget to remove ext.enableCrashlytics = false from debug build type if you used it to disable Crashlytics during debug. Instead of this you can disable it in Application.onCreate:
Fabric.with(this, new Crashlytics.Builder().core(
new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build()).build());
If you're not opposed to using an application id suffix, you don't need separate organizations. The crashes and answers will be treated as separate apps.
For instance, let's say my application id is io.example
In your build.gradle:
buildTypes {
debug {
applicationIdSuffix ".debug"
}
release {
//options
}
}
After you deploy the debug version to a device or emulator, on the Fabric site you will see two apps:
io.example
io.example.debug
One thing that is nice about this approach is that you can also keep track of other build flavors seprately: io.exmaple.free, io.exmaple.paid, io.example.exterprise, and so on.
A simpler solution, which is also compatible with Gradle 5.x+ is to create separate fabric.properties files for each of the build variants that needs a unique Fabric API key and secret. Create the fabric.properties files as:
#Contains API Secret used to validate your application. Commit to internal source control; avoid making secret public.
apiSecret=YOUR_API_SECRET
apiKey=YOUR_API_KEY
replacing YOUR_API_SECRET with the build variant's API secret and YOUR_API_KEY with the build variant's API key.
Then place each variant's fabric.properties under the project src/variant folder, e.g. app/src/debug or app/src/release. See documentation on build variants for additional details.
At build time, the fabric.properties for the variant being built will be used.
When I am trying to build project with value of meta-data tag as a string reference, crashlytics fail with following error:
Crashlytics found an invalid API key: #string/crashlytics.
Check the Crashlytics plugin to make sure that the application has been added successfully!
Contact support#crashlytics.com for assistance.
Doesn't work
<meta-data
android:name="com.crashlytics.ApiKey"
android:value="#string/crashlytics"/>
Works
<meta-data
android:name="com.crashlytics.ApiKey"
android:value="1234567890..."/>
I am want to define different keys inside string.xml for different productFlavors of my android project.
Update
After writing to crashlytics support:
Currently we only are able to evaluate the AndroidManifest.xml at build time so we don't look at any strings resources so we only support a hard coded string. I'll definitely share this with the team that you're interested so we can look into supporting this in a future release.
Edit: The solution accepted is working only if you are using an old version of Crashlytics (I was using v1.1.11). If you are using Fabric SDK you will notice
the tasks of the plugin have changed considerably and the script below
will not work. Also the API secret is not needed anymore, therefore
you can just use the <meta> in the manifest to specify the API key along with a manifest placeholder defined in your flavor:
in build.gradle:
flavor1 {
...
manifestPlaceholders = [crashlyticsApiKey: CRASHLYTICS_API_SECRET_HERE]
...
}
in AndroidManifest.xml:
...
<meta-data
android:name="com.crashlytics.ApiKey"
android:value="${crashlyticsApiKey}" />
...
There is another undocumented way to specify the Crashlytics key as noted here, and it is to use the crashlytics.properties (in the root of your project) to specify that value along with the API secret:
apiKey=YOUR_API_KEY
apiSecret=YOUR_API_SECRET
Unfortuntately this will not allow you to simply specify a different crashlytics.properties for each flavor, because it needs to be in the root of your project in order to be picked correctly by the gradle plugin. That means you need to generate that file dynamically.
The idea is to add the key/secret values in your flavor as custom properties, and generate the crashlytics.properties at buildtime, using the values from the current flavor to fill the file.
The build.gradle inside your android module should look like this:
...
productFlavors {
flavor1 {
...
set("crashlyticsApiKey", CRASHLYTICS_API_KEY_HERE)
set("crashlyticsApiSecret", CRASHLYTICS_API_SECRET_HERE)
...
}
...
}
File crashlyticsProperties = new File("${project.projectDir.absolutePath}/crashlytics.properties")
applicationVariants.all { variant ->
variant.productFlavors.each { flavor ->
def variantSuffix = variant.name.capitalize()
def generateResourcesTask = project.tasks.getByName("crashlyticsGenerateResources${variantSuffix}")
def generatePropertiesTask = task("crashlyticsGenerateProperties${variantSuffix}") << {
Properties properties = new Properties()
println "...copying apiSecret for ${variant.name}"
properties.put("apiSecret", flavor.crashlyticsApiSecret)
println "...copying apiKey for ${variant.name}"
properties.put("apiKey", flavor.crashlyticsApiKey)
properties.store(new FileWriter(crashlyticsProperties), "")
}
generateResourcesTask.dependsOn generatePropertiesTask
def cleanResourcesTask = project.tasks.getByName("crashlyticsCleanupResourcesAfterUpload${variantSuffix}")
cleanResourcesTask.doLast {
println "...removing crashlytics.properties"
crashlyticsProperties.delete()
}
}
}
...
Basically the script hooks in the building process and generates/fills the properties file just before the Crashlytics gradle plugin does its magic.
With Fabric's Crashlytics 2.6.6. I'm able to simply select a Build Variant from the menu (usually located on the left in Android Studio) and run the app. It takes a minute or so to propagate through to the Fabric dashboard, but I didn't have any need for a workaround.
I am using the new gradle android buildsystem.
The project consists of two android library projects and one main project.
Using the ant build, the manifest merger must be enable in project.properties. But when using the gradle build system the manifest merger is enabled by default. How can i disable the manifest merger?
Edit: this is actually possible though indirectly, starting with 0.3
What you need to do is disable the processManifest task so that it doesn't run and tell the processResources where the manifest to use is:
android.applicationVariants.all { variant ->
variant.processResources.manifestFile = file('src/main/AndroidManifest.xml')
variant.processManifest.enabled=false
}
Note that if you are customizing the app package name through the DSL, you should keep the default manifest untouched in the default location to provide a consistent package name for the R classes, and then have your manually merged manifests somewhere else and point each variant processResources task to them.
This may help.
android.applicationVariants.all{ variant ->
variant.outputs.each { output ->
output.processResources.manifestFile = file('AndroidManifest.xml')
output.processManifest.enabled=false
}
}
For the 0.6.+ plugin you also have to change from buildVariants to applicationVariants:
android.applicationVariants.all { variant ->
variant.processResources.manifestFile = file('src/main/AndroidManifest.xml')
variant.processManifest.enabled=false
}
It doesn't look like these solutions work for the 1.0 plugin:
Could not find property 'processResources' on
com.android.build.gradle.internal.api.ApplicationVariantImpl_Decorated#774f1d0b.
Anyone have an update? Our issue is a stray activity showing up in the final apk from recyclerview-v7:21.0.3:
<activity
android:label="RecyclerViewTestActivity"
android:name="android.support.v7.widget.TestActivity"/>
Update: It looks like manifest merging can be configured (see http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger ). In this specific case, the TestActivity coming from the recyclerview-v7 library can be removed with:
<activity
android:name="android.support.v7.widget.TestActivity"
android:label="RecyclerViewTestActivity"
tools:node="remove"/>
Thanks Filip.
For the 0.5.+ plugin you have to change from each to all like this:
android.buildVariants.all { variant ->
variant.processResources.manifestFile = file('src/main/AndroidManifest.xml')
variant.processManifest.enabled=false
}