PermissionsUtil类
import android.app.Activity;import android.content.pm.PackageManager;import android.support.annotation.NonNull;import android.support.v4.app.ActivityCompat;import android.support.v4.content.ContextCompat;import android.util.Log;import android.widget.Toast;import java.util.ArrayList;import java.util.List;public class PermissionsUtil { private Activity context; private int requestId; private ListpermissionList; public PermissionsUtil(Activity context){ this.context = context; permissionList = new ArrayList<>(); } /** * 查询当前权限是否禁止 * */ public void shouldShowPermissionRationale(int requestId,String ... permission){ this.requestId = requestId; for (int i = 0; i < permission.length; i++) { boolean checkPermisssion = ContextCompat.checkSelfPermission(context, permission[i])!= PackageManager.PERMISSION_GRANTED; //表示权限被拒绝,说明此权限作用 if(checkPermisssion){ permissionList.add(permission [i]); } } if (null != permissionList && !permissionList.isEmpty()){ //permissionList集合里面有未授权的权限 String[] permissions = permissionList.toArray(new String[permissionList.size()]); requestPermissions(context,permissions); } //权限已经授权 else { Toast.makeText(context,"权限已经授权",Toast.LENGTH_LONG).show(); } } //查询当前申请的所有权限是否都被允许 public void shouldShowPermissionRationale(String ... permission){ permissionList.clear(); for (int i = 0; i
在Activity使用
import android.Manifest;import android.support.annotation.NonNull;import android.support.v4.app.ActivityCompat;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import com.example.binder.permissionstest.util.PermissionsUtil;public class MainActivity extends AppCompatActivity implements View.OnClickListener,ActivityCompat.OnRequestPermissionsResultCallback { private PermissionsUtil permissionsUtil; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); permissionsUtil = new PermissionsUtil(this); findViewById(R.id.permission).setOnClickListener(this); } @Override public void onClick(View v) { String[] permissions = new String[]{Manifest.permission.CAMERA,Manifest.permission.CALL_PHONE, Manifest.permission.WRITE_EXTERNAL_STORAGE}; switch (v.getId()){ case R.id.permission: permissionsUtil.shouldShowPermissionRationale(111,permissions); break; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { permissionsUtil.onRequestPermissionsResult(requestCode,permissions,grantResults); }}
清单文件添加权限
结束