卸載app的方式有多種,能夠直接調用android系統的卸載程序,可是這樣會調出android卸載提示框,問題就是真的很差看。android
因此採用靜默卸載的方式,避免彈出系統提示框。app
方法一(調用系統卸載程序):ui
1 //卸載應用 2 Uri packageURI = Uri.parse("package:" + pkgName); 3 Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI); 4 startActivity(uninstallIntent);
方法二(靜默安裝):spa
1 /** 2 * 卸載應用入口提示 3 * 4 * @param position app在列表中的位置 5 * @param mData app列表 6 */ 7 public void startUninstall(int position, List<AppInfoModel> mData) { 8 9 //獲取應用程序包名 10 String pkg = mData.get(position).packageName; 11 //判斷此應用程序是否存在 12 Boolean pkgExist; 13 pkgExist = appExist(mContext,pkg); 14 if (!pkgExist) { 15 Toast.makeText(mContext, "程序未安裝", Toast.LENGTH_SHORT).show(); 16 } else { 17 //靜默卸載 18 Boolean uninstallSuccess = uninstall(pkg); 19 if (uninstallSuccess){ 20 Toast.makeText(mContext, "卸載成功", Toast.LENGTH_SHORT).show(); 21 } else { 22 Toast.makeText(mContext, "卸載失敗", Toast.LENGTH_SHORT).show(); 23 } 24 } 25 26 } 27 28 29 /** 30 * 靜默卸載App 31 * 32 * @param packageName 包名 33 * @return 是否卸載成功 34 */ 35 private static boolean uninstall(String packageName) { 36 Process process = null; 37 BufferedReader successResult = null; 38 BufferedReader errorResult = null; 39 StringBuilder successMsg = new StringBuilder(); 40 StringBuilder errorMsg = new StringBuilder(); 41 try { 42 process = new ProcessBuilder("pm", "uninstall", packageName).start(); 43 successResult = new BufferedReader(new InputStreamReader(process.getInputStream())); 44 errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream())); 45 String s; 46 while ((s = successResult.readLine()) != null) { 47 successMsg.append(s); 48 } 49 while ((s = errorResult.readLine()) != null) { 50 errorMsg.append(s); 51 } 52 } catch (Exception e) { 53 KLog.d("e = " + e.toString()); 54 } finally { 55 try { 56 if (successResult != null) { 57 successResult.close(); 58 } 59 if (errorResult != null) { 60 errorResult.close(); 61 } 62 } catch (Exception e) { 63 KLog.d("Exception : " + e.toString()); 64 } 65 if (process != null) { 66 process.destroy(); 67 } 68 } 69 //若是含有"success"單詞則認爲卸載成功 70 return successMsg.toString().equalsIgnoreCase("success"); 71 } 72 73 /** 74 * 判斷應用是否存在 75 * 76 * @param context 上下文 77 * @param packageName 包名 78 * @return 是否存在 79 */ 80 private boolean appExist(Context context, String packageName) { 81 try { 82 List<PackageInfo> packageInfoList = context.getPackageManager().getInstalledPackages(0); 83 for (PackageInfo packageInfo : packageInfoList) { 84 if (packageInfo.packageName.equalsIgnoreCase(packageName)) { 85 return true; 86 } 87 } 88 } catch (Exception e) { 89 KLog.d(e.toString()); 90 } 91 return false; 92 }