申请权限逻辑
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 Activity activity;
private List<String> permissions;
private int requestCode;
private OnPermissionListener onPermissionListener;
public Permission(Activity activity, List<String> permissions, int requestCode, OnPermissionListener onPermissionListener) {
this.activity = activity;
this.permissions = permissions;
this.requestCode = requestCode;
this.onPermissionListener = onPermissionListener;
}
public Permission(Activity activity, List<String> permissions, int requestCode) {
this.activity = activity;
this.permissions = permissions;
this.requestCode = requestCode;
if (activity instanceof OnPermissionListener){
onPermissionListener = (OnPermissionListener) activity;
}else {
throw new RuntimeException("请设置权限申请回调");
}
}
public List<String> getPermissions() {
return permissions;
}
/**
* 检查所有权限是否允许
* @param isRequestPermission 是否请求申请未允许的权限
* @return true 允许所有权限,false 没有允许全部权限
*/
public boolean check(boolean isRequestPermission) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
return true;
}
//装没有允许的权限
List<String> notGranted = new ArrayList<>();
for (int i = 0; i < permissions.size(); i++) {
String permission = permissions.get(i);
if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
notGranted.add(permission);
}
}
if (isRequestPermission && !notGranted.isEmpty()){
String[] arr = new String[notGranted.size()];
for (int i = 0; i < notGranted.size(); i++) {
arr[i] = notGranted.get(i);
}
ActivityCompat.requestPermissions(activity, arr, requestCode);
}
return notGranted.isEmpty();
}
public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults){
if(this.requestCode == requestCode){
List<String> granted = new ArrayList<>();
List<String> denied = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
String p = permissions[i];
int g = grantResults[i];
if (g == PackageManager.PERMISSION_GRANTED){
granted.add(p);
}else {
denied.add(p);
}
}
onPermissionListener.onGranted(granted);
onPermissionListener.onDenied(denied);
}
}
}
请求回调
import java.util.List;
public interface OnPermissionListener {
/**
* 同意的权限
*
* @param permission
*/
void onGranted(List<String> permission);
/**
* 拒接的权限
*
* @param permission
*/
void onDenied(List<String> permission);
}