Android7.0安装apk文件之后不弹出安装界面的问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xzx208/article/details/86678415

Android7.0以下的版本,别忘了加上:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  

Android7.0以上的版本,还需要加上权限:

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

完整的代码如下:

private void installApk() {
        File apkfile = new File(mSavePath, mFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri=null;
        //判断是否是Android 7.0以及更高的版本
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N) {
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(mContext,"你的包名.fileprovider",apkfile);
        }else{
            uri = Uri.fromFile(apkfile);
        }
 
        i.setDataAndType(uri,"application/vnd.android.package-archive");
        mContext.startActivity(i);
    }
如果报FileUriExposedException 异常(具体请百度),Android 7.0以上版本还需要在manifest.xml加上一个Provider

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="你的包名.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false"
            >
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>
对应的android:resource="@xml/file_paths"文件需要新建:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_storage_directory" path="." />
</paths>
加上“.”表示全部,具体请百度
 

猜你喜欢

转载自blog.csdn.net/xzx208/article/details/86678415