Android 6.0动态权限适配和 7.0 FileProvider的使用

当项目中compileSdkVersion以及targetSdkVersion从22升级到23以及更高之后,就需要注意到6.0权限的动态申请问题,以及7.0系统访问存储空间的时候,FileProvider的使用,如果没有注意到或者使用不好,则会引起app的Crash问题

6.0动态权限适配

6.0系统以后,Android对于敏感和危险权限,为了用户信息的安全,禁止随意申请,必须动态申请,经过用户同意之后,才可以获得和使用此权限

检查权限 checkSelfPermission

主要通过ActivityCompat或者ContextCompat中的checkSelfPermission方法检查,返回值为int

  • PackageManager.PERMISSION_GRANTED 授权同意
  • PackageManager.PERMISSION_DENIED 授权失败,权限请求被拒绝
int result = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_SETTINGS);

 /**
     * Determine whether you have been granted a particular permission.
     *
     * @param permission The name of the permission being checked.
     *
     * @return {@link android.content.pm.PackageManager#PERMISSION_GRANTED} if you have the
     * permission, or {@link android.content.pm.PackageManager#PERMISSION_DENIED} if not.
     *
     * @see android.content.pm.PackageManager#checkPermission(String, String)
     */
    public static int checkSelfPermission(@NonNull Context context, @NonNull String permission) {
        if (permission == null) {
            throw new IllegalArgumentException("permission is null");
        }

        return context.checkPermission(permission, android.os.Process.myPid(), Process.myUid());
    }
再次请求确认 shouldShowRequestPermissionRationale
ActivityCompat.shouldShowRequestPermissionRationale(Activity activity, String permission)

方法源码解释
   /**
     * Gets whether you should show UI with rationale for requesting a permission.
     * You should do this only if you do not have the permission and the context in
     * which the permission is requested does not clearly communicate to the user
     * what would be the benefit from granting this permission.
     * 

* For example, if you write a camera app, requesting the camera permission * would be expected by the user and no rationale for why it is requested is * needed. If however, the app needs location for tagging photos then a non-tech * savvy user may wonder how location is related to taking photos. In this case * you may choose to show UI with rationale of requesting this permission. *

* * @param activity The target activity. * @param permission A permission your app wants to request. * @return Whether you can show permission rationale UI. * * @see #checkSelfPermission(android.content.Context, String) * @see #requestPermissions(android.app.Activity, String[], int) */ public static boolean shouldShowRequestPermissionRationale(@NonNull Activity activity, @NonNull String permission) { if (Build.VERSION.SDK_INT >= 23) { return ActivityCompatApi23.shouldShowRequestPermissionRationale(activity, permission); } return false; }

判断是否有必要向用户解释为什么要这项权限。如果应用第一次请求过此权限,但是被用户拒绝了,则之后调用该方法将返回 true,此时就有必要向用户详细说明需要此权限的原因,返回true的时候,基本上就是申请权限操作最后一次挣扎的机会了
如果第二次再请求此权限时,用户勾选了权限请求对话框的“不再询问”,则此方法返回 false。如果设备规范禁止应用拥有该权限,此方法也返回 false。

请求权限 requestPermissions
  ActivityCompat.requestPermissions(this, permission, 123)
权限申请结果处理

重写Activity中的onRequestPermissionsResult方法

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        var isGranted = false
        when (requestCode) {
            PERMISSION_REQUEST_SINGLE -> {
                isGranted = if (grantResults.size == 1) grantResults[0] == PackageManager.PERMISSION_GRANTED else false
            }
            PERMISSION_REQUEST_MULTI -> {
                isGranted = true
                for (it in grantResults) {
                    if (it == PackageManager.PERMISSION_DENIED) {
                        isGranted = false
                        break
                    }
                }
            }
        }
        if (isGranted) {
            onPermissonGranted()
        } else {
            onPermissonGrantFailed()
        }
    }

对于shouldShowRequestPermissionRationale方法的常规使用如下代码:

override fun onPermissionGrantFailed() {
        super.onPermissionGrantFailed()
        var isSend = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)

        var dialog = AlertDialog.Builder(this).apply {
            setMessage("该功能需要拍照权限,否则功能将不能使用")
            setPositiveButton(if (isSend) "重新申请" else "手动开启")
            { dialog, which ->
                if (isSend) {
                    requestPermission(PERMISSION_REQUEST_MULTI, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                } else {
                    startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                        data = Uri.fromParts("package", packageName, null)
                    })
                }
            }
            setNegativeButton("取消") { dialog, which ->
                dialog.dismiss()
            }
        }
        dialog.show()
    }

7.0 FileProvider的使用

FileProvider是7.0系统新增的功能类,主要是为了访问SD卡文件或者系统应用之间共享文件的时候,采用content://author的方法来兼容处理,官方解释如下:
要在应用间共享文件,您应发送一项 content:// URI,并授予 URI 临时访问权限。进行此授权的最简单方式是使用 FileProvider 类。如需了解有关权限和共享文件的详细信息,请参阅共享文件。
https://developer.android.com/about/versions/nougat/android-7.0-changes.html#accessibility

AndroidManifest中声明FileProvider


            
  

kt_file_paths



    
    

    

    

    
    


  • 代表设备的根目录new File("/");
  • 代表context.getFilesDir()
  • 代表context.getCacheDir()
  • 代表Environment.getExternalStorageDirectory()
  • 代表context.getExternalFilesDirs()
  • 代表getExternalCacheDirs()
    FileProvider的源码如下图:


    Android 6.0动态权限适配和 7.0 FileProvider的使用_第1张图片
    FileProvider.jpg

每个节点都包含name和path两个属性
path表示根目录中的子目录,比如:


//比如
var pic = Environment.getExternalStorageDirectory().absolutePath + "/pics/" + System.currentTimeMillis() + ".jpg"

/storage/emulated/0/pics/1528710742956.jpg

FileProvider.getUriForFile(this@KtFileProviderActivity, "$packageName.fileProvider", file)
转换之后的路径
content://com.kt.video.fileProvider/external/1528710742956.jpg

上述例子中的external代替了/storage/emulated/0/pics/这个绝对路径的映射 content://com.kt.video.fileProvider/external/1528710742956.jpg

常用的打开相机代码修改:

private fun openCamera() {
        var pic = Environment.getExternalStorageDirectory().absolutePath + "/pics/" + System.currentTimeMillis() + ".jpg"
        var file = File(pic)
        var uri: Uri? = null
        try {
            uri = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                FileProvider.getUriForFile(this@KtFileProviderActivity, "$packageName.fileProvider", file)
            } else {
                Uri.fromFile(file)
            }
            startActivity(Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {
                putExtra(MediaStore.EXTRA_OUTPUT, uri)
            })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

安装apk的代码修改:

fun installApk(context: Context, fileName: String) {
        val apkFile = File(fileName)
        if (apkFile.exists()) {
            context.startActivity(Intent(Intent.ACTION_VIEW).apply {
                val data: Uri
                // 判断系统版本是否大于等于7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    data = FileProvider.getUriForFile(context, "$packageName.fileProvider", apkFile)
                    // 给目标应用一个临时授权
                    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                } else {
                    data = Uri.fromFile(apkFile)
                }
                setDataAndType(data, "application/vnd.android.package-archive")
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            })
        } else {
            Toast.makeText(context, context.getString(R.string.apk_not_exit), Toast.LENGTH_SHORT).show()
        }
    }

你可能感兴趣的:(Android 6.0动态权限适配和 7.0 FileProvider的使用)