检测我的应用程序的自己的Andr​​oid:版本code运行时

问题描述:

有没有办法为我的应用程序就知道了android:从AndroidManifest.xml中的版本code或我必须在我的一个类创建一个单独的恒

Is there a way for my app to know the android:versionCode from AndroidManifest.xml or do I have to create a separate constant in one of my classes?

我把这个在我的子类android.app.Application但你可以使用它的任何地方,你有一个背景。只要改变getPackageManager()来context.getPackageManager()。

I put this in my subclassed android.app.Application but you can use it anywhere you have a context. Just change getPackageManager() to context.getPackageManager().

public int getVersion() {
    int v = 0;
    try {
        v = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
    } catch (NameNotFoundException e) {
        // Huh? Really?
    }
    return v;
}