從com.android.tools.build:gradle:4.1.0
開始,build.gradle
文件正式移除了versionName
和versionCode
,參照鏈接。
如果依然需要BuildConfig.VERSION_NAME
的話,可以使用如下方式
buildConfigField "int", 'VERSION_CODE', String.valueOf(1)
buildConfigField 'String', 'VERSION_NAME', "\"" + "1.0.0" + "\""
但是僅僅這麼做不太夠,因爲這樣之後並不能讓AndroidManifest.xml
帶上版本號,導致最後打的包裏面是沒有版本號的。所以還需要在AndroidManifest.xml
加上版本號。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:versionCode="1"
android:versionName="1.0.0">
</manifest>
當然也可以捨棄BuildConfig.VERSION_NAME
的方式,用以下代碼來讀取版本號。
try {
val manager = this.packageManager
val info = manager.getPackageInfo(this.packageName, 0)
info.versionName
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
L.i("info.versionName ${info.versionName} ${info.longVersionCode} ")
}else{
L.i("info.versionName ${info.versionName} ${info.versionCode} ")
}
} catch (e: Exception) {
e.printStackTrace()
}