2010年6月15日星期二

檢視軟件版本, PackageInfo.versionCode 和 PackageInfo.versionName

許多時應用軟件都提供一個About Me選項, 從而檢視軟件版本.

檢視軟件版本

在Android可以使用下面程序代碼:
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
myVersionCode = packageInfo.versionCode;
myVersionName = packageInfo.versionName;

返回的數據是AndroidManifest.xml文件中定義的android:versionCode和android:versionName.

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/version"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>


AndroidCheckVersion.java
package com.AndroidCheckVersion;

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

public class AndroidCheckVersion extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView version = (TextView)findViewById(R.id.version);

int myVersionCode;
String myVersionName;

try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
myVersionCode = packageInfo.versionCode;
myVersionName = packageInfo.versionName;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myVersionCode = 0; //dummy
myVersionName = ""; //dummy
}

String myVersion = (
"\n"
+ "Version Code: " + String.valueOf(myVersionCode) + "\n"
+ "Version Name: " + myVersionName + "\n");

version.setText(myVersion);
}
}




沒有留言:

發佈留言