嗨stackoverflow im真的很难打开在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()
是指用于应用程序专用的文件,因此包含应用程序包名称的路径(从技术上讲,此目录是公共目录,但仍不是您要查找的目录)。
File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
然后,您可以创建File
下载文件的表示形式:
File apk = new File(downloads, filename);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句