我有一个下载apk文件的应用程序。在我的应用程序中,我下载了一个apk文件,并希望在下载完成后安装此apk文件。我使用API19在我的手机上测试它,它工作。但它在牛油糖上不起作用,version.how可以改变这段代码,使其真正在牛油糖和更高版本上工作。
安装apk的api低于24的代码如下:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/icm/" + fileName)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(intent);
在nougat版本和更高版本上不起作用的代码:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = FileProvider.getUriForFile(getContext(), getContext().getApplicationContext().getPackageName() + "clicksite.org.cafebazar.fileprovider", new File(Environment.getExternalStorageDirectory() + "/icm/" + fileName));
intent.setDataAndType(uri, "application/pdf");
getActivity().startActivity(intent);
android清单:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="clicksite.org.cafebazar">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<category android:name="android.intent.category.LAUNCHER"/>
<action android:name="android.intent.action.MAIN"/>
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
和res文件夹中xml目录下的provider_path.xml:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
请告诉我如何将此代码更改为适用于nougat版本或更高版本
发布于 2018-06-24 00:11:13
问题#1:错误的权限
Uri uri = FileProvider.getUriForFile(getContext(), getContext().getApplicationContext().getPackageName() + "clicksite.org.cafebazar.fileprovider", new File(Environment.getExternalStorageDirectory() + "/icm/" + fileName));
这不匹配:
android:authorities="${applicationId}.provider"
将前面的行更改为:
Uri uri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", new File(Environment.getExternalStorageDirectory(), "icm/" + fileName));
问题#2:错误的MIME类型
intent.setDataAndType(uri, "application/pdf");
APK文件不是PDF文件。将其更改为:
intent.setDataAndType(uri, "application/vnd.android.package-archive");
可能有比这两个更多的问题,因为你没有解释你的症状是什么。然而,这些问题肯定需要解决。我还建议在API14级和更高级别上使用using ACTION_INSTALL_PACKAGE
,而不是ACTION_VIEW
。
https://stackoverflow.com/questions/51002834
复制相似问题