android權(quán)限再次探索筆記記錄 以前只是看一看找不到感覺,今天就要上手摸一摸結(jié)果發(fā)現(xiàn)坑多啊

// 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.
//異步顯示對用戶的擴(kuò)展* * *不阻止
//這個(gè)線程等待用戶的響應(yīng)!用戶后
//參考解釋,請?jiān)俅握埱笤S可。
    } 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
    }
}

總結(jié)

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

shouldShowRequestPermissionRationale

onRequestPermissionsResult 在點(diǎn)擊拒絕或者同意權(quán)限后回調(diào)

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

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

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

谷歌翻譯如下

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

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

關(guān)鍵注釋

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

目標(biāo)sdk低于23的體現(xiàn)

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

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

好了下面是我的日志調(diào)試工具

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);

    }

    /*
    是否應(yīng)該顯示 請求權(quán)限信息
     */
    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 ? "應(yīng)該顯示權(quán)限說明" : "不應(yīng)該顯示權(quán)限說明";
    }

    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,"彈出系統(tǒng)對話框開始");
            AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);

            builder.setMessage("我是系統(tǒng)對話框");
            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,"彈出系統(tǒng)對話框結(jié)束");
        }
    }
}

        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
從下面代碼可以看出來,思路是先檢查權(quán)限,如果 沒有獲取到 就調(diào)用requestContactsPermissions 判斷是否應(yīng)該提示則返回true
,但是不過結(jié)果true or false 都調(diào)用了 下載demo 發(fā)現(xiàn)項(xiàng)目并不能編譯,越來缺少了build.gradle 然后又發(fā)現(xiàn)缺少了design包然后又發(fā)現(xiàn)缺少了一個(gè)圖片,經(jīng)過修改正常運(yùn)行,并且也能正常提示,所以這讓我懷疑人生了額。
經(jīng)過仔細(xì)思考發(fā)現(xiàn)清單文件是關(guān)鍵

下面是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判斷操作結(jié)果, 成功則提示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 缺少了一個(gè) build.gradle和一個(gè)圖片,能不能修復(fù)看你們的本事了,我已經(jīng)告訴你們了 哈哈,

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,923評論 6 535
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,740評論 3 420
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 176,856評論 0 380
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,175評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,931評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,321評論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,383評論 3 443
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,533評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,082評論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,891評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,067評論 1 371
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,618評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,319評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,732評論 0 27
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,987評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,794評論 3 394
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,076評論 2 375

推薦閱讀更多精彩內(nèi)容

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