Skip to content Skip to sidebar Skip to footer

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 pe

Solution 1:

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 = newString[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

Solution 2:

I think that the best way here is to use WebView API to grant and deny permissions.

  1. Create class that extends WebChromeClient;
  2. Override onPermissionRequest()
  3. Request asked permission inside your app, or handle request in another way.
  4. Also you probably will need to override onPermissionRequestCanceled()
  5. Set an instance of your client to WebViewwebView.setWebChromeClient(chromeClient);

Solution 3:

If you are developing a Web App using the webView then you should learn about JavascriptInterface provided by Android. Go through following links

Javascript interface

Android webView

All you need to do is setup javascript call back.call that method from your web page, handle the javascript call back in the Activity/fragment and from there you can open the camera.

You should also check the answer of @Nilesh Rathod for the run time permissions.

here are the code snippets that will help you

privateclassWebAppInterface {

    publicWebAppInterface(Context context) {
    }

    @JavascriptInterfacepublicvoidopenCamera(String title) {
        //check permissions and open camera intent;
    }
}


mWebView.addJavascriptInterface(newWebAppInterface(this), "PLATFORM_ID");

Post a Comment for "Need Permission To Access Camera In Android Web-view?"