Android 7.0升级软件出错

现象:

在Android7.0及其以上版本手机上,在升级到线上最新的版本时,会自动下载,可以安装,但是安装到最后,会出现解析包出现错误


解决步骤:

  1.在AndroidManifest中申明fileProvider

<provider
    android:name="android.support.v4.content.FileProvider"  //android V4 包中的类FileProvider
    android:authorities="com.**********.fileProvider"  //软件主包名加.fileProvider形式,防止重名
    android:exported="false"   //设置不允许导出,fileProvider应该是私有的
    android:grantUriPermissions="true">  //允许获得文件的临时访问权限
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />   //设置fileProvider访问的文件路径
</provider>

2.在res文件夹下建立xml文件夹,在xml文件夹下建立file_paths.xml

//作用:为了有对url指向的文件有临时访问权限,file_paths.xml的作用是返回content://URI
<?xml version="1.0" encoding="utf-8"?>
<paths>
     //其实path代表的全路径是Environment.getExternalStorageDirectory()+/Android/data/*********/
    <external-path path="Android/data/*********/" name="files_root" /> 
    <external-path path="." name="external_storage_root" />
</paths>

3.安装apk方法

private void openFile(File f) {
   Intent intent = new Intent();
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //如果是7.0以上的版本
      try {
         //设置具有访问uri临时读权限 
         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
         //软件主包名加.fileProvider
         Uri contentUri = FileProvider.getUriForFile(WelcomeActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", f); 
        //安装apk的文件类型
         intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
      }catch(Exception e){
         String s=e.getMessage();
         e.printStackTrace();
      }
   } else {//7.0以下的安装方法
      intent.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive");
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   }
   //由于上面的设置,则如果启动,就会打开安装activity
   intent.setAction(android.content.Intent.ACTION_VIEW);
   try {
      //启动activity
      this.startActivity(intent);
   }catch (Exception e){
      String s=e.getMessage();
      e.printStackTrace();
   }
}

猜你喜欢

转载自blog.csdn.net/sunshine_0707/article/details/84065183
今日推荐