Android靜默安裝

公司新需求,弄個靜默安裝激活。然後研究了下:

如果APK存放到android的/system/app目錄,APK就算是系統級應用。可以做到靜默安裝。

1、方法:

public static boolean installSilently(Context context, String filePath) {
		try {
			Class<?> pmService = null;
			Class<?> activityThread = null;
			Method method;

			activityThread = Class.forName("android.app.ActivityThread");
			Class<?> paramTypes[] = getParamTypes(activityThread,
					"getPackageManager");
			method = activityThread.getMethod("getPackageManager", paramTypes);
			Object PackageManagerService = method.invoke(activityThread);

			pmService = PackageManagerService.getClass();

			Class<?> paramTypes1[] = getParamTypes(pmService, "installPackage");
			method = pmService.getMethod("installPackage", paramTypes1);
			method.invoke(PackageManagerService,
					Uri.fromFile(new File(filePath)), null, 0, null);
			return true;
		} catch (Exception e) {
			MyLog.printLog(e);
		}
		return false;
	}


private static Class<?>[] getParamTypes(Class<?> cls, String mName) {
		Class<?> cs[] = null;

		try {
			Method[] mtd = cls.getMethods();

			for (int i = 0; i < mtd.length; i++) {
				if (!mtd[i].getName().equals(mName)) {
					continue;
				}
				cs = mtd[i].getParameterTypes();
			}
		} catch (Exception e) {
			MyLog.printLog(e);
		}
		return cs;
	}


filePath爲需要靜默安裝的APK的存醋路徑。

2、需要的權限

<uses-permission android:name="android.permission.INSTALL_PACKAGES" />

這個權限會在eclipse上報錯,直接刪除報錯信息就好。


3、應用激活就用包名啓動下已安裝的APK,算是激活了。

public static boolean openAppByPname(Context context, String pName) {
		boolean isOk = false;
		try {
			Intent intent = context.getPackageManager()
					.getLaunchIntentForPackage(pName);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);

			isOk = true;
		} catch (Exception e) {
			MyLog.printLog(e);
		}
		return isOk;
	}



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