Home>

Using the package manager

package com.liunan.myfirstapp.util;
import android.content.context;
import android.content.pm.applicationinfo;
import android.content.pm.packageinfo;
import android.content.pm.packagemanager;
/ **
* created by Liu Nan on 2016-03-22.
* /
public class packageutils {
/ **
* Get version name
* @param context
* @return version name
* /
public static string getversionname (context context) {
// Get the package manager
packagemanager pm=context.getpackagemanager ();
// Get package information
try {
packageinfo packageinfo=pm.getpackageinfo (context.getpackagename (), 0);
// Return the version number
return packageinfo.versionname;
} catch (packagemanager.namenotfoundexception e) {
e.printstacktrace ();
}
return null;
}/**
* Get version number
* @param context
* @return version number
* /
public static int getversioncode (context context) {
// Get the package manager
packagemanager pm=context.getpackagemanager ();
// Get package information
try {
packageinfo packageinfo=pm.getpackageinfo (context.getpackagename (), 0);
// Return the version number
return packageinfo.versioncode;
} catch (packagemanager.namenotfoundexception e) {
e.printstacktrace ();
}
return 0;
}
/ **
* Get the name of the app
* @param context
* @return name
* /
public static string getappname (context context) {
packagemanager pm=context.getpackagemanager ();
// Get package information
try {
packageinfo packageinfo=pm.getpackageinfo (context.getpackagename (), 0);
// Get application information
applicationinfo applicationinfo=packageinfo.applicationinfo;
// Get albelres
int labelres=applicationinfo.labelres;
// Return the name of the app
return context.getresources (). getstring (labelres);
} catch (packagemanager.namenotfoundexception e) {
e.printstacktrace ();
}
return null;
}
}

Let's share a piece of code to introduce Android to get the app version number and version name.

/ Here is the tool method to get version information

// version name
public static string getversionname (context context) {
return getpackageinfo (context) .versionname;
}
//version number
public static int getversioncode (context context) {
return getpackageinfo (context) .versioncode;
}
private static packageinfo getpackageinfo (context context) {
packageinfo pi=null;
try {
packagemanager pm=context.getpackagemanager ();
pi=pm.getpackageinfo (context.getpackagename (),packagemanager.get_configurations);
return pi;
} catch (exception e) {
e.printstacktrace ();
}
return pi;
}
  • Previous Add, delete, modify, and check the array of JavaScript study notes
  • Next Java practical verification code implementation code