1. 程式人生 > >AndroidManifest佔位符(實現根據正式還是測試環境設定不同的app名稱)

AndroidManifest佔位符(實現根據正式還是測試環境設定不同的app名稱)

佔位符,其實是一個可以被替換的臨時標記,比如${name},我們就可以使用真實的name變數的值替換這個佔位符,達到可以動態的修改這個佔位符的目的。所以AndroidManifest檔案的佔位符,其實是幫助我們動態修改AndroidManifest檔案裡的內容

AndroidManifest清單檔案

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.cjy.hhlc">

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher1"
        android:label="${appName}"
        android:roundIcon="@mipmap/ic_launcher1"
        android:supportsRtl="true"
        android:largeHeap="true"
        android:name="com.cjy.hhlc.base.BaseApplication"
        android:testOnly="false"
        android:resizeableActivity="true"
        android:theme="@style/AppTheme"
        tools:replace="label">

當前應用build.gradle檔案

android {
    buildTypes {
        release {
            manifestPlaceholders.put("appName","應用名稱正式版")
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.config
        }
        debug {
            manifestPlaceholders.put("appName","應用名稱測試版")
            signingConfig signingConfigs.config
        }
    }
}

注意:

Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : Attribute [email protected] value=(應用名稱測試版) from AndroidManifest.xml:40:9-35
  	is also present at [:photopicker] AndroidManifest.xml:13:9-41 value=(@string/app_name).
  	Suggestion: add 'tools:replace="android:label"' to <application> element at AndroidManifest.xml:37:5-294:19 to override.

錯誤原因:AndroidStudio的Gradle外掛預設會啟用Manifest Merger Tool,若你匯入的Library專案中也定義了與主專案相同的屬性,則此時會合並失敗,並報上面的錯誤。

解決辦法:

在Manifest.xml檔案裡的application中加上tools:replace="label"

這樣再次編譯就好了