申請(qǐng)權(quán)限邏輯
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("請(qǐng)?jiān)O(shè)置權(quán)限申請(qǐng)回調(diào)");
}
}
public List<String> getPermissions() {
return permissions;
}
/**
* 檢查所有權(quán)限是否允許
* @param isRequestPermission 是否請(qǐng)求申請(qǐng)未允許的權(quán)限
* @return true 允許所有權(quán)限耻卡,false 沒有允許全部權(quán)限
*/
public boolean check(boolean isRequestPermission) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
return true;
}
//裝沒有允許的權(quán)限
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);
}
}
}
請(qǐng)求回調(diào)
import java.util.List;
public interface OnPermissionListener {
/**
* 同意的權(quán)限
*
* @param permission
*/
void onGranted(List<String> permission);
/**
* 拒接的權(quán)限
*
* @param permission
*/
void onDenied(List<String> permission);
}