本篇将会封装一个工具,办理安卓权限申请的标题
终极结果:
对应的日志
- 不授权的情况
对应的日志
步调一
在安卓工程目次下 app ---> src ---> main ---> AndroidManifest.xml ,在AndroidManifest.xml下添加须要的权限,如下
步调二
封装一个申请权限的工具类Permission,代码内里有解释,就不赘述了
package com.example.espprovisiondemo;import android.Manifest;import android.app.Activity;import android.content.pm.PackageManager;import android.os.Build;import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat;import java.util.ArrayList;import java.util.List;public class Permission { //须要申请权限的数组 private String[] permissions = { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_SCAN, }; //生存真正须要去申请的权限 private List<String> permissionList = new ArrayList<>(); public static int RequestCode = 100; public void checkPermissions(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { for (int i = 0; i < permissions.length; i++) { if (ContextCompat.checkSelfPermission(activity,permissions) != PackageManager.PERMISSION_GRANTED) { permissionList.add(permissions); } } //有须要去动态申请的权限 if (permissionList.size() > 0) { requestPermission(activity); } } } //去申请的权限 public void requestPermission(Activity activity) { ActivityCompat.requestPermissions(activity,permissionList.toArray(new String[permissionList.size()]),RequestCode); }}步调三
在activity内里使用工具类
package com.example.espprovisiondemo;import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import android.content.pm.PackageManager;import android.os.Bundle;import android.util.Log;public class MainActivity extends AppCompatActivity {// private Permission permission; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Permission permission = new Permission(); permission.checkPermissions(this); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == Permission.RequestCode) { for (int i = 0; i < grantResults.length; i++) { if (grantResults != PackageManager.PERMISSION_GRANTED) { Log.e("p","拒绝的权限名称:" + permissions); Log.e("p","拒绝的权限结果:" + grantResults); Log.e("p","有权限未授权,可以弹框出来,让客户去手机设置界面授权。。。"); }else { Log.e("p","授权的权限名称:" + permissions); Log.e("p","授权的权限结果:" + grantResults); } } } }}末端
本日的分享至此接近尾声喽,小伴们,以为有点用的话,大概已经看到这内里来的请点赞加关注吧~~
后续分享更多Android原生技能及物联网技能相干文章。如果有任何疑问的话,欢迎在下方留言~ |