Android照相机和相册动态权限

1.相机

@OnClick(R.id.to_camear_btn)
    public void onClick() {

//        checkSelfPermission 检测有没有 权限
//        PackageManager.PERMISSION_GRANTED 有权限
//        PackageManager.PERMISSION_DENIED  拒绝权限
        if(ActivityCompat.checkSelfPermission(this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
            //权限发生了改变 true  //  false 小米
            if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CAMERA)){



                new AlertDialog.Builder(this).setTitle("title")
                        .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 请求授权
                                ActivityCompat.requestPermissions(PermissionActivity.this,new String[]{Manifest.permission.CAMERA},1);

                            }
                        }).setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).create().show();



            }else {
                ActivityCompat.requestPermissions(PermissionActivity.this,new String[]{Manifest.permission.CAMERA},1);

            }

        }else{

            camear();

        }




    }


    /**
     *
     * @param requestCode
     * @param permissions 请求的权限
     * @param grantResults 请求权限返回的结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if(requestCode == 1){
            // camear 权限回调

            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

                // 表示用户授权
                Toast.makeText(this, " user Permission" , Toast.LENGTH_SHORT).show();

                camear();


            } else {

                //用户拒绝权限
                Toast.makeText(this, " no Permission" , Toast.LENGTH_SHORT).show();

            }



        }

    }

    public void camear(){
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {            
                @Override
                public void onClick(View view) {
                    onTakePhoto();
                }
            });
        }
        public void onTakePhoto()   {
            if (Build.VERSION.SDK_INT>=23)       {
                int request= ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
                if (request!= PackageManager.PERMISSION_GRANTED)//缺少权限,进行权限申请
                {
                    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},123);
                    return;//
                }
                else
                {
                    //权限同意,不需要处理,去掉用拍照的方法               
                    // Toast.makeText(this,"权限同意",Toast.LENGTH_SHORT).show();
                }
            }
            else{
                //低于23 不需要特殊处理,去掉用拍照的方法
            }
        }
        //参数 requestCode是我们在申请权限的时候使用的唯一的申请码 
        //String[] permission则是权限列表,一般用不到
        //int[] grantResults 是用户的操作响应,包含这权限是够请求成功
        //由于在权限申请的时候,我们就申请了一个权限,所以此处的数组的长度都是1
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode==123)
            {            //当然权限多了,建议使用Switch,不必纠结于此
                if (grantResults[0]==PackageManager.PERMISSION_GRANTED)            {
                    Toast.makeText(this, "权限申请成功",Toast.LENGTH_SHORT).show();
                }else if (grantResults[0]== PackageManager.PERMISSION_DENIED)            {
                    Toast.makeText(this, "权限申请失败,用户拒绝权限", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

2.相册

public class MainActivity extends AppCompatActivity {

    //调用系统相册-选择图片
    private static final int IMAGE = 1;
    //所需权限
//    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View v) {
        //调用相册
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取图片路径
        if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String imagePath = c.getString(columnIndex);
            showImage(imagePath);
            c.close();
        }
    }

    //加载图片
    private void showImage(String imaePath){
        Bitmap bm = BitmapFactory.decodeFile(imaePath);
        ((ImageView)findViewById(R.id.image)).setImageBitmap(bm);
    }

}


你可能感兴趣的:(Android照相机和相册动态权限)