APK文件只能包含一個AndroidManifest.xml文件充尉,但是Android Studio項(xiàng)目可以包含多個Manifest文件项贺,因此在構(gòu)建應(yīng)用時呻逆,Gradle構(gòu)建會將所有的清單文件合并到一個封裝到APK文件的清單文件中瞧捌。所有我們的主項(xiàng)目的Manifest文件并不是最終的打包時的Manifest文件
假如我們引入一個第三方庫讯赏,但是里面的Mianfest文件定義了一些我們不想要的東西费就,在合并到最終的Manifest文件時我們需要刪除里面的一些東西(多余的權(quán)限申請诉瓦,多余的Activity定義等),我們可以參考一下合并多個清單文件的規(guī)則:合并多個清單文件 利用清單文件的合并規(guī)則去刪除或者添加一些屬性
還有另一種方法就是在Gradle構(gòu)建的過程中通過Task去修改Manifest文件
在 Migrate to Android Plugin for Gradle 3.0.0 這篇文章中介紹了一種方法力细,通過Android Plugin提供的task拿到Manifest的內(nèi)容睬澡,然后對其做修改 如下:
android.applicationVariants.all { variant ->
variant.outputs.all { output ->
output.processManifest.doLast {
// Stores the path to the maifest.
String manifestPath = "$manifestOutputDirectory/AndroidManifest.xml"
// Stores the contents of the manifest.
def manifestContent = file(manifestPath).getText()
// Changes the version code in the stored text.
manifestContent = manifestContent.replace('android:versionCode="1"',
String.format('android:versionCode="%s"', generatedCode))
// Overwrites the manifest with the new text.
file(manifestPath).write(manifestContent)
}
}
}
但是上面的方法的給的有瑕疵:
variant.outputs返回的是一個List,并沒有all方法眠蚂,應(yīng)該換用each方法(應(yīng)該是文檔的錯誤)
Manifest文件的位置可以直接通過output來拿到
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
output.processManifest.doLast {
def manifestOutFile = output.processManifest.manifestOutputFile
def manifestContent = manifestOutFile.getText('UTF-8')
···
//對manifestContent進(jìn)行字符串操作
···
manifestOutFile.write(manifestContent)
}
}
}
可以通過manifestOutputFile.path確定最終Manifest文件的位置
全量編譯時