Android 6.0以上の動的アクセス権呼び出しカメラ(暗黙的ジャンプ)

2641 ワード

1.インベントリファイル

2.カメラのクリックイベント
//         
img.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(Build.VERSION.SDK_INT>=23){
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CAMERA},0);
            int permission = ContextCompat.checkSelfPermission(MainActivity.this.getApplicationContext(), Manifest.permission.CAMERA);
            if(permission==PackageManager.PERMISSION_GRANTED){
                //              
                startCamera();
            }else {
                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("  ");
                builder.setMessage("        ");
                builder.setPositiveButton(" ", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //       
                        ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CAMERA},0);
                    }
                });
                builder.setNegativeButton(" ", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "          ", Toast.LENGTH_SHORT).show();
                    }
                });
                builder.show();
            }
        }else {
            //  6.0      
            startCamera();
        }
    }
});

3.カメラを開く方法を呼び出す
private void startCamera() {
    //    
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
     intent.addCategory("android.intent.category.DEFAULT");
     startActivityForResult(intent,1);
}

4.イベントコールバック(権限申請完了コールバック)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(permissions[0].equals(Manifest.permission.CAMERA)){
        if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
            Toast.makeText(MainActivity.this,"   ",Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this, "    ", Toast.LENGTH_SHORT).show();
        }
    }
}