新版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()

        }

猜你喜欢

转载自blog.csdn.net/Ser_Bad/article/details/109995482