在SDK 29+中安装软件包-使用PackageInstaller / PackageManager

时间:2019-10-14 15:48:42

标签: android packageinstaller

摘要:如何使用PackageInstaller安装已下载到android tablet SDK 29+的软件包?

在将targetSDK更新为29之后,我试图通过我的Android应用程序下载并安装软件包。使用Uri.fromFilestartActivity,将目标安装为<23时,一切正常。有关示例,请参见下面的代码。

        if(result) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String filePath = Environment.getExternalStorageDirectory() + DOWNLOAD_DIR + updateContext.getFilename();
        if (android.os.Build.VERSION.SDK_INT < 29) {
            Ln.i("Inside < 29");
            File file = new File(filePath);
            Ln.i(filePath);
            Uri uri = Uri.fromFile(file); //For < SDK 24
            if (android.os.Build.VERSION.SDK_INT >= 24) {
                uri = FileProvider.getUriForFile(
                        context, context.getApplicationContext()
                                .getPackageName() + ".provider", file);
            }
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            if(updateContext != UpdateContext.SELF) {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(intent);
        } else {
            Ln.i("Ran 29+ install");
            InstallPackageAndroidQAndAbove(context, filePath, intent);
        }
    }
    static void InstallPackageAndroidQAndAbove(Context context, String filePath, Intent intent) {
        int sessionId = 0;
        PackageInstaller.Session session = null;
        PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
        PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
        sessionParams.setAppPackageName(context.getApplicationContext().getPackageName());

        try {
            sessionId = packageInstaller.createSession(sessionParams);
        } catch (Exception ex) {
            Ln.e("Could not create session");
        }

        try {
            session = packageInstaller.openSession(sessionId);
        } catch (Exception ex) {
            Ln.e("Could not open session");
        }

        intent.setAction("ACTION_INSTALL_COMPLETE");

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context,
                sessionId,
                intent,
                0);

        IntentSender statusReceiver = pendingIntent.getIntentSender();

        session.commit(statusReceiver);
    }

在装有Android 29+的平板电脑上运行时,文件会在正确的位置下载。安装窗口短暂打开,然后自动关闭。控制台中没有警告,只是无声的失败。

我想我对PackageInstaller的工作方式了解有些问题。问题还可能是第一种方法中的FileProvider调用FileProvider.getUriForFile

0 个答案:

没有答案
相关问题