簡體   English   中英

提示用戶安裝 APK

[英]Prompting user to install APK

我正在為我的 Android 應用程序(我沒有使用 Play 商店)構建自己的更新機制。 我可以使用DownloadManager成功下載新的 apk。 下載完成后,我想提示用戶安裝 apk。 我嘗試了以下方法:

    File file = context.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "/app-debug.apk");
    String test = file.getAbsolutePath();
    Intent promptInstall = new Intent(Intent.ACTION_VIEW)
            .setDataAndType(Uri.parse("content://" + file.getAbsolutePath()),
                    "application/vnd.android.package-archive");
    context.startActivity(promptInstall);

不幸的是,這根本不起作用。 該文件在那里,但沒有安裝提示。 出了什么問題? 我是否還必須將第二個參數調整為setDataAndType 它應該適用於 SDK 23 到 29。

編輯

我現在嘗試了以下方法:

    File file = context.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "/app-debug.apk");

    Uri fileUri = Uri.fromFile(file); //for Build.VERSION.SDK_INT <= 24
    if (Build.VERSION.SDK_INT >= 24) {
        fileUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
    }
    Intent promptInstall = new Intent(Intent.ACTION_VIEW, fileUri);
    promptInstall.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
    promptInstall.setDataAndType(fileUri, "application/vnd.android.package-archive");
    promptInstall.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
    promptInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(promptInstall);

在清單中,我現在有以下內容:

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="ir.greencode"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/path" />
        </provider>

我已經創建了 path.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="." /></paths>

但現在我收到錯誤消息:

java.lang.IllegalArgumentException:找不到具有權限 com.testapp.provider 的提供者的元數據

我下載的 APK 位於/storage/emulated/0/Android/data/com.testapp/files/Download/app-debug.apk 這意味着file指向該目錄。 最后,我想將 apk 存儲在內部存儲或 SD 存儲中(取決於有更多可用空間)。

我該如何解決這個問題?

在 Android 上以編程方式安裝應用程序的可能副本

我認為該線程的這個答案應該有效:

https://stackoverflow.com/a/54424223/9490453

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM