This sharing stems from recent actual development work.

The project requirements are

  • Embed WebView in the native Android application, and place Web pages for supporting audio and video live streaming business;

  • You also need to preview the content in common document formats such as Word, Excel, PowerPoint, and PDF.

After some technical selection, the project was finally selected to integrate Tencent TBS browsing service and support the two functions mentioned above.

Ability to integrate

  1. First, go to the page shown in the following figure, download the SDK from the download page and save it.

  1. After the download is successful, place the JAR package in the libs directory of the Module that you want to integrate the capability. Then, in Android Studio, display the Project tree as a Project view, locate the JAR package, right-click it, and select “Add as Library.” Wait a moment to complete the library introduction.

  2. Next, open the AndroidManifest.xml configuration file of the Android native project and declare the following permissions (note that permissions that require dynamic permissions should be applied separately) :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.front" />
Copy the code
  1. Initialize the SDK and execute the following code in Java code and AndroidManifest.xml to initialize Tencent TBS:
HashMap map = new HashMap();
map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
QbSdk.initTbsSettings(map);
Copy the code
<service
    android:name="com.tencent.smtt.export.external.DexClassLoaderProviderService"
    android:label="dexopt"
    android:process=":dexopt">
</service>
Copy the code

At this point, we can use the WebView in Tencent TBS as well as the system’s native WebView API. When guiding packages, be sure to import the following packages, not the system native:


import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
Copy the code

Load the page and execute the JS method

Basic implementation

This step is relatively simple and is basically the same as using the system’s native WebView and associated apis. I put the page to load in the assets directory of the project, so my code snippet is as follows:

WebSettings webSettings = videoPreviewWv.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(false);
webSettings.setAllowFileAccess(true);
webSettings.setDomStorageEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setAppCacheEnabled(true);
videoPreviewWv.loadUrl(Environment.VIDEO_RECORD_URL);
Copy the code

Note: videoPreviewWv is a WebView object.

In addition to the basic loading of the page above, I also want to call the JS method inside the page after it has loaded so that the live stream can start immediately after the page has loaded.

Therefore, I added the following method:

videoPreviewWv.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView webView, String s) {
        super.onPageFinished(webView, s);
        String jsStr = "javascript:open('" + SharedPrefUtil.getToken(activity) + "', '" + Environment.VIDEO_IP + "'," + Integer.parseInt(sn) + ", '" + Environment.VIDEO_STUN_IP + "'" + ")";
        videoPreviewWv.evaluateJavascript(jsStr, null); }});Copy the code

The onPageFinished() method is called back when the page has loaded.

EvaluateJavascript () will call the js methods, and you can use the jsStr string value as a format reference to fit your own JS file.

As shown in the code above, when the page is loaded, I call the open() method in JS, passing in the token, video push IP and other parameters.

For js methods that don’t require any arguments, I’ll use the method that stops live streaming as an example:

videoPreviewWv.evaluateJavascript("javascript:close()".null);
Copy the code

How’s that? Easy enough, right? However, at this point, the page is still not displayed properly.

After repeated investigation, I found that the problem lies in the following three points:

Ignore SSL connection error

In the actual debugging, I found that after the above work, the page did not display, because the SSL security connection error.

When this happens, we want to ignore and continue loading the page. It’s easy to implement:

videoPreviewWv.setWebViewClient(new com.tencent.smtt.sdk.WebViewClient() {
    @Override
    public void onReceivedSslError(WebView webView, com.tencent.smtt.export.external.interfaces.SslErrorHandler sslErrorHandler, com.tencent.smtt.export.external.interfaces.SslError sslError) { sslErrorHandler.proceed(); }});Copy the code

By default, camera and microphone rights are granted

At this point, the page is ready to display. However, there are still shortcomings.

Every time you execute js’s open() method, there will still be a permission request dialog because the web page will request permissions for the camera and microphone, even though the user has already been requested by native code. In this way, it is equivalent to requesting permissions repeatedly. And every time we turn on live, we ask for it.

So, is there a way to make the embedded WebView allow these permissions by default?

Yes, of course. Here’s the code for automatically granting permissions:

videoPreviewWv.setWebChromeClientExtension(new IX5WebChromeClientExtension() {
    @Override
    public boolean onPermissionRequest(String s, long l, MediaAccessPermissionsCallback mediaAccessPermissionsCallback) {
        long allowed = 0;
        allowed = allowed | MediaAccessPermissionsCallback.ALLOW_AUDIO_CAPTURE;
        mediaAccessPermissionsCallback.invoke(s, allowed, true);
        return true; }}Copy the code

The elimination of white margins by default

After a series of operations, we have the functionality we want. But there is one final flaw — the web page has white margins.

The problem is not really a native code problem, but a modification of the embedded Web page (HTML). Add the following code:

<style>
	 body{
        margin:0px
    }
</style>
Copy the code

All right, so that’s the embedding of the WebView.

Common types Document preview

Next, let’s talk about using Tencent TBS to preview common types of documents.

Download the document to the local directory

Because the document preview does not support online files, we need to download the files to the local first. Web downloads are not the focus of this article and will not be covered here.

However, if we need to successfully use the file preview capability of Tencent TBS, we need to make the following declaration in Androidmanifest.xml:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provide_file_paths" />
</provider>
Copy the code

Provide_file_paths contains the following information:


      
<resources>
    <paths>
        <external-path
            name="sdcard"
            path="" />
        <files-path
            name="my_files"
            path="cache" />
    </paths>
</resources>
Copy the code

For rules for defining PROvide_FILe_Paths, also search for FileProvider Path configuration Policy.

The file preview view is launched

After the file is successfully downloaded, execute the following code to open the file preview screen.

HashMap<String, String> params = new HashMap<String, String>();
params.put("local"."true");
params.put("style"."1");
JSONObject Object = new JSONObject();
try {
    Object.put("pkgName", activity.getApplicationContext().getPackageName());
} catch (JSONException e) {
    e.printStackTrace();
}
params.put("menuData", Object.toString());
QbSdk.openFileReader(activity, file.getAbsolutePath(), params, null);
Copy the code

Ok, here we are, embedding the web page and previewing the common documents.

The end of this share, I hope the above content to help you.