android webview打开前置摄像头

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.webkit.JsResult;
import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class WebTestActivity  extends Activity {
    private WebView webView;
    private final int REQUEST_CAMERA_PERMISSION = 100;
    private PermissionRequest pendingPermissionRequest;
    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_test);
        webView = findViewById(R.id.webView);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        // 允许自动播放
        settings.setMediaPlaybackRequiresUserGesture(false);
        String url = "file:///android_asset/camera_test.html";
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onPermissionRequest(final PermissionRequest request) {
                // 检查权限
                if (ContextCompat.checkSelfPermission(WebTestActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    request.grant(request.getResources());
                } else {
                    // 保存请求以便在用户授予权限后使用
                    pendingPermissionRequest = request;
                    // 请求权限
                    ActivityCompat.requestPermissions(WebTestActivity.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                // 自动确认 JavaScript Alert
                result.confirm();
                return true; // 表示我们已经处理了这个 alert
            }
        });
        webView.loadUrl(url);
    }

    @Override
    protected void onDestroy() {
        webView.destroy();
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户允许了摄像头权限,授予权限
                if (pendingPermissionRequest != null) {
                    pendingPermissionRequest.grant(pendingPermissionRequest.getResources());
                    pendingPermissionRequest = null;
                }
            } else {
                // 用户拒绝了摄像头权限
                Toast.makeText(this, "摄像头权限被拒绝", Toast.LENGTH_SHORT).show();
                // 清理请求
                pendingPermissionRequest = null;
            }
        }
    }
}

  

camera_test.html代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>摄像头测试</title>
</head>
<body>
<button id="cameraButton">打开前置摄像头</button>
<video id="video" width="320" height="240" autoplay></video>

<script>
        document.getElementById('cameraButton').addEventListener('click', async () => {
            try {
                const constraints = {
                    video: {
                        facingMode: 'user'
                    }
                };
                const stream = await navigator.mediaDevices.getUserMedia(constraints);
                const videoElement = document.getElementById('video');
                videoElement.srcObject = stream;
            } catch (error) {
                console.error('Error accessing camera: ', error);
                alert('Error accessing camera: ' + error.message);
                }
        });
    </script>
</body>
</html>

  效果

 

posted on 2024-10-17 15:45  白衣雨果  阅读(53)  评论(0编辑  收藏  举报