公司新需求,弄个静默安装激活。然后研究了下:
如果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;
}