Android 7.0 安裝Apk時報錯FileUriExposedException 解決

安裝Apk時報錯FileUriExposedException
1、AndroidManifest.xml寫入

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

2、聲明res/xml/file_paths
這裏寫圖片描述

3、file_paths.xml添加內容

<?xml version="1.0" encoding="utf-8"?>  
<paths>  
    <external-path path="Android/data/你的包名/" name="files_root" />  
    <external-path path="." name="external_storage_root" />  
</paths>  

4、啓動安裝Intent,代碼如下

public static void installApk(Context context, String fileName) {  
   Intent intent = new Intent(Intent.ACTION_VIEW);  
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  
      intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);  
      Uri contentUri = FileProvider.getUriForFile(context, "你的包名.fileprovider", new File(fileName));  
      intent.setDataAndType(contentUri, "application/vnd.android.package-archive");  
   } else {  
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
      intent.setDataAndType(Uri.parse("file://" + fileName),  
            "application/vnd.android.package-archive");  
   }  
   context.startActivity(intent);  
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章