Android APP 读取 AndroidManifest.xml 中的版本信息详解

APP都会涉及到版本的问题,Android APP的版本信息保存在AndroidManifest.xml文件的顶部。如下图:

有2个属性表示,“android:versionCode”和“android:versionName”,其中versionCode是int类型,是给程序用的,一般版本控制就用这个,versionName是String类型,是给用户看的,比如在APP的关于页面,显示当前版本。新建的工程中versionCode默认是1,versionName默认是1.0。

下面来用程序读取一下这2个属性。

布局文件代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="APP版本信息:" />

    <TextView
        android:id="@+id/tvVersion"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Activity代码如下:

package chengyujia.androidtest;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.widget.TextView;

public class VersionActivity extends Activity {

    private TextView tvVersion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_version);
        tvVersion = (TextView) findViewById(R.id.tvVersion);
        showVersion();
    }

    private void showVersion() {
        // 在Activity中可以直接调用getPackageManager(),获取PackageManager实例。
        PackageManager packageManager = getPackageManager();
        // 在Activity中可以直接调用getPackageName(),获取安装包全名。
        String packageName = getPackageName();
        // flags提供了10种选项,及其组合,如果只是获取版本号,flags=0即可
        int flags = 0;
        PackageInfo packageInfo = null;
        try {
            // 通过packageInfo即可获取AndroidManifest.xml中的信息。
            packageInfo = packageManager.getPackageInfo(packageName, flags);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        if (packageInfo != null) {
            // 这里就拿到版本信息了。
            int versionCode = packageInfo.versionCode;
            String versionName = packageInfo.versionName;
            tvVersion.setText("versionCode=" + versionCode + "\nversionName=" + versionName);
        }
    }
}

运行看一下效果:

上图显示的是默认值,当我们的APP发布新版本时,需要在AndroidManifest.xml中修改这两个值,其中versionCode是int类型,一般从1开始自增,如果赋予非int类型的值会报错,比如下图:

而versionName是String类型的,只要是字符串就行,比如下图:

下面运行看一下截图:

版本信息读取就写这些吧,该吃晚饭喽^_^

posted @ 2015-11-25 19:13  成宇佳  阅读(12870)  评论(2编辑  收藏  举报