如何解决如何使用Java编写的PackageManager安装apk?
我有一个 android 应用程序,如果存在新版本的 apk,它会从服务器更新自身。
问题是,它现在不适用于运行 android 10 及更高版本的设备。问题的根本原因是 ACTION_VIEW 已被弃用,并且自 android 10 起不再受支持。这是不起作用的遗留代码:
private void installapk(File file) {
Log.w(TAG,"Installing new version...");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
// Otherwise will throw exception,have to install it in new task
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
所以现在搜索了一段时间后,似乎我剩下的唯一选择是使用 packagemanager 类来完成这项工作。我找到了这个例子,它编译并运行时没有给出任何错误消息,但它似乎什么也没做。
public static void install(Context context,String packageName,File file) {
InputStream in = null;
OutputStream out = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
PackageInstaller.Session session = null;
try {
in = new FileInputStream(file);
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);
session = packageInstaller.openSession(sessionId);
out = session.openWrite(file.getName(),-1);
final byte[] buffer = new byte[65536];
int bytes_read;
while((bytes_read = in.read(buffer)) != -1){
out.write(buffer,bytes_read);
}
session.fsync(out);
in.close();
out.close();
session.commit(createIntentSender(context,sessionId,ACTION_INSTALL_COMPLETE));
} catch (IOException e) {
Log.w(TAG,e.getMessage());
} finally {
;
}
}
}
private static IntentSender createIntentSender(Context context,int sessionId,String action) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,new Intent(action),0);
return pendingIntent.getIntentSender();
}
这段代码运行良好,但正如我所说,结果没有任何反应。我做错了什么?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。