【问题标题】:How to install Android system app programmactically如何以编程方式安装Android系统应用程序
【发布时间】:2020-09-20 16:49:34
【问题描述】:

单击“更新”按钮时,我将安装 android 系统应用程序。 但我没有找到合适的解决方案。
我在代码中使用了命令“pm install ***.apk”。
我尝试使用如下:

Intent in = new Intent(Intent.ACTION_VIEW);
in.setDataAndType("...apk name", "application/vnd.android.package-archive");
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(in);

但是这些代码对我没有帮助。
如果你曾经解决过这个问题,请帮助我。

【问题讨论】:

  • 您想在没有其他用户参与的情况下执行安装吗?您的应用程序是否使用系统证书签名?您在哪个版本的 Android 上运行?

标签: java android system


【解决方案1】:

以下是从网站下载 APK 并提示用户安装的完整代码示例:

protected void installUpdate() {
    String destination = getApplicationContext().getExternalFilesDir(DOWNLOAD_SERVICE) + "/";
    String fileName = "update.apk";
    destination += fileName;
    final Uri uri = Uri.parse("file://" + destination);

    File file = new File(destination);
    if (file.exists()) {
        file.delete();
    }

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse("https://mylink.com/update.apk"));
    request.setDescription("Update");
    request.setTitle("MyApp");
    request.setDestinationUri(uri);

    final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);

    BroadcastReceiver onComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            File toInstall = new File(getApplicationContext().getExternalFilesDir(DOWNLOAD_SERVICE), "update" + ".apk");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri apkUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", toInstall);
                Intent intentUpdate = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                intentUpdate.setData(apkUri);
                intentUpdate.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
            } else {
                Uri apkUri = Uri.fromFile(toInstall);
                Intent intentUpdate = new Intent(Intent.ACTION_VIEW);
                intentUpdate.setDataAndType(apkUri, "application/vnd.android.package-archive");
                intentUpdate.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }

            getApplicationContext().startActivity(intentUpdate);
            toInstall.deleteOnExit();

            getApplicationContext().unregisterReceiver(this);
            stopSelf();
        }
    };
    getApplicationContext().registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-23
    • 2023-03-03
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多