Android : Webcam Error in WebView (Camera Permission not working)
Asked Answered
L

2

10

I have created WebView Activity and loading https://web.doar.zone/coronavirus

This URL required Camera permission which I had taken Runtime Permission in Android.

Here is the full code of MainActivity.java:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    Context context;

    ActivityMainBinding binding;

    private String url = "https://web.doar.zone/coronavirus";

    @Override
    protected void onResume() {
        super.onResume();
        checkCameraPermission();
    }

    private void checkCameraPermission() {
        int writeExternalStorage = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        if (writeExternalStorage != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1001);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1001) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Do your stuff
                openWebView();
            } else {
                checkCameraPermission();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        context = getApplicationContext();

        openWebView();
    }

    @SuppressLint("SetJavaScriptEnabled")
    void openWebView() {

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        final NetworkInfo networkInfo;
        if (connectivityManager != null) {
            networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
                binding.internetTextView.setVisibility(View.INVISIBLE);
                binding.webView.setVisibility(View.VISIBLE);
                //binding.webView.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3");
                binding.webView.getSettings().setJavaScriptEnabled(true);
                binding.webView.getSettings().setUseWideViewPort(true);
                binding.webView.getSettings().setDomStorageEnabled(true);
                binding.webView.setInitialScale(1);
                binding.webView.setWebChromeClient(new MyWebChromeClient());
                binding.webView.setWebViewClient(new WebViewClient() {

                    @Override
                    public boolean shouldOverrideUrlLoading(WebView webview, String url) {
                        Uri uri = Uri.parse(url);
                        if (uri.getScheme().contains("whatsapp") || uri.getScheme().contains("tel")) {
                            try {
                                Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                                if (intent.resolveActivity(getPackageManager()) != null)
                                    startActivity(intent);
                                return true;
                            } catch (URISyntaxException use) {
                                Log.e("TAG", use.getMessage());
                            }
                        } else {
                            webview.loadUrl(url);
                        }

                        return true;
                    }

                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                    }
                });
                binding.webView.loadUrl(url);
            } else {

                binding.internetTextView.setVisibility(View.VISIBLE);
                binding.buttonTryAgain.setVisibility(View.VISIBLE);
                binding.webView.setVisibility(View.INVISIBLE);

                Toast.makeText(context, "Connect to Internet and Refresh Again", Toast.LENGTH_LONG).show();
            }
        } else {
            binding.internetTextView.setVisibility(View.VISIBLE);
            binding.buttonTryAgain.setVisibility(View.VISIBLE);
            binding.webView.setVisibility(View.INVISIBLE);

            Toast.makeText(context, "Connect to Internet and Refresh Again", Toast.LENGTH_LONG).show();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (binding.webView.canGoBack()) {
                    binding.webView.goBack();
                } else {
                    finish();
                }
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    class MyWebChromeClient extends WebChromeClient {

        MyWebChromeClient() {
            // TODO Auto-generated constructor stub
            binding.pb.setProgress(0);
        }

        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            super.onPermissionRequest(request);
            //request.grant(request.getResources());
        }

        public void onProgressChanged(WebView view, int progress) {
            if (progress < 100  /* && pBar.getVisibility() == View.VISIBLE*/) {
                binding.pb.setVisibility(View.VISIBLE);
            }
            binding.pb.setProgress(progress);
            if (progress == 100) {
                binding.pb.setVisibility(View.GONE);
            }
        }
    }
}

Now I am getting error as below When I comment this line:

request.grant(request.getResources());

enter image description here

And If I uncomment this line then I am getting:

 java.lang.IllegalStateException: Either grant() or deny() has been already called.
    at org.chromium.android_webview.permission.AwPermissionRequest.c(PG:3)
    at org.chromium.android_webview.permission.AwPermissionRequest.b(PG:1)
    at Cn.grant(PG:8)
    at com.example.webviewapp.MainActivity$MyWebChromeClient.onPermissionRequest(MainActivity.java:164)
    at org.chromium.android_webview.AwContents.onPermissionRequest(PG:8)
    at android.os.MessageQueue.nativePollOnce(Native Method)
    at android.os.MessageQueue.next(MessageQueue.java:326)
    at android.os.Looper.loop(Looper.java:181)
    at android.app.ActivityThread.main(ActivityThread.java:7078)
2020-04-29 11:52:21.813 4943-4943/com.example.webviewapp W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)

Any Help?

Lampyrid answered 29/4, 2020 at 6:26 Comment(0)
A
28

You've already handled runtime Camera permission of android os. We need to grant camera permission (RESOURCE_VIDEO_CAPTURE) inside webview also.

First call below method to open camera without user gesture:

binding.webView.getSettings().setMediaPlaybackRequiresUserGesture(false);

Calling request.grant(request.getResources()) method like this will grant all requested permission. To avoid that you should only grant permission which you need which is RESOURCE_VIDEO_CAPTURE:

@Override
public void onPermissionRequest(final PermissionRequest request) {
    final String[] requestedResources = request.getResources();
    for (String r : requestedResources) {
        if (r.equals(PermissionRequest.RESOURCE_VIDEO_CAPTURE)) {
            request.grant(new String[]{PermissionRequest.RESOURCE_VIDEO_CAPTURE});
            break;
        }
    }
}

In your code this line was causing the issue: super.onPermissionRequest(request); this super method call denies the permission.

Apsis answered 5/5, 2020 at 8:51 Comment(7)
Thank you for your answer. The camera is opened successfully but it's displaying in half of width and height on TOP-LEFT CornerLampyrid
@PratikButani I'm not sure how but, It's happening because of this line binding.webView.setInitialScale(1);Apsis
Thanks, I removed binding.webView.setInitialScale(1); Its working now.Lampyrid
@AnkitMakwana after keep this i am facing one issue. when i open external link(help of shouldOverrideUrlLoading) in browser.then came back to webview web cam is disabling.but working when i click home button and come again in app. what was the cause, have you face this issue?Leshalesher
@MohdQasim No. please provide the URL where you are facing this issue so that we can check out that scenario.Apsis
@AnkitMakwana issue is when i go to external link via webview cam is disabling, because of focus change so i am enabling cam when i got focus.issue fixedLeshalesher
Thanks alot . spent 2 days and then your solution worked like a charm !Maiga
A
1

First of call check your camera permission and then load your webview. How can you do that:

1.remove openWebView() in your onCreate method

2.replace checkCameraPermission() with new method

 private void checkCameraPermissionAndStartWebView() {
      int writeExternalStorage = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
      if (writeExternalStorage != PackageManager.PERMISSION_GRANTED) {
         ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1001);
      } else {
         openWebView();
      }
 }

3.in onResume and in on onRequestPermissionsResult call new checkCameraPermissionAndStartWebView method instead

Austine answered 5/5, 2020 at 8:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.