Gradle: How to customize Android Manifest permissi

2019-01-21 08:23发布

问题:

For my build system, I need to build several app variants, each requesting a different set of permissions. How can this be done with Gradle, without invoking a separate script?

回答1:

I just managed to do this by having different flavors in my gradle file:

    free {
        packageName 'com.sample.free'
        buildConfigField "boolean", "HAS_AD", "true"
    }

    paid {
        packageName 'com.sample.paid'
        buildConfigField "boolean", "HAS_AD", "false"
    }

and then I created a new folder under src called "free" and under that a folder called "res"

src/
 + free/
 |   + res/
 + src/

and in that folder create a new file "AndroidManifest.xml" with the following code in it:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.sample" >
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

According to Gradle Plugin User Guide on Android Tools Project Site:

Similar to Build Types, Product Flavors also contribute code and resources through their own sourceSets.

and

The following rules are used when dealing with all the sourcesets used to build a single APK:

  • All source code (src/*/java) are used together as multiple folders generating a single output.
  • Manifests are all merged together into a single manifest. This allows Product Flavors to have different components and/or permissions, similarly to Build Types.
  • All resources (Android res and assets) are used using overlay priority where the Build Type overrides the Product Flavor, which overrides the main sourceSet.
  • Each Build Variant generates its own R class (or other generated source code) from the resources. Nothing is shared between variants.

meaning that you can create a folder with each flavor name under src and put your custom files in them. If said file is an AndroidManifest gradle will merge it with the manifest in the main.