问题描述
PackageInstaller( https://developer.android.com/reference/似乎从API 21(Lollipop)开始添加了android/content/pm/PackageInstaller.html ),但是我还没有找到任何有关如何通过此API安装APK的可靠代码示例.任何代码帮助将不胜感激.
PackageInstaller (https://developer.android.com/reference/android/content/pm/PackageInstaller.html) seems to have been added starting in API 21 (Lollipop), however I have not found any solid code examples on how to install an APK via this API. Any code help would be appreciated.
我正在调查适用于Android M Preview的COSU/Kiosk应用程序,并试图实现新功能由设备所有者静默安装和卸载应用程序"( https://developer.android.com/preview/api-overview.html#afw ).
I’m investigating COSU/Kiosk apps for Android M Preview and was trying to implement the new feature "Silent install and uninstall of apps by Device Owner" (https://developer.android.com/preview/api-overview.html#afw) via the PackageInstaller API.
找到了这些,但没有帮助:什么是"PackageInstaller";棒棒糖课程,以及如何使用它?
Found these, but not helpful: How to install/update/remove APK using "PackageInstaller" class in Android L?What's "PackageInstaller" class on Lollipop, and how to use it?
也没有找到任何Android示例应用.
Did not find any Android sample apps either.
谢谢.
推荐答案
在Android 6.0及更高版本中可以实现.
This is possible from Android 6.0 and up.
- 让您的应用成为设备所有者.
一旦您的应用获得了设备所有者的许可,我们就可以在没有任何用户干预的情况下静默安装,卸载和更新.
Once your app gets the Device owner permission, we can install, uninstall and update silently without any user intervention.
public static boolean installPackage(Context context, InputStream in, String packageName)
throws IOException {
PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
PackageInstaller.SessionParams.MODE_FULL_INSTALL);
params.setAppPackageName(packageName);
// set params
int sessionId = packageInstaller.createSession(params);
PackageInstaller.Session session = packageInstaller.openSession(sessionId);
OutputStream out = session.openWrite("COSU", 0, -1);
byte[] buffer = new byte[65536];
int c;
while ((c = in.read(buffer)) != -1) {
out.write(buffer, 0, c);
}
session.fsync(out);
in.close();
out.close();
session.commit(createIntentSender(context, sessionId));
return true;
}
private static IntentSender createIntentSender(Context context, int sessionId) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
sessionId,
new Intent(ACTION_INSTALL_COMPLETE),
0);
return pendingIntent.getIntentSender();
}
卸载:
String appPackage = "com.your.app.package";
Intent intent = new Intent(getActivity(), getActivity().getClass());
PendingIntent sender = PendingIntent.getActivity(getActivity(), 0, intent, 0);
PackageInstaller mPackageInstaller = getActivity().getPackageManager().getPackageInstaller();
mPackageInstaller.uninstall(appPackage, sender.getIntentSender());
在此存储库.
这篇关于PackageInstaller“通过设备所有者静默安装和卸载应用程序"-Android M预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!