AndroidManifest.xml之<manifest android:versionCode android:versionName> element详解

本文介绍了如何在Android应用中通过PackageManager API读取AndroidManifest.xml文件中的versionCode和versionName,以及如何从资源文件中获取应用名称。提供代码示例便于开发者实践。

android:versionCode和android:versionName两个字段分别表示版本代码,版本名称。versionCode是整型数字,versionName是字符串。versionName是给用户看的,不太容易比较大小,升级检查时,可以以检查versionCode为主,方便比较出版本的前后大小。

在应用中如何读取AndroidManifest.xml中的versionCode和versionName呢?可以使用PackageManager的API,参考以下代码:

public static int getVerCode(Context context) {
        int verCode = -1;
        try {
            verCode = context.getPackageManager().getPackageInfo(
                    "com.myapp", 0).versionCode;
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        return verCode;
    }
   
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(
                    "com.myapp", 0).versionName;
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        return verName;   
}


或者在AndroidManifest中将android:versionName="1.2.0"写成android:versionName="@string/app_versionName",然后在values/strings.xml中添加对应字符串,这样实现之后,就可以使用如下代码获得版本名称:

public static String getVerName(Context context) {
        String verName = context.getResources()
        .getText(R.string.app_versionName).toString();
        return verName;
}

同理,apk的应用名称可以这样获得:

public static String getAppName(Context context) {
        String verName = context.getResources()
        .getText(R.string.app_name).toString();
        return verName;
}


<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.onlinebookstore"> <!-- 记得添加下面的权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" /> <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" /> <application android:allowBackup="true" android:icon="@drawable/s2" android:label="在线书店" android:requestLegacyExternalStorage="true" android:supportsRtl="true" android:theme="@style/Theme.FlowerShop"> <activity android:name=".activity.LoginActivity"/> <activity android:name=".activity.WelcomeActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".activity.ManageActivity" android:exported="false" /> <activity android:name=".activity.StuffEditActivity" android:exported="false" /> <activity android:name=".activity.LoginActivity" android:exported="false" /> <activity android:name=".activity.RegisterActivity" android:exported="false" /> <activity android:name=".activity.MainActivity" android:exported="false" /> <activity android:name=".activity.DetailActivity" android:exported="false" /> <activity android:name=".activity.AboutActivity" android:exported="false" /> <activity android:name=".activity.InfoActivity" android:exported="false" /> <activity android:name=".activity.RecordActivity" android:exported="false" /> </application> </manifest>。plugins { id 'com.android.application' } android { namespace 'com.example.flowershop' compileSdk 34 defaultConfig { applicationId "com.example.onlinebookstore" minSdk 21 targetSdk 34 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation 'androidx.appcompat:appcompat:1.3.1' implementation 'com.google.android.material:material:1.4.0' implementation 'com.github.getActivity:XXPermissions:20.0' implementation ('com.github.bumptech.glide:glide:4.16.0'){ exclude group : 'androidx.annotation' } annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0' }。下面是报错信息Executing tasks: [testDebugUnitTest] in project E:\7.flower-shop\flower-shop\app Starting Gradle Daemon... Connected to the target VM, address: '127.0.0.1:49946', transport: 'socket' Gradle Daemon started in 2 s 237 ms > Task :app:preBuild UP-TO-DATE > Task :app:preDebugBuild UP-TO-DATE > Task :app:javaPreCompileDebug UP-TO-DATE > Task :app:checkDebugAarMetadata UP-TO-DATE > Task :app:generateDebugResValues UP-TO-DATE > Task :app:mapDebugSourceSetPaths > Task :app:generateDebugResources UP-TO-DATE > Task :app:mergeDebugResources UP-TO-DATE > Task :app:packageDebugResources UP-TO-DATE > Task :app:parseDebugLocalResources UP-TO-DATE > Task :app:createDebugCompatibleScreenManifests UP-TO-DATE > Task :app:extractDeepLinksDebug UP-TO-DATE > Task :app:processDebugMainManifest FAILED Incorrect package="com.example.onlinebookstore" found in source AndroidManifest.xml: E:\7.flower-shop\flower-shop\app\src\main\AndroidManifest.xml. Setting the namespace via the package attribute in the source AndroidManifest.xml is no longer supported. Recommendation: remove package="com.example.onlinebookstore" from the source AndroidManifest.xml: E:\7.flower-shop\flower-shop\app\src\main\AndroidManifest.xml. > Task :app:preDebugUnitTestBuild UP-TO-DATE > Task :app:javaPreCompileDebugUnitTest UP-TO-DATE > Task :app:processDebugUnitTestJavaRes NO-SOURCE FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:processDebugMainManifest'. > Incorrect package="com.example.onlinebookstore" found in source AndroidManifest.xml: E:\7.flower-shop\flower-shop\app\src\main\AndroidManifest.xml. Setting the namespace via the package attribute in the source AndroidManifest.xml is no longer supported. Recommendation: remove package="com.example.onlinebookstore" from the source AndroidManifest.xml: E:\7.flower-shop\flower-shop\app\src\main\AndroidManifest.xml. * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. > Get more help at https://help.gradle.org. BUILD FAILED in 10s 12 actionable tasks: 2 executed, 10 up-to-date 21:07:28: Execution finished 'testDebugUnitTest'. Disconnected from the target VM, address: '127.0.0.1:49946', transport: 'socket'。该修改那些地方让它成为新的项目onlinebooksotre
06-03
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" android:installLocation="preferExternal" android:compileSdkVersion="34" android:compileSdkVersionCodename="14" package="com.yuanwu.jixietwo" platformBuildVersionCode="34" platformBuildVersionName="14"> <uses-sdk android:minSdkVersion="23" android:targetSdkVersion="34" /> <supports-screens android:anyDensity="true" android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" /> <!-- 查看网络连接 --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- 拥有完全的网络访问权限 --> <uses-permission android:name="android.permission.INTERNET" /> <uses-feature android:glEsVersion="0x20000" /> <!-- 允许接收WLAN多播 --> <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" /> <!-- 控制振动 --> <uses-permission android:name="android.permission.VIBRATE" /> <!-- 修改或删除您共享存储空间中的内容 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-feature android:name="android.hardware.touchscreen" android:required="false" /> <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" /> <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" /> <uses-permission android:name="com.android.vending.BILLING" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <application android:label="@string/app_name" android:icon="@mipmap/app_icon" android:extractNativeLibs="true"> <meta-data android:name="unity.builder" android:value="12370032558358" /> <activity android:theme="@style/UnityThemeSelector" android:name="com.unity3d.player.UnityPlayerActivity" android:exported="true" android:launchMode="singleTask" android:screenOrientation="landscape" android:configChanges="density|fontScale|keyboard|keyboardHidden|layoutDirection|locale|mcc|mnc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:hardwareAccelerated="false" android:resizeableActivity="false"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <meta-data android:name="unityplayer.UnityActivity" android:value="true" /> <meta-data android:name="android.notch_support" android:value="true" /> </activity> <meta-data android:name="unity.splash-mode" android:value="2" /> <meta-data android:name="unity.splash-enable" android:value="true" /> <meta-data android:name="unity.launch-fullscreen" android:value="true" /> <meta-data android:name="unity.allow-resizable-window" android:value="false" /> <meta-data android:name="notch.config" android:value="portrait|landscape" /> <meta-data android:name="unity.build-id" android:value="a2f5cdfc-a9e0-4cfb-be1f-c67906e8f0bb" /> <meta-data android:name="com.google.android.play.billingclient.version" android:value="4.0.0" /> <activity android:theme="@android:style/Theme.Translucent.NoTitleBar" android:name="com.android.billingclient.api.ProxyBillingActivity" android:exported="false" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize" /> <activity android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:name="com.unity3d.services.ads.adunit.AdUnitActivity" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mcc|mnc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:hardwareAccelerated="true" /> <activity android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" android:name="com.unity3d.services.ads.adunit.AdUnitTransparentActivity" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mcc|mnc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:hardwareAccelerated="true" /> <activity android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" android:name="com.unity3d.services.ads.adunit.AdUnitTransparentSoftwareActivity" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mcc|mnc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:hardwareAccelerated="false" /> <activity android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:name="com.unity3d.services.ads.adunit.AdUnitSoftwareActivity" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mcc|mnc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:hardwareAccelerated="false" /> <activity android:name="bin.mt.file.content.MTDataFilesWakeUpActivity" android:exported="true" android:taskAffinity="com.yuanwu.jixietwo.MTDataFilesWakeUp" android:excludeFromRecents="true" android:noHistory="true" /> <provider android:name="bin.mt.file.content.MTDataFilesProvider" android:permission="android.permission.MANAGE_DOCUMENTS" android:exported="true" android:authorities="com.yuanwu.jixietwo.MTDataFilesProvider" android:grantUriPermissions="true"> <intent-filter> <action android:name="android.content.action.DOCUMENTS_PROVIDER" /> </intent-filter> </provider> </application> </manifest> 翻译一下什么意思
最新发布
09-17
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值