1. 程式人生 > >Android菜鳥筆記- 獲取未安裝的APK圖標、版本號、包名、名稱、是否安裝、安裝、打開

Android菜鳥筆記- 獲取未安裝的APK圖標、版本號、包名、名稱、是否安裝、安裝、打開

ack ear 例如 start true intent ble post oca

周末閑來無事,把Android的基礎知識拿出來復習復習,今天主題是《獲取未安裝的APK圖標、版本號、包名、名稱、是否安裝、跳轉安裝、打開》

一、獲取APK圖標

通常讀取APK的圖標能夠用,PackageManager裏面的getApplicationIcon(ApplicationInfo)來得到一個drawable。但實際使用的時候常常僅僅能得到一個默認的圖標。根本不是APK的圖標。

參考小米開源文件管理器,結合實踐,代碼例如以下:

/*
     * 採用了新的辦法獲取APK圖標。之前的失敗是由於android中存在的一個BUG,通過
     * appInfo.publicSourceDir = apkPath;來修正這個問題,詳情參見:
     * http://code.google.com/p/android/issues/detail?id=9151
     */
    public static Drawable getApkIcon(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath,
                PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            appInfo.sourceDir = apkPath;
            appInfo.publicSourceDir = apkPath;
            try {
                return appInfo.loadIcon(pm);
            } catch (OutOfMemoryError e) {
                Log.e("ApkIconLoader", e.toString());
            }
        }
        return null;
    }

下面代碼段中PackageManager、PackageInfo、ApplicationInfo均同上面一致。

二、獲取APK名稱

String label = appInfo.loadLabel(mPackManager).toString();


三、獲取APK包名

String packageName = appInfo.packageName;


四、獲取APK版本號

String version = info.versionName==null?

"0":info.versionName


五、推斷APK是否安裝

private boolean isApkInstalled(String packagename)
	  {
	    PackageManager localPackageManager = getPackageManager();
	    try
	    {
	      PackageInfo localPackageInfo = localPackageManager.getPackageInfo(packagename, PackageManager.GET_UNINSTALLED_PACKAGES);
	      return true;
	    }
	    catch (PackageManager.NameNotFoundException localNameNotFoundException)
	    {
	     return false;
	    }
	    
	  }


六、安裝APK

 private void installAPK(String apkPath)
	 {
		 Intent intent = new Intent();
		 intent.setAction(Intent.ACTION_VIEW);
		 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		 intent.setDataAndType(Uri.parse("file://" + apkPath),
					"application/vnd.android.package-archive");
		 mContext.startActivity(intent);
	 }

七、打開APK

</pre><pre name="code" class="java"> private void openAPK(String packagename)
	 {
		   PackageManager packageManager = mContext.getPackageManager(); 
		   Intent intent=new Intent(); 
		   intent =packageManager.getLaunchIntentForPackage(packagename); 
		   mContext.startActivity(intent);
	 }

Ps.關於APK的靜默安裝還在研究中...



Android菜鳥筆記- 獲取未安裝的APK圖標、版本號、包名、名稱、是否安裝、安裝、打開