Access your mobile camera in a WebView in Android Studio

4

I'm creating a QR code reader on a website and now I need to use this site in a Mobile version, so I'm creating a WebView that is opening the site.

In any browser, the QR code reader works, either on the desktop or on the mobile phone. But when I use the webview it does not allow permission to use the Android camera.

I have already inserted all the permissions and checks I found on the internet, but nothing works on any version of Android (I'm using 6.0)

<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" />

I saw an option to insert a JavaScript to call the camera in WebView but I could not find how it can be done.

If necessary, please forward the APP code.

    
asked by anonymous 07.03.2018 / 21:06

1 answer

0

Try to assign the permissions on the class as well, and load your HTML with LoadURL:

WebView wView = (WebView) findViewById(R.id.seuWebView);

    wView.getSettings().setJavaScriptEnabled(true);
    wView.getSettings().setAllowFileAccessFromFileURLs(true);
    wView.getSettings().setAllowUniversalAccessFromFileURLs(true);

    wView.setWebViewClient(new WebViewClient());
    wView.setWebChromeClient(new WebChromeClient() {
        // Grant permissions for cam
        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            Log.d("Log1", "onPermissionRequest");
            runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.M)
                @Override
                public void run() {
                    Log.d("Log2", request.getOrigin().toString());
                    if(request.getOrigin().toString().equals("file:///")) {
                        Log.d("Log3", "GRANTED");
                        request.grant(request.getResources());
                    } else {
                        Log.d("Log4", "DENIED");
                        request.deny();
                    }
                }
            });
        }


    });

    wView.loadUrl(SEU_HTML);

And as for JS, use getMedia to set the video to a tag in your HTML, in which case you create a <video> tag in your HTML and do the following:

var constraints = { video: { width: 800, height: 800 } };

    navigator.mediaDevices.getUserMedia(constraints)
            .then(function(mediaStream) {
        var video = document.querySelector('video');
        video.srcObject = mediaStream;
        video.onloadedmetadata = function(e) {
            video.play();
        };
    }).catch(function(err) { console.log(err.name + ": " + err.message); });

Try these two things there, and put that permission on the manifest, just to make sure:

<uses-permission android:name="android.permission.INTERNET" />

Thank you, it's noiz: D.

    
08.03.2018 / 12:57