android 代码打开权限,android开发权限询问的示例代码
现在基于信息安全问题,特别是版本是23以上权限越严格。
特别是拍照,读,写权限
一般权限允许过,下次就不用询问了的,所以很多应用都喜欢在首页或者启动页直接询问,不允许的就用不了1、下面给出封装好的类,至于什么时候调看项目需要
public class EasyPermissions {
private static final String TAG = "EasyPermissions";
public interface PermissionCallbacks extends
ActivityCompat.OnRequestPermissionsResultCallback {
void onPermissionsGranted(List perms);
void onPermissionsDenied(List perms);
}
/**
* Check if the calling context has a set of permissions.
*
* @param context the calling context.
* @param perms one ore more permissions, such as {@code android.Manifest.permission.CAMERA}.
* @return true if all permissions are already granted, false if at least one permission
* is not yet granted.
*/
public static boolean hasPermissions(Context context, String... perms) {
for (String perm : perms) {
boolean hasPerm = (ContextCompat.checkSelfPermission(context, perm) == PackageManager.PERMISSION_GRANTED);
if (!hasPerm) {
return false;
}
}
return true;
}
/**
* Request a set of permissions, showing rationale if the system requests it.
*
* @param object Activity or Fragment requesting permissions. Should implement
* {@link ActivityCompat.OnRequestPermissionsResultCallback}
* or
* {@link android.support.v13.app.FragmentCompat.OnRequestPermissionsResultCallback}
* @param rationale a message explaining why the application needs this set of permissions, will
* be displayed if the user rejects the request the first time.
* @param requestCode request code to track this request, must be < 256.
* @param perms a set of permissions to be requested.
*/
public static void requestPermissions(final Object object, String rationale,
final int requestCode, final String... perms) {
requestPermissions(object, rationale,
android.R.string.ok,
android.R.string.cancel,
requestCode, perms);
}
/**
* Request a set of permissions, showing rationale if the system requests it.
*
* @param object Activity or Fragment requesting permissions. Should implement
* {@link ActivityCompat.OnRequestPermissionsResultCallback}
* or
* {@link android.support.v13.app.FragmentCompat.OnRequestPermissionsResultCallback}
* @param rationale a message explaining why the application needs this set of permissions, will
* be displayed if the user rejects the request the first time.
* @param positiveButton custom text for positive button
* @param negativeButton custom text for negative button
* @param requestCode request code to track this request, must be < 256.
* @param perms a set of permissions to be requested.
*/
public static void requestPermissions(final Object object, String rationale,
@StringRes int positiveButton,
@StringRes int negativeButton,
final int requestCode, final String... perms) {
checkCallingObjectSuitability(object);
boolean shouldShowRationale = false;
for (String perm : perms) {
shouldShowRationale = shouldShowRationale || shouldShowRequestPermissionRationale(object, perm);
}
if (shouldShowRationale) {
//弹框询问
AlertDialog dialog = new AlertDialog.Builder(getActivity(object))
.setMessage(rationale)
.setPositiveButton(positiveButton, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
executePermissionsRequest(object, perms, requestCode);
}
})
.setNegativeButton(negativeButton, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing, user does not want to request
PermissionCallbacks callbacks = (PermissionCallbacks) object;
if(callbacks != null) {
callbacks.onPermissionsDenied(new ArrayList());
}
}
}).create();
dialog.show();
} else {
executePermissionsRequest(object, perms, requestCode);
}
}
/**
* Handle the result of a permission request, should be called from the calling Activity's
* {@link ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[])}
* method.
*
* If any permissions were granted or denied, the Activity will receive the appropriate
* callbacks through {@link PermissionCallbacks} and methods annotated with
* {@link AfterPermissionGranted} will be run if appropriate.
*
* @param requestCode requestCode argument to permission result callback.
* @param permissions permissions argument to permission result callback.
* @param grantResults grantResults argument to permission result callback.
* @param object the calling Activity or Fragment.
* @throws IllegalArgumentException if the calling Activity does not implement
* {@link PermissionCallbacks}.
*/
public static void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults, Object object) {
checkCallingObjectSuitability(object);
PermissionCallbacks callbacks = (PermissionCallbacks) object;
// Make a collection of granted and denied permissions from the request.
ArrayList granted = new ArrayList<>();
ArrayList denied = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
String perm = permissions[i];
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
granted.add(perm);
} else {
denied.add(perm);
}
}
// Report granted permissions, if any.
if (!granted.isEmpty()) {
// Notify callbacks
callbacks.onPermissionsGranted(granted);
}
// Report denied permissions, if any.
if (!denied.isEmpty()) {
callbacks.onPermissionsDenied(denied);
}
// If 100% successful, call annotated methods
if (!granted.isEmpty() && denied.isEmpty()) {
runAnnotatedMethods(object, requestCode);
}
}
private static boolean shouldShowRequestPermissionRationale(Object object, String perm) {
if (object instanceof Activity) {
return ActivityCompat.shouldShowRequestPermissionRationale((Activity) object, perm);
} else if (object instanceof Fragment) {
return ((Fragment) object).shouldShowRequestPermissionRationale(perm);
} else {
return false;
}
}
private static void executePermissionsRequest(Object object, String[] perms, int requestCode) {
checkCallingObjectSuitability(object);
if (object instanceof Activity) {
ActivityCompat.requestPermissions((Activity) object, perms, requestCode);
} else if (object instanceof Fragment) {
((Fragment) object).requestPermissions(perms, requestCode);
}
}
private static Activity getActivity(Object object) {
if (object instanceof Activity) {
return ((Activity) object);
} else if (object instanceof Fragment) {
return ((Fragment) object).getActivity();
} else {
return null;
}
}
private static void runAnnotatedMethods(Object object, int requestCode) {
Class clazz = object.getClass();
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(AfterPermissionGranted.class)) {
// Check for annotated methods with matching request code.
AfterPermissionGranted ann = method.getAnnotation(AfterPermissionGranted.class);
if (ann.value() == requestCode) {
// Method must be void so that we can invoke it
if (method.getParameterTypes().length > 0) {
throw new RuntimeException("Cannot execute non-void method " + method.getName());
}
try {
// Make method accessible if private
if (!method.isAccessible()) {
method.setAccessible(true);
}
method.invoke(object);
} catch (IllegalAccessException e) {
ILogger.e(TAG, "runDefaultMethod:IllegalAccessException", e);
} catch (InvocationTargetException e) {
ILogger.e(TAG, "runDefaultMethod:InvocationTargetException", e);
}
}
}
}
}
private static void checkCallingObjectSuitability(Object object) {
// Make sure Object is an Activity or Fragment
if (!((object instanceof Fragment) || (object instanceof Activity))) {
throw new IllegalArgumentException("Caller must be an Activity or a Fragment.");
}
// Make sure Object implements callbacks
if (!(object instanceof PermissionCallbacks)) {
throw new IllegalArgumentException("Caller must implement PermissionCallbacks.");
}
}}
注:这个类不是我写的,分享给大家
2、调用示例(activity或fragment):(方法调用的时机随你)
private void requestGalleryPermission() {
//权限参数可以添加很多,不固定参数的
if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
getPhotos();//如果具有权限做的操作
} else {
// Ask for one permission
EasyPermissions.requestPermissions(this, getString(R.string.permissions_tips_gallery),
GalleryFinal.PERMISSIONS_CODE_GALLERY, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
}
3、拒绝和允许做的操作(activity或fragment):
@Override
public void onPermissionsGranted(List list) {
//允许
getPhotos();
}
@Override
public void onPermissionsDenied(List list) {
//拒绝
mTvEmptyView.setText(R.string.permissions_denied_tips);
//mIvTakePhoto.setVisibility(View.GONE);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
android 代码打开权限,android开发权限询问的示例代码相关推荐
- android仿微信语音聊天功能,Android仿微信发送语音消息的功能及示例代码
微信的发送语音是有一个向上取消的,我们使用ontouchlistener来监听手势,然后做出相应的操作就行了. 直接上代码: //语音操作对象 private mediaplayer mplayer ...
- android百度地图例子,使用百度地图API进行Android地图应用开发(Eclipse)(示例代码)...
随着基于位置的服务的兴起,地图类App呈现爆发趋势.随着而来的是地图供应商开放大量的API.供开发人员开发基于PC或者移动端的应用程序. 如今我们研究使用百度地图SDK进行Android项目的开发. ...
- android打电话报告,Android开发学习——打电话应用(示例代码)
打电话应用 system/app/phone.apk 这个是打电话应用,这个Java API 不允许应用级程序员改写,系统级才可以 system/app/dialer.apk 这个是拨号器应用,可 ...
- android 如何打开s3db,Android开发教程:使用已有的SQL数据库
极品好儿媳全文阅读,燃料乙醇放量,嘉兴办公家具,应向阳,58会展网,证书挂靠,鱼缸清洗,qq蜡笔小新头像 我在sqliteadmin 创建好数据库StuDB,里面的表如下: 650) this.wid ...
- android第三方打开文件,Android第三方文件选择器aFileChooser使用方法详解
aFileChooser是android平台上的一个第三方文件选择器,其在github上的项目主页是:https://github.com/iPaulPro/aFileChooser aFileCho ...
- android camera2预览方向,Android Camera2预览偶尔会旋转90度(示例代码)
我正在使用Android的Camera2 API开发一些应用程序.到目前为止,我已经能够在TextureView中显示预览.该应用程序默认为横向模式.使用模拟器时,预览将显示为颠倒.在我的物理Nexu ...
- android 通知打开app,Android打开通知栏并回到主页的几种方式
用PendingIntent.getActivity创建通知栏 在MainActivity中增加点击事件,用来启动NotifyService和延迟2秒销毁MainActivity,如下面代码所示 In ...
- android莫名其妙打开支付宝,Android 7.0 无法拉起支付宝App
一.问题描述: 在 Android 7.0 和使用腾讯 X5 浏览器内核的 **WebView **上,无法拉起支付宝.而在之前版本的 WebView 上不存在. 支付宝平台上有相关提问: Andro ...
- android scheme打开app,android 通过Scheme链接启动app
一.参考文章: http://www..com/shadajin/p/5724117.html http://jingyan.baidu.com/article/c45ad29cd6b15505175 ...
最新文章
- 前端进阶(三) webpack处理vue以及vue-cli脚手架环境
- 查看进程运行状态的环境变量
- c++入门之初话结构体
- 2013年1月31号
- wireshark抓包常见提示含义解析
- opengl 球纹理旋转源代码
- db2 删除存储过程_数据库教程-SQL Server存储过程使用及异常处理
- 使用ViewContainerRef探索Angular DOM操作技术
- 程序员工作3年只涨2千,你不知道程序员有多难!
- cblas_saxpy catlas_sset
- ES6——Promise 对象
- DataSource接口 Connection pooling(连接池
- makefile中=、:=和+=的区别
- 四、对象创建和垃圾回收流程
- 收藏!深度学习必读10篇经典算法论文总结!
- IOS设备之armv6,armv7,armv7s,arm64
- 本地计算机如何使用代理服务器,自动设置代理ip
- delphi android 蓝牙,Android实例-Delphi开发蓝牙官方实例解析(XE10+小米2+小米5)
- 怎样获取Atlantic免费一年的VPS主机
- vue+element 获取中文首字母,转换成大写