Search code examples
androidandroid-webview

Need permission to access camera in Android web-view?


I am developing a Web App with the help of Webview in android studio but having some issue I need to have the access open the camera how can I do that I have given the following permission in AndroidManifest.xml

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

what should I need to do more to open the camera?


Solution

  • if your app targeting Android 6.0 and above than add runtime permission

    Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app

    add runtime permission using below code for camera

    String permission = Manifest.permission.CAMERA;
    int grant = ContextCompat.checkSelfPermission(this, permission);
    if (grant != PackageManager.PERMISSION_GRANTED) {
        String[] permission_list = new String[1];
        permission_list[0] = permission;
        ActivityCompat.requestPermissions(this, permission_list, 1);
    }
    

    and than handle result like this

     @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(AccountClass.this,"permission granted", Toast.LENGTH_SHORT).show();  
                 // perform your action here
    
            } else {
                Toast.makeText(AccountClass.this,"permission not granted", Toast.LENGTH_SHORT).show();
            }
        }
    
    }
    

    read about runtime permission