Conditionally add <activity> tag on AndroidManifest.xml using Gradle

瘦欲@ 提交于 2020-01-02 10:17:16

问题


I have an application that only have Services, Receivers and Activities that are not directly accessed by the use (there is no launcher activity).

But now I have to add an activity to be used as launcher activity BUT this launcher activity must be present only when the app has some specific variables set during the BUILD.

So basically, when calling the gradle build I set a variable HAS_LAUNCHER=1 and in my build.gradle I have something like:

defaultConfig {
    ...

    def hasLauncher = System.getenv("HAS_LAUNCHER")
    if (hasLauncher != null && hasLauncher == "1") {
        // Something here to include the activity tag in the AndroidManifest.xml
    }
}

And in my AndroidManifest I have to add the <activity> tag when that if condition is true:

<activity
    android:name=".LauncherActivity"
    android:label="Launcher"
    android:theme="@style/AppTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity>


How can I accomplish that without using a new dimension of productFlavors? (the app already has a dimension with 3 flavors and 2 buildTypes, so I don't want to make even more outputs)

回答1:


may be too late, but after many days searching for a solution I have done in this way :

gradle defaultConfig

defaultConfig {
    resValue "bool", "showActivity", "true"
...

In the builTypes

 buildTypes {
    release {
        resValue "bool", "showActivity", "false"
        debuggable false
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }

In manifest

    <activity
     android:name="xxx.xx.xxx"
        android:enabled="@bool/showActivity"
        android:label="@string/myActivity"
        android:icon="@android:drawable/ic_menu_preferences">
    ...

This way you can control activity visibility from gradle. Note that you can also use in code , just create a bool resource showActivity , it will be replaced by gradle value and you'll be able to read it

context.getResources().getBoolean(R.bool.showActivity)


来源:https://stackoverflow.com/questions/37283428/conditionally-add-activity-tag-on-androidmanifest-xml-using-gradle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!