android權限再次探索筆記記錄 以前只是看一看找不到感覺,今天就要上手摸一摸結果發現坑多啊

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation? 
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {

        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
//異步顯示對用戶的擴展* * *不阻止
//這個線程等待用戶的響應!用戶后
//參考解釋,請再次請求許可。
    } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}



@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

總結

ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.READ_CONTACTS)
判斷是否有這個權限,有權限返回```PackageManager.PERMISSION_GRANTED``

shouldShowRequestPermissionRationale

onRequestPermissionsResult 在點擊拒絕或者同意權限后回調

比較困惑的還是shouldShowRequestPermissionRationale根據方法得說明,翻譯如下

*獲取是否應該以請求請求的理由顯示UI。
*只有在沒有權限和上下文的情況下才應該這樣做。
*請求的權限沒有明確地傳達給用戶。
*授予這個權限會有什么好處。

*例如,如果您編寫相機應用程序,請求相機許可
*將被用戶預期,并且沒有理由為什么它被請求是
*需要。然而,如果應用程序需要標記照片的位置,那么非技術。
*精明的用戶可能想知道位置如何與拍照有關。在這種情況下
*您可以選擇以請求此權限的理由來顯示UI。

谷歌翻譯如下

*獲取您是否應該以請求許可的理由顯示UI。
*只有在您沒有權限和上下文的情況下,您才應該這樣做
*所請求的許可不明確地與用戶進行通信
*授予此權限會有什么好處。
* <p>
*例如,如果您編寫相機應用程序,請求相機權限
*是用戶期望的,并且沒有理由說明它為什么被要求
*需要。但是,如果應用程序需要位置標記照片,然后是非技術
*精明的用戶可能想知道拍攝地點與拍照有何關系。在這種情況下
*您可以選擇以請求此權限的理由顯示用戶界面。

* 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.

關鍵注釋

 @return Whether you can show permission rationale UI.
Whether you can show permission rationale UI.
你是否可以顯示告知用戶權限理由的界面 如果可以返回true

目標sdk低于23的體現

W/PermissionUtil: =========================================
W/PermissionUtil: checkSelfPermission:android.permission.SYSTEM_ALERT_WINDOW:未獲得/拒絕
    shouldShowRequestPermissionRationale:android.permission.SYSTEM_ALERT_WINDOW result不應該顯示權限說明
W/PermissionUtil: requestPermissions:[android.permission.SYSTEM_ALERT_WINDOW] requestCode2
W/PermissionUtil: onRequestPermissionsResult: requestCode ,result:,grantResultslength:0
    彈出系統對話框開始
 E/AndroidRuntime: FATAL EXCEPTION: main

沒有系統對話框權限shouldShowRequestPermissionRationale:android =false如果依然嘗試申請,那么回調 onRequestPermissionsResult返回的結果數組長度為0 如果嘗試彈出當然是崩潰
如果目標sdk大于等于23,結果 還是 直接 shouldShowRequestPermissionRationale:android false onRequestPermissionsResult有值,但是為0 ,換了2個手機都這樣,有點崩潰,暫時放棄了,我有點懷疑小米和華為手機了.無論如何都不給彈出了,我卸載重裝都這樣,這不坑爹么
然后測試調用相機權限,成功彈出了,特么系統對話框的權限我突然想起來了,在高版本彈出系統對話框需要另外一種方式,叫啟用應用上層顯示的那種,這搞毛線,浪費我半天時間糾結了。

好了下面是我的日志調試工具

package cn.qssq666.robot.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.WindowManager;

import java.util.Arrays;

/**
 * Created by qssq on 2018/4/21 qssq666@foxmail.com
 */
public class PermissionUtil {

    private static final String TAG = "PermissionUtil";
    public static boolean debug=true;

    public static void onRequestPermissionsResult(Activity activity, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {




        Log.w(TAG, "onRequestPermissionsResult:" + " requestCode ,result:" + getPermissionsResultMsg(permissions, grantResults)+",grantResultslength:"+grantResults.length);


    }

    private static String getPermissionsResultMsg(String[] permissions, int[] grantResults) {


        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < permissions.length; i++) {


            stringBuilder.append(printPermission(permissions[i]) + ":" + getResultMsg(grantResults[i]) + "\n");
        }


        return stringBuilder.toString();
    }

    public static void requestPermissions(Activity activity, String[] permissions, int requestCode) {


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            activity.requestPermissions(permissions,requestCode);
        Log.w(TAG, "requestPermissions:" + printPermissions(permissions) + " requestCode" + requestCode);
        }else{

        }

    }

    public static int checkSelfPermission(Activity activity, String permission) {
        if(debug){
            Log.w(TAG,"=========================================");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int i = activity.checkSelfPermission(permission);

            if (debug) {
                Log.w(TAG, "checkSelfPermission:" + printPermission(permission) + ":" + getResultMsg(i));
            }

            return i;
        }
        if (debug) {
            Log.w(TAG, "Build.VERSION.SDK_INT <23 checkSelfPermission:" + printPermission(permission) + ":" + getResultMsg(PackageManager.PERMISSION_GRANTED));


        }
        return PackageManager.PERMISSION_GRANTED;
    }

    public static String printPermission(String permission) {
        return permission;

    }

    public static String printPermissions(String[] permission) {
        return Arrays.toString(permission);

    }

    /*
    是否應該顯示 請求權限信息
     */
    public static boolean shouldShowRequestPermissionRationale(Activity activity, String permissionRationale) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            boolean result = activity.shouldShowRequestPermissionRationale(permissionRationale);
            if (debug) {
                Log.w(TAG, "shouldShowRequestPermissionRationale:" + printPermission(permissionRationale) + " result" + getRationaleResultMsg(result));
            }
        } else {
                Log.w(TAG, "shouldShowRequestPermissionRationale <23 false" );

        }

        return false;
    }

    private static String getRationaleResultMsg(boolean result) {
        return result ? "應該顯示權限說明" : "不應該顯示權限說明";
    }

    public static String getResultMsg(int permissionCode) {
        if (permissionCode == PackageManager.PERMISSION_GRANTED) {
            return "獲得/成功";
        } else {
            return "未獲得/拒絕";

        }
    }

    public static void showSystemDialog(Activity mainActivity) {

        if(debug){
            Log.w(TAG,"彈出系統對話框開始");
            AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);

            builder.setMessage("我是系統對話框");
            Dialog dialog= builder.create();
            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
//            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);


            dialog.show();
            Log.w(TAG,"彈出系統對話框結束");
        }
    }
}

        if (PermissionUtil.checkSelfPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW) == PackageManager.PERMISSION_GRANTED) {
            registerWakeLock();
            Log.w(TAG, "shouldShowRequestPermissionRationale not-call  has granted permission");
        } else {


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (PermissionUtil.shouldShowRequestPermissionRationale(this,Manifest.permission.SYSTEM_ALERT_WINDOW)) {
                    Log.w(TAG, "shouldShowRequestPermissionRationale call");

                    PermissionUtil.requestPermissions(this,new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW}, REQUEST_LOCK);

                } else {
                    PermissionUtil.requestPermissions(this,new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW}, REQUEST_LOCK);
                    Log.w(TAG, "shouldShowRequestPermissionRationale not-call");

                }
            } else {

                Log.w(TAG, "low api not request permissions");
            }
        }

最后附上官方的demo 地址
https://github.com/googlesamples/android-RuntimePermissions/#readme
從下面代碼可以看出來,思路是先檢查權限,如果 沒有獲取到 就調用requestContactsPermissions 判斷是否應該提示則返回true
,但是不過結果true or false 都調用了 下載demo 發現項目并不能編譯,越來缺少了build.gradle 然后又發現缺少了design包然后又發現缺少了一個圖片,經過修改正常運行,并且也能正常提示,所以這讓我懷疑人生了額。
經過仔細思考發現清單文件是關鍵

下面是demo的部分代碼
清單是必須填寫的,不然低版本沒法兼容的.

    <!-- BEGIN_INCLUDE(manifest) -->

    <!-- Note that all required permissions are declared here in the Android manifest.
     On Android M and above, use of these permissions is only requested at run time. -->
    <uses-permission android:name="android.permission.CAMERA" />

    <!-- The following permissions are only requested if the device is on M or above.
     On older platforms these permissions are not requested and will not be available. -->
    <uses-permission-sdk-23 android:name="android.permission.READ_CONTACTS" />
    <uses-permission-sdk-23 android:name="android.permission.WRITE_CONTACTS" />
         .requestPermissions(MainActivity.this, PERMISSIONS_CONTACT,
                                            REQUEST_CONTACTS);

onRequestPermissionsResult判斷操作結果, 成功則提示permision_available_camera的snackbar提示

            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Camera permission has been granted, preview can be displayed
                Log.i(TAG, "CAMERA permission has now been granted. Showing preview.");
                Snackbar.make(mLayout, R.string.permision_available_camera,
                        Snackbar.LENGTH_SHORT).show();

所有邏輯代碼


    /**
     * Called when the 'show camera' button is clicked.
     * Callback is defined in resource layout definition.
     */
    public void showContacts(View v) {
        Log.i(TAG, "Show contacts button pressed. Checking permissions.");

        // Verify that all required contact permissions have been granted.
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            // Contacts permissions have not been granted.
            Log.i(TAG, "Contact permissions has NOT been granted. Requesting permissions.");
            requestContactsPermissions();

        } else {

            // Contact permissions have been granted. Show the contacts fragment.
            Log.i(TAG,
                    "Contact permissions have already been granted. Displaying contact details.");
            showContactDetails();
        }
    }

    /**
     * Requests the Contacts permissions.
     * If the permission has been denied previously, a SnackBar will prompt the user to grant the
     * permission, otherwise it is requested directly.
     */
    private void requestContactsPermissions() {
        // BEGIN_INCLUDE(contacts_permission_request)
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_CONTACTS)
                || ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_CONTACTS)) {

            // Provide an additional rationale to the user if the permission was not granted
            // and the user would benefit from additional context for the use of the permission.
            // For example, if the request has been denied previously.
            Log.i(TAG,
                    "Displaying contacts permission rationale to provide additional context.");

            // Display a SnackBar with an explanation and a button to trigger the request.
            Snackbar.make(mLayout, R.string.permission_contacts_rationale,
                    Snackbar.LENGTH_INDEFINITE)
                    .setAction(R.string.ok, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ActivityCompat
                                    .requestPermissions(MainActivity.this, PERMISSIONS_CONTACT,
                                            REQUEST_CONTACTS);
                        }
                    })
                    .show();
        } else {
            // Contact permissions have not been granted yet. Request them directly.
            ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
        }
        // END_INCLUDE(contacts_permission_request)
    }


    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {

        if (requestCode == REQUEST_CAMERA) {
            // BEGIN_INCLUDE(permission_result)
            // Received permission result for camera permission.
            Log.i(TAG, "Received response for Camera permission request.");

            // Check if the only required permission has been granted
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Camera permission has been granted, preview can be displayed
                Log.i(TAG, "CAMERA permission has now been granted. Showing preview.");
                Snackbar.make(mLayout, R.string.permision_available_camera,
                        Snackbar.LENGTH_SHORT).show();
            } else {
                Log.i(TAG, "CAMERA permission was NOT granted.");
                Snackbar.make(mLayout, R.string.permissions_not_granted,
                        Snackbar.LENGTH_SHORT).show();

            }
            // END_INCLUDE(permission_result)

        } else if (requestCode == REQUEST_CONTACTS) {
            Log.i(TAG, "Received response for contact permissions request.");

            // We have requested multiple permissions for contacts, so all of them need to be
            // checked.
            if (PermissionUtil.verifyPermissions(grantResults)) {
                // All required permissions have been granted, display contacts fragment.
                Snackbar.make(mLayout, R.string.permision_available_contacts,
                        Snackbar.LENGTH_SHORT)
                        .show();
            } else {
                Log.i(TAG, "Contacts permissions were NOT granted.");
                Snackbar.make(mLayout, R.string.permissions_not_granted,
                        Snackbar.LENGTH_SHORT)
                        .show();
            }

        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

官方的demo 缺少了一個 build.gradle和一個圖片,能不能修復看你們的本事了,我已經告訴你們了 哈哈,

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26



    defaultConfig {
        applicationId "com.example.android.system.runtimepermissions"
        minSdkVersion 14
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:27.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.android.support:design:27.1.0'
}

https://developer.android.com/training/permissions/requesting.html
https://developer.android.google.cn/training/permissions/requesting.html
http://www.lxweimin.com/p/e1ab1a179fbb

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,523評論 25 708
  • 用兩張圖告訴你,為什么你的 App 會卡頓? - Android - 掘金 Cover 有什么料? 從這篇文章中你...
    hw1212閱讀 12,970評論 2 59
  • 1. Android 6.0 在運行時請求權限介紹 從 Android 6.0(API 級別 23)開始,用戶開始...
    conio閱讀 4,275評論 0 6
  • 人每天都在思考,回顧過去,展望未來。如果只是簡單思考,如同做白日夢一般,想法在腦海里一閃而過,成了過眼云煙。如果進...
    庚翼閱讀 183評論 1 2
  • 新購的HL-1029高透明 雙組分有機硅膠 和128FR 黑色 導熱阻燃絕緣 柔性雙組分環氧樹脂膠 經過測試,10...
    hydro閱讀 295評論 0 0