在Fragment中獲取AndroidManifest.xml根元素(<manifest>)下的版本信息

String appVersionName=null;

try{

PackageManage manage=this.getActivity().getPackageManage();
  PackageInfo   info=manage.getPackageInfo(
            this.getActicity().getPackageName(),0);

      appVersionName=info.versionName;
}catch(NameNotFoundException e){
    e.printStackTrace();
}

得到應用程序信息的方法getPackageInfo(PackageName,flags)的源碼解釋如下:

/**
 * Retrieve overall information about an application package that is
 * installed on the system.
 * <p>
 * Throws {@link NameNotFoundException} if a package with the given name can
 * not be found on the system.
 *
 * @param packageName The full name (i.e. com.google.apps.contacts) of the
 *            desired package.
 * @param flags Additional option flags. Use any combination of
 *  {@link #GET_ACTIVITIES}, {@link #GET_GIDS},
 *  {@link #GET_CONFIGURATIONS}, {@link #GET_INSTRUMENTATION},
 *  {@link #GET_PERMISSIONS}, {@link #GET_PROVIDERS},
 *  {@link #GET_RECEIVERS}, {@link #GET_SERVICES},
 *  {@link #GET_SIGNATURES}, {@link #GET_UNINSTALLED_PACKAGES} to
 *            modify the data returned.
 * @return Returns a PackageInfo object containing information about the
 *         package. If flag GET_UNINSTALLED_PACKAGES is set and if the
 *         package is not found in the list of installed applications, the
 *         package information is retrieved from the list of uninstalled
 *         applications (which includes installed applications as well as
 *         applications with data directory i.e. applications which had been
 *         deleted with {@code DONT_DELETE_DATA} flag set).
     * @see #GET_ACTIVITIES
     * @see #GET_GIDS
     * @see #GET_CONFIGURATIONS
     * @see #GET_INSTRUMENTATION
     * @see #GET_PERMISSIONS
     * @see #GET_PROVIDERS
     * @see #GET_RECEIVERS
     * @see #GET_SERVICES
     * @see #GET_SIGNATURES
     * @see #GET_UNINSTALLED_PACKAGES
     */

大意爲會在系統已安裝的應用程序中檢索這個包的信息,如果這個包的名字在這個系統中沒有被找到的話就會拋出一個NameNotFoundException,參數PackageName是期望的包名稱,參數Flags有多種選擇會根據不同選擇返回不同的數據,如果flags設置的是GET_UNINSTALLED_PACKAGES並且這個包是不會被找到的在已安裝的應用程序集合中,這個包的信息檢索就會是來自於未安裝的應用程序集合(這個集合還包含已經安裝但是被刪掉的應用程序的數據信息)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章