Android 6.0動(dòng)態(tài)權(quán)限適配和 7.0 FileProvider的使用

當(dāng)項(xiàng)目中compileSdkVersion以及targetSdkVersion從22升級(jí)到23以及更高之后,就需要注意到6.0權(quán)限的動(dòng)態(tài)申請(qǐng)問(wèn)題,以及7.0系統(tǒng)訪問(wèn)存儲(chǔ)空間的時(shí)候,F(xiàn)ileProvider的使用,如果沒(méi)有注意到或者使用不好,則會(huì)引起app的Crash問(wèn)題

6.0動(dòng)態(tài)權(quán)限適配

6.0系統(tǒng)以后,Android對(duì)于敏感和危險(xiǎn)權(quán)限,為了用戶信息的安全,禁止隨意申請(qǐng),必須動(dòng)態(tài)申請(qǐng),經(jīng)過(guò)用戶同意之后,才可以獲得和使用此權(quán)限

檢查權(quán)限 checkSelfPermission

主要通過(guò)ActivityCompat或者ContextCompat中的checkSelfPermission方法檢查,返回值為int

  • PackageManager.PERMISSION_GRANTED 授權(quán)同意
  • PackageManager.PERMISSION_DENIED 授權(quán)失敗,權(quán)限請(qǐng)求被拒絕
int result = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_SETTINGS);

 /**
     * Determine whether <em>you</em> 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());
    }
再次請(qǐng)求確認(rèn) 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.
     * <p>
     * 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.
     * </p>
     *
     * @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;
    }

判斷是否有必要向用戶解釋為什么要這項(xiàng)權(quán)限。如果應(yīng)用第一次請(qǐng)求過(guò)此權(quán)限,但是被用戶拒絕了,則之后調(diào)用該方法將返回 true,此時(shí)就有必要向用戶詳細(xì)說(shuō)明需要此權(quán)限的原因,返回true的時(shí)候,基本上就是申請(qǐng)權(quán)限操作最后一次掙扎的機(jī)會(huì)了
如果第二次再請(qǐng)求此權(quán)限時(shí),用戶勾選了權(quán)限請(qǐng)求對(duì)話框的“不再詢問(wèn)”,則此方法返回 false。如果設(shè)備規(guī)范禁止應(yīng)用擁有該權(quán)限,此方法也返回 false。

請(qǐng)求權(quán)限 requestPermissions
  ActivityCompat.requestPermissions(this, permission, 123)
權(quán)限申請(qǐng)結(jié)果處理

重寫(xiě)Activity中的onRequestPermissionsResult方法

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, 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()
        }
    }

對(duì)于shouldShowRequestPermissionRationale方法的常規(guī)使用如下代碼:

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

        var dialog = AlertDialog.Builder(this).apply {
            setMessage("該功能需要拍照權(quán)限,否則功能將不能使用")
            setPositiveButton(if (isSend) "重新申請(qǐng)" else "手動(dòng)開(kāi)啟")
            { 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系統(tǒng)新增的功能類(lèi),主要是為了訪問(wèn)SD卡文件或者系統(tǒng)應(yīng)用之間共享文件的時(shí)候,采用content://author的方法來(lái)兼容處理,官方解釋如下:
要在應(yīng)用間共享文件,您應(yīng)發(fā)送一項(xiàng) content:// URI,并授予 URI 臨時(shí)訪問(wèn)權(quán)限。進(jìn)行此授權(quán)的最簡(jiǎn)單方式是使用 FileProvider 類(lèi)。如需了解有關(guān)權(quán)限和共享文件的詳細(xì)信息,請(qǐng)參閱共享文件。
https://developer.android.com/about/versions/nougat/android-7.0-changes.html#accessibility

AndroidManifest中聲明FileProvider

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/kt_file_paths" />
  </provider>

kt_file_paths

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <root-path
        name="root"
        path="" />
    <files-path
        name="files"
        path="pics" />

    <cache-path
        name="cache"
        path="pics" />

    <external-path
        name="external"
        path="pics" />

    <external-files-path
        name="external_file_path"
        path="Android/data/pics" />
    <external-cache-path
        name="external_cache_path"
        path="pics" />

</paths>
  • <root-path/> 代表設(shè)備的根目錄new File("/");
  • <files-path/> 代表context.getFilesDir()
  • <cache-path/> 代表context.getCacheDir()
  • <external-path/> 代表Environment.getExternalStorageDirectory()
  • <external-files-path>代表context.getExternalFilesDirs()
  • <external-cache-path>代表getExternalCacheDirs()
    FileProvider的源碼如下圖:


    FileProvider.jpg

每個(gè)節(jié)點(diǎn)都包含name和path兩個(gè)屬性
path表示根目錄中的子目錄,比如:

<external-path
        name="external"
        path="pics" />
//比如
var pic = Environment.getExternalStorageDirectory().absolutePath + "/pics/" + System.currentTimeMillis() + ".jpg"

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

FileProvider.getUriForFile(this@KtFileProviderActivity, "$packageName.fileProvider", file)
轉(zhuǎn)換之后的路徑
content://com.kt.video.fileProvider/external/1528710742956.jpg

上述例子中的external代替了/storage/emulated/0/pics/這個(gè)絕對(duì)路徑的映射 content://com.kt.video.fileProvider/external/1528710742956.jpg

常用的打開(kāi)相機(jī)代碼修改:

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
                // 判斷系統(tǒng)版本是否大于等于7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    data = FileProvider.getUriForFile(context, "$packageName.fileProvider", apkFile)
                    // 給目標(biāo)應(yīng)用一個(gè)臨時(shí)授權(quán)
                    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()
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容