WebSDK Integration via WebView Best Practices Guide
In native application development, integrating WebSDK through WebView is a common technical solution for extending web-level functionalities. However, users may encounter issues such as black screens, camera launch failures, or authorization failures, which can significantly affect user experience.
This document provides a detailed integration process through an example, offering solutions to these issues. The example demonstrates how to request camera permissions at the right time and automatically reload the WebSDK in case of exceptions, reducing the loss in conversion rates due to black screens. It effectively addresses camera launch and authorization failure issues.
The following is the detailed integration sample code for your reference.
package com.example.testwebview;
public class WebActivity extends Activity {
private WebView webView;
private static final int CAMERA_PERMISSION_REQUEST_CODE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
// Set WebChromeClient to handle permission requests
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onPermissionRequest(final PermissionRequest request) {
// // Check if camera permission is granted
if (ContextCompat.checkSelfPermission(WebActivity.this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
//WebSDK callback for camera request: If camera permission is granted, proceed with subsequent Web page operations
request.grant(request.getResources());
} else {
// If camera permission is not granted, request the permission
ActivityCompat.requestPermissions(WebActivity.this,
new String[]{Manifest.permission.CAMERA},
CAMERA_PERMISSION_REQUEST_CODE);
}
}
});
loadWebsdk(); // Load WebSDK
}
private void loadWebsdk() {
String url = getIntent().getStringExtra("url");
if (url != null && !url.isEmpty()) {
webView.loadUrl(url);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Reload WebSDK after successfully obtaining authorization
loadWebsdk();
} else {
Toast.makeText(this, "Camera Permission Denied", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}