84

My app has an auto-update feature that download an APK and when the download is finished that a Intent.VIEW_ACTION to open the app and let the user install the downloaded apk

Uri uri = Uri.parse("file://" + destination);
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(uri,
    manager.getMimeTypeForDownloadedFile(downloadId));
activity.startActivity(install);

This works great for all the device < 24

Now with Android 24 apparently we are not allowed any more to start intents with file:/// and after some googling it was advised to use A File Provider

new code:

Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri apkUri = FileProvider.getUriForFile(AutoUpdate.this,
    BuildConfig.APPLICATION_ID + ".provider", file);
install.setDataAndType(apkUri,
    manager.getMimeTypeForDownloadedFile(downloadId));
activity.startActivity(install);

Now activity.startActivity(install); throws an error

No Activity found to handle Intent { act=android.intent.action.VIEW dat=content://com.xxxx.xx.provider/MyFolder/Download/MyApkFile.apk typ=application/vnd.android.package-archive flg=0x4000000 }

Is there any way I can open the APK viewer in Android 7 (24) ?

4

5 回答 5

179

经过大量尝试后,我已经能够通过为低于 Nougat 的任何内容创建不同的 Intent 来解决此问题,因为在 Nougat 导致错误之前使用 FileProvider 创建具有 Android 版本的安装意图:

ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.INSTALL_PACKAGE dat=content://XXX.apk flg=0x1 }

在 Android Nougat 上使用普通 Uri 会产生以下错误:

FileUriExposedException: file:///XXX.apk exposed beyond app through Intent.getData()

我的解决方案适用于模拟器上的 Android N 和运行 Android M 的手机。

File toInstall = new File(appDirectory, appName + ".apk");
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Uri apkUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".fileprovider", toInstall);
    intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
    intent.setData(apkUri);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
    Uri apkUri = Uri.fromFile(toInstall);
    intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
activity.startActivity(intent);

Android Nougat 7.1 的更新:

您还需要在清单中添加权限 REQUEST_INSTALL_PACKAGES。它从 Api Level 23 (Android 6.0 Marshmallow) 开始可用,并且需要从 Level 25 (Android 7.1 Nougat) 开始。

更新:

如果您尝试安装的文件位于外部存储上,请记住请求读取和写入外部存储的权限。并为 Android Nougat 及更高版本设置正确的 FileProvider。

首先通过canReadWriteExternal()以下调用检查您是否具有写入权限,如果之前没有调用requestPermission()

private static final int REQUEST_WRITE_PERMISSION = 786;

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED)
        Toast.makeText(this, "Permission granted", Toast.LENGTH_LONG).show();
}

private void requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        requestPermissions(new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
}

private boolean canReadWriteExternal() {
    return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
            ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
}

以下是外部存储上下载文件夹的文件提供程序示例。AndroidManifest.xml

<application ... >
    ...

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths" />
    </provider>
</application>

资源/xml/filepaths.xml

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

如果您在安装 .apk 时遇到错误,例如“解析包时出现问题”。可能是您没有请求读/写权限,或者您尝试安装的文件不存在或已损坏。

Android Oreo 8.0 的更新:

您必须检查当前应用程序是否允许在 Android Oreo 8.0 或更高版本上安装 APK。

您可以使用PackageManager 类的canRequestPackageInstalls方法检查您的应用是否允许安装 APK 。如果它返回 false,那么您可以使用ACTION_MANAGE_UNKNOWN_APP_SOURCES操作启动意图以启动设置对话框,用户可以在其中允许应用安装 APK。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O 
        && !getPackageManager().canRequestPackageInstalls()) {
    Intent unknownAppSourceIntent = new Intent()
            .setAction(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
            .setData(Uri.parse(String.format("package:%s", getPackageName())));

    unknownAppSourceDialog.launch(unknownAppSourceIntent);
} else {
    // App already have the permission to install so launch the APK installation.
    startActivity(intent);
}

确保将以下代码添加到您的活动中以接收意图结果。

ActivityResultLauncher<Intent> unknownAppSourceDialog = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() == Activity.RESULT_OK) {
            // User has allowed app to install APKs
            // so we can now launch APK installation.
            startActivity(intent);
        }
    });
于 2016-10-19T12:17:27.877 回答
17

我在调用开始活动时遇到了这个问题。暂停我当前的活动后,它突然回来并调用了onResume。就像什么都没发生一样。我的问题是清单中的这个权限:

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

几乎没有人提到这一点。所以记住这一点。在 sdk >= 24 中,您需要使用提供程序,因为它需要在 sdk 24 以下以 file:/// 开头的意图,您应该提供以 content:/// 开头的 uri,这就是我们需要 sdk 24 及以上版本的文件提供程序的原因。我认为我不需要为此编写任何代码,因为@just_user 已经写了正确的答案。 https://stacklearn.ir

于 2019-08-14T09:06:13.943 回答
6

这可能是问题,你有

intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 

在你的例子中应该是

install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

因为 install 是意图的名称。

于 2016-09-14T12:53:37.347 回答
2

您应该注意,对于 API < 24,您需要使用:

        setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive")

而不是单独设置数据和类型:

data = Uri.fromFile(apkFile)
    type = "application/vnd.android.package-archive"

否则,你会得到 ActivityNotFoundException

于 2018-10-24T08:33:21.210 回答
0

对于所有面临“解析此包时出现问题”问题的人。

手动设置权限。

ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);

请参阅此示例: 以编程方式下载并安装应用程序

于 2022-03-03T11:33:48.370 回答