Set a global variable in gradle that can use in manifest file

徘徊边缘 提交于 2019-11-30 03:56:06

You can set them, for instance I'm setting it for different product flavors

productFlavors {
        production {
            applicationId = "com.myapp.app"
            resValue "string", "authority", "com.facebook.app.FacebookContentProvider5435651423234"
        }
        development {
            applicationId = "com.myapp.development"
            resValue "string", "authority", "com.facebook.app.FacebookContentProvider2134564533421"
        }
        qa {
            applicationId = "com.myapp.qa"
            resValue "string", "authority", "com.facebook.app.FacebookContentProvider29831237981287319"
        }
}

And use it like this

<provider
    android:name="com.facebook.FacebookContentProvider"
    android:authorities="@string/authority"
    android:exported="true" />

If you just want to use the application id set in gradle in your manifest, you can simply use:

${applicationId}

For instance:

<provider
    android:authorities="${applicationId}.ShareFileProvider" ... >
    ...
</provider>

If you want the same behavior with custom variables, you can use manifestPlaceholders, like this:

android {
    defaultConfig {
        manifestPlaceholders = [hostName:"www.example.com"]
    }
}

And in your manifest:

<intent-filter ... >
    <data android:scheme="http" android:host="${hostName}" ... />
    ...
</intent-filter>

See https://developer.android.com/studio/build/manifest-build-variables.html for more information.

While Marko's answer seems to work, there's currently a better solution that doesn't require adding variables to the string resource files.

The manifest merger accepts placeholders:

For custom placeholders replacements, use the following DSL to configure the placeholders values :

 android {
     defaultConfig {
         manifestPlaceholders = [ activityLabel:"defaultName"]
     }
     productFlavors {
         free {
         }
         pro {
             manifestPlaceholders = [ activityLabel:"proName" ]
         }
     }

will substitute the placeholder in the following declaration :

<activity android:name=".MainActivity" android:label="${activityLabel}" >

You can also manipulate those strings with groovy functions.

To use the string in Manifest, you can directly make it in strings.xml. Like this,

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