您好,stackoverflow,我在 Android Nougat 上打开下载的 apk 非常困难。我知道文件提供程序需要被我使用,只是不知道如何输入正确的路径。应用程序崩溃或找不到文件。它总是打开/storage/emulated/0/Android/data/cf.vojtechh.apkmirror/Downloads - 当然不存在。我需要应用程序访问内部存储中的下载目录(类似于 Environment.getExternalStorageDirectory().getPath() + "/"+ Environment.DIRECTORY_DOWNLOADS + "/"+ fileName)
有什么想法吗?我已经在互联网上寻找这个一个多小时了,但我就是找不到它(我已经到了这一点,我非常生气,我想把崩溃留在那里并忽略它)
MainActivity.java
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
File apkfile = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), fileName);
Uri apkUri = FileProvider.getUriForFile(MainActivity.this, "cf.vojtechh.apkmirror.provider", apkfile);
String s = apkUri.toString();
Log.d("HERE!!",s);
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(apkUri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
} else {
File apkfile = new File(Environment.getExternalStorageDirectory().getPath() + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + fileName);
Uri apkUri = Uri.fromFile(apkfile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="Download" path="Download/"/>
</paths>
AndroidManifest.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="cf.vojtechh.apkmirror.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
最佳答案
尝试使用Environment#getExternalStoragePublicDirectory()
方法代替。 Context#getExternalFilesDir()
旨在用于您的应用程序私有(private)的文件,因此包含您的应用程序包名称的路径(从技术上讲,此目录是公共(public)的,但仍然不是您要查找的目录)。
File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
然后您可以创建下载文件的File
表示形式:
File apk = new File(downloads, filename);
关于java - 使用文件提供程序在 Android Nougat 上打开下载的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40494468/