繁体   English   中英

如何以编程方式安装Android系统应用

[英]How to install Android system app programmactically

单击“更新”按钮时,我将安装 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);

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

这是从网站下载 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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM