Android项目开发中常常遇到下载更新的需求,之前调用系统安装器执行安装操做代码以下:html
Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive"); context.startActivity(intent);
若是Android系统为7.0及以上时则会报异常FileUriExposedException,这是因为安卓官方为了提升私有文件的安全性,面向 Android 7.0 或更高版本的应用私有目录被限制访问 (0700)。此设置可防止私有文件的元数据泄漏,如它们的大小或存在性。传递file:// URI 可能给接收器留下没法访问的路径。所以,尝试传递 file:// URI 会触发 FileUriExposedException。所以须要使用 FileProvider。java
<application android:allowBackup="true" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:theme="@style/AppTheme"> <provider android:name="android.support.v4.content.FileProvider" android:authorities="packageName.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"/> </provider> </application>
在项目res路径下新建名为xml的路径,在xml路径下新建名为file_paths.xml的文件,在file_paths.xml文件中增长以下内容指定分享的路径:android
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <external-path path="Android/data/packageName/" name="files_root" /> </PreferenceScreen>
Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", new File(path)); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(contentUri, context.getContentResolver().getType(contentUri)); //指定打开文件所调用的Activity,若不指定,则会弹出打开方式选择框, intent.setClassName("com.android.packageinstaller","com.android.packageinstaller.PackageInstallerActivity"); context.startActivity(intent);
如上代码虽然能够在Android7.0系统中正常安装apk,可是在低于Android7.0的系统中则不起做用,因此对apk安装调用方法进行封装,完美适配全部系统版本进行apk的安装调用。安全
/** * 安装apk * * @param context Application对象 * @param path * apk路径 */ public static void InstallApk(Context context, String path) { Intent intent = new Intent(); if (Build.VERSION.SDK_INT >= 24) {//Android 7.0以上 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", new File(path)); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(contentUri, context.getContentResolver().getType(contentUri)); //指定打开文件所调用的Activity intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity"); } else { intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive"); } context.startActivity(intent); }
清单文件配置的authorities的值必须与FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", new File(path));方法中第二个参数一致。app