安卓6.0运行时权限申请参考

网友投稿 882 2022-11-25

安卓6.0运行时权限申请参考

安卓6.0运行时权限申请参考

PermissionHelper

package com.mlibs.library.permission;import android.Manifest;import android.annotation.TargetApi;import android.APP.Activity;import android.app.Fragment;import android.app.FragmentManager;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android-.Uri;import android.os.Build;import android.os.Bundle;import android.provider.Settings;import android.support.annotation.NonNull;import android.support.v4.content.ContextCompat;import com.mlibs.library.BuildConfig;import java.util.ArrayList;import java.util.Arrays;import java.util.Hashtable;import java.util.List;import java.util.Map;/** * 推荐使用: * //6.0权限申请 混淆:-dontwarn com.hjq.permissions.** * implementation 'com.hjq:xxpermissions:6.2' *

* 本工具类有很多问题,仅供参考 * 已知问题: * 1.已知不能在子线程运行 * 2.要注意内存溢出问题 * * @author mwq */public class PermissionHelper extends Fragment { private static final String TAG = "PermissionHelper"; private static List mRegisteredInManifestPermissions; // key=request_code private static Map mOnGrantedListeners; private static Map mOnDeniedListeners; private static int mRequestCode = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } /** * @param permissions e.g. {@link Manifest.permission#CAMERA} * @return true:全部授予 false:有没授予的权限存在 */ public static boolean isGranted(Activity activity, String... permissions) { checkManifestPermissions(activity, permissions); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { for (String permission : permissions) { if (activity.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED) { return false; } } } return true; } /** * @param grantedListener 运行权限全部授予 * @param deniedListener 运行权限没有全部授予 */ @TargetApi(Build.VERSION_CODES.M) public static void requestPermissions(Activity activity, OnPermissionGrantedListener grantedListener, OnPermissionDeniedListener deniedListener, String... permissions) { checkManifestPermissions(activity, permissions); if (isGranted(activity, permissions)) { if (grantedListener != null) grantedListener.onGranted(); return; } Fragment fragment = activity.getFragmentManager().findFragmentByTag(TAG); if (fragment == null) { fragment = new PermissionHelper(); final FragmentManager fragmentManager = activity.getFragmentManager(); fragmentManager.beginTransaction().add(fragment, TAG).commitAllowingStateLoss(); activity.runOnUiThread(new Runnable() { @Override public void run() { fragmentManager.executePendingTransactions(); } }); } mOnGrantedListeners.put(mRequestCode, grantedListener); mOnDeniedListeners.put(mRequestCode, deniedListener); fragment.requestPermissions(permissions, mRequestCode++); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (mOnGrantedListeners.containsKey(requestCode)) { // 这里规定全部权限都通过才算通过 boolean granted = true; // 在Activity A申请权限,然后马上跳转到Activity B,则grantResults.length=0 if (grantResults.length == 0) granted = false; for (int result : grantResults) { if (result == PackageManager.PERMISSION_DENIED) { granted = false; break; } } if (granted) { OnPermissionGrantedListener listener = mOnGrantedListeners.get(requestCode); if (listener != null) listener.onGranted(); } else { OnPermissionDeniedListener listener = mOnDeniedListeners.get(requestCode); if (listener != null) listener.onDenied(); } mOnGrantedListeners.remove(mRequestCode); mOnDeniedListeners.remove(mRequestCode); } mOnGrantedListeners.clear(); mOnGrantedListeners = null; mOnDeniedListeners.clear(); mOnDeniedListeners = null; if (mRegisteredInManifestPermissions != null) mRegisteredInManifestPermissions.clear(); mRegisteredInManifestPermissions = null; } /** * @param permission 单个权限 * @return 是否缺少某项权限 */ public boolean hasPermission(Context context, String permission) {// ActivityCompat.checkSelfPermission()//检查// ActivityCompat.requestPermissions()//请求 return ContextCompat.checkSelfPermission(context.getApplicationContext(), permission) == PackageManager.PERMISSION_DENIED; } /** * call before {@link #isGranted(Activity, String...)} and {@link #requestPermissions(Activity, OnPermissionGrantedListener, OnPermissionDeniedListener, String...)} */ private static void checkManifestPermissions(Activity activity, String... permissions) { if (permissions == null || permissions.length == 0) { throw new IllegalArgumentException("至少出入一个权限"); } if (mRegisteredInManifestPermissions == null) { mRegisteredInManifestPermissions = getRegisteredInManifestPermissions(activity); } if (mOnGrantedListeners == null) mOnGrantedListeners = new Hashtable<>(); if (mOnDeniedListeners == null) mOnDeniedListeners = new Hashtable<>(); for (String permission : permissions) { if (!mRegisteredInManifestPermissions.contains(permission)) { throw new IllegalArgumentException("这个权限:\"" + permission + "\" 没有在清单文件中注册!!!"); } } } /** * @return 在清单文件中注册过的权限 */ private static List getRegisteredInManifestPermissions(Activity activity) { List list = new ArrayList<>(); try { PackageInfo packageInfo = activity.getPackageManager().getPackageInfo(activity.getPackageName(), PackageManager.GET_PERMISSIONS); String[] permissions = packageInfo.requestedPermissions; if (permissions != null) { list.addAll(Arrays.asList(permissions)); } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return list; } /** * 跳转到权限设置页面(不同手机可能跳转方式不同,使用时需要查下资料确定一下) */ public static void startAppSettings(Context context) { if (Build.MANUFACTURER.equals("Xiaomi")) { Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR"); ComponentName componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity"); intent.setComponent(componentName); intent.putExtra("extra_pkgname", BuildConfig.APPLICATION_ID); context.startActivity(intent);// ActivityCompat.startActivityForResult(activity, intent, , ); } else if (Build.MANUFACTURER.equals("Meizu")) { Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC"); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.putExtra("packageName", BuildConfig.APPLICATION_ID); context.startActivity(intent); } else { Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setData(Uri.parse("package:" + context.getPackageName())); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); context.startActivity(intent); } } @FunctionalInterface public interface OnPermissionDeniedListener { void onDenied(); } @FunctionalInterface public interface OnPermissionGrantedListener { void onGranted(); }}

第二版

package com.audient.permissionhelper;import android.Manifest;import android.annotation.TargetApi;import android.app.Activity;import android.app.Fragment;import android.app.FragmentManager;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android-.Uri;import android.os.Build;import android.os.Bundle;import android.provider.Settings;import android.support.annotation.NonNull;import android.support.v4.content.ContextCompat;import android.util.Log;import BuildConfig;import java.util.ArrayList;import java.util.Arrays;import java.util.List;/** * 推荐使用: * //6.0权限申请 混淆:-dontwarn com.hjq.permissions.** * implementation 'com.hjq:xxpermissions:6.2' *

* 本工具类有很多问题,仅供参考 * 已知问题: * 1.已知不能在子线程运行 * 2.要注意内存溢出问题 * * @author mwq */public class PermissionUtils extends Fragment { private static final String TAG = "PermissionFragment"; private static List mRegisteredInManifestPermissions; private static OnPermission mOnPermission; private static int mRequestCode = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } /** * @param permissions e.g. {@link Manifest.permission#CAMERA} * @return true:全部授予 false:有没授予的权限存在 */ public static boolean isGranted(Activity activity, String... permissions) { checkManifestPermissions(activity, permissions); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { for (String permission : permissions) { if (activity.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED) { return false; } } } return true; } /** * @param onPermission 运行权限 */ @TargetApi(Build.VERSION_CODES.M) public static void requestPermissions(Activity activity, OnPermission onPermission, String... permissions) { checkManifestPermissions(activity, permissions); mOnPermission = onPermission; if (isGranted(activity, permissions)) { if (onPermission != null) onPermission.onRequestResults(true, new ArrayList<>()); return; } Fragment fragment = activity.getFragmentManager().findFragmentByTag(TAG); if (fragment == null) { fragment = new PermissionUtils(); final FragmentManager fragmentManager = activity.getFragmentManager(); fragmentManager.beginTransaction().add(fragment, TAG).commitAllowingStateLoss(); fragmentManager.executePendingTransactions(); } fragment.requestPermissions(permissions, mRequestCode); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == mRequestCode) { Log.i("调试信息", "requestCode = [" + requestCode + "], permissions = [" + Arrays.toString(permissions) + "], grantResults = [" + Arrays.toString(grantResults) + "]"); super.onRequestPermissionsResult(requestCode, permissions, grantResults); ArrayList noGranteds = new ArrayList<>(); // 这里规定全部权限都通过才算通过 boolean granted = true; // 在Activity A申请权限,然后马上跳转到Activity B,则grantResults.length=0 if (grantResults.length == 0) granted = false; for (int i = 0; i < grantResults.length; i++) { if (grantResults[i] == PackageManager.PERMISSION_DENIED) { granted = false; noGranteds.add(permissions[i]); } } if (mOnPermission != null) { mOnPermission.onRequestResults(granted, noGranteds); } } } /** * @param permission 单个权限 * @return 是否缺少某项权限 */ public boolean hasPermission(Context context, String permission) { return ContextCompat.checkSelfPermission(context.getApplicationContext(), permission) == PackageManager.PERMISSION_DENIED; } /** * call before {@link #isGranted(Activity, String...)} and {@link #requestPermissions(Activity, OnPermission, String...)} */ private static void checkManifestPermissions(Activity activity, String... permissions) { if (permissions == null || permissions.length == 0) { throw new IllegalArgumentException("至少输入一个权限"); } if (mRegisteredInManifestPermissions == null) { mRegisteredInManifestPermissions = getRegisteredInManifestPermissions(activity); } for (String permission : permissions) { if (!mRegisteredInManifestPermissions.contains(permission)) { throw new IllegalArgumentException("这个权限:\"" + permission + "\" 没有在清单文件中注册!!!"); } } } /** * @return 在清单文件中注册过的权限 */ private static List getRegisteredInManifestPermissions(Activity activity) { List list = new ArrayList<>(); try { PackageInfo packageInfo = activity.getPackageManager().getPackageInfo(activity.getPackageName(), PackageManager.GET_PERMISSIONS); String[] permissions = packageInfo.requestedPermissions; if (permissions != null) { list.addAll(Arrays.asList(permissions)); } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return list; } /** * 跳转到权限设置页面(不同手机可能跳转方式不同,使用时需要查下资料确定一下) */ public static void startAppSettings(Context context) { if (Build.MANUFACTURER.equals("Xiaomi")) { Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR"); ComponentName componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity"); intent.setComponent(componentName); intent.putExtra("extra_pkgname", BuildConfig.APPLICATION_ID); context.startActivity(intent);// ActivityCompat.startActivityForResult(activity, intent, , ); } else if (Build.MANUFACTURER.equals("Meizu")) { Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC"); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.putExtra("packageName", BuildConfig.APPLICATION_ID); context.startActivity(intent); } else { Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setData(Uri.parse("package:" + context.getPackageName())); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); context.startActivity(intent); } } @FunctionalInterface public interface OnPermission { /** * @param isAll 是否全部通过 * @param noGranteds 未通过的权限数据 */ void onRequestResults(boolean isAll, List noGranteds); }}

参考链接:​​http://demodashi.com/demo/13506.html​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:动态添加按钮 TagCloudView
下一篇:字符串和asccii转换
相关文章

 发表评论

暂时没有评论,来抢沙发吧~