I want to use getUserMedia in Android Lolipop 5.0 WebView
I want to start a webcam using getUserMedia in Android WebView. The following wrote the code, but errorCallback is called. why not?
By the way, the following website was implemented by link.
myWebView = (WebView) findViewById(R.id.webview);
// Settings
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
// Set a web view client and a chrome client
myWebView.setWebViewClient(new WebViewClient());
myWebView.setWebChromeClient(new WebChromeClient() {
// Need to accept permissions to use the camera and audio
@Override
public void onPermissionRequest(final PermissionRequest request) {
Log.d(TAG, "onPermissionRequest");
MainActivity.this.runOnUiThread(new Runnable() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void run() {
if(request.getOrigin().toString().equals(LOCAL_FILE)) {
request.grant(request.getResources());
}
else {
request.deny();
}
}
});
}
});
// Load the local HTML file into the webview
myWebView.loadUrl(LOCAL_FILE);
[permissions]
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
[JavaScript]
var constraints = {video: true, audio: true};
var localStream = null;
function init() {
console.log(‘Getting user media with constraints’, constraints);
navigator.webkitGetUserMedia(constraints, handleUserMediaSuccess, handleUserMediaError);
};
function handleUserMediaSuccess(stream) {
console.log(‘[+] Successfully got local video stream!’);
attachMediaStream = function(element, stream) {
element.src = window.webkitURL.createObjectURL(stream);
};
attachMediaStream(document.getElementById("localVideo"), stream);
};
function handleUserMediaError(error) {
alert(‘[!] getUserMedia error: ‘, error);
};
window.onload = function() {
init();
};
source to share
This was also failing for me while following the same doc. Solution in my case: I needed to manually enable the permissions that the manifest was trying to set. My device did not prompt me to accept them during installation.
On my Android device> Settings> Apps> Application manager> MyAppName> Permissions> Enable camera and microphone
source to share
All you have to do is change the LOCAL_FILE value to your full website url. If you don't know exactly what format is expected, you can debug the output request.getOrigin().toString()
from the method run
.
public void run() {
if(request.getOrigin().toString().equals(LOCAL_FILE)) { // <-- HERE!
request.grant(request.getResources());
}
else {
request.deny();
}
}
source to share