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
https://www.jianshu.com/p/e1ab1a179fbb

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,080评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,422评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,630评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,554评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,662评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,856评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,014评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,752评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,212评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,541评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,687评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,347评论 4 331
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,973评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,777评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,006评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,406评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,576评论 2 349

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,803评论 25 707
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,699评论 2 59
  • 1. Android 6.0 在运行时请求权限介绍 从 Android 6.0(API 级别 23)开始,用户开始...
    conio阅读 4,179评论 0 6
  • 人每天都在思考,回顾过去,展望未来。如果只是简单思考,如同做白日梦一般,想法在脑海里一闪而过,成了过眼云烟。如果进...
    庚翼阅读 159评论 1 2
  • 新购的HL-1029高透明 双组分有机硅胶 和128FR 黑色 导热阻燃绝缘 柔性双组分环氧树脂胶 经过测试,10...
    hydro阅读 281评论 0 0