新版gradle移除versionCode和versionName的問題

com.android.tools.build:gradle:4.1.0開始,build.gradle文件正式移除了versionNameversionCode,參照鏈接

如果依然需要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()

        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章