0
点赞
收藏
分享

微信扫一扫

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​​

举报
0 条评论