A practice of Tencent TBS browsing service integration

This sharing stems from the recent actual development work.

Project requirements are

  • Embed WebView in the native Android application and place the Web page used to support the audio and video live broadcasting service;

  • In addition, the content preview of common document formats such as Word, Excel, PowerPoint and PDF shall be provided.

After some technical selection, we finally selected the integration of Tencent TBS browsing service into the project to support the two functions mentioned above.

Capability integration

  1. First, enter the web page shown in the figure below, download the SDK on the download page and save it.

  1. After the download is successful, put the jar package into the libs directory of the Module to integrate the capability. Then, in Android Studio, display the Project tree structure in Project view, find the jar package, right-click and select "Add as Library". Wait a moment to complete the library import.

  2. Next, open the androidmanifest.exe of the Android native project XML configuration file, declaring the following permissions (special attention should be paid to the permissions that need to apply for dynamic permissions, which 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" />
  1. Initialize the SDK in Java code and androidmanifest Execute the following code in 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);
<service
    android:name="com.tencent.smtt.export.external.DexClassLoaderProviderService"
    android:label="dexopt"
    android:process=":dexopt">
</service>

At this point, we can use WebView in Tencent TBS just like using the native WebView API of the system. When importing packages, be careful to import the following packages instead of the native system:

import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

Load the web page and execute the JS method

Basic implementation

This step is relatively simple and basically consistent with the use of the system's native WebView and related API s. I put the web page to be loaded into the assets directory of the project, so my code fragment 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);

Note: videoPreviewWv is a WebView object.

In addition to the above basic page loading, I also hope to call the js method inside after the page is loaded, so that the live broadcast can be started immediately after the page is loaded.

Therefore, I added the following methods:

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);
    }
});

After the web page is loaded, the onPageFinished() method is called back.

evaluateJavascript() is responsible for calling the js method. You can use the value of jsStr string as the format reference to adapt your own js file.

As shown in the above code, when the web page is loaded, I call the open() method in js and pass in the parameters such as token and video streaming IP.

For the js method without any parameters, I take the method of stopping live broadcast as an example:

videoPreviewWv.evaluateJavascript("javascript:close()", null);

What about? Is it simple? However, at this point, the web page is still displayed abnormally.

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

Ignore SSL secure connection errors

In the actual debugging, I found that only the above work was completed, and the web page could not be displayed because of the SSL secure connection error.

When we encounter this problem, we want to ignore and continue to load the web page. It is also 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();
    }
});

Camera and microphone permissions are given by default

At this point, the web page can be displayed. However, there are still deficiencies.

Every time js's open() method is executed, because the web page will request the permission of the camera and microphone, there will still be a dialog box for permission request. In fact, the user has been asked for permission by the native code before. In this way, it is equivalent to repeatedly requesting permission. And every time you start the live broadcast, you will request it once.

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

Of course, the following are the relevant codes 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;
    }
}

Elimination of default white edges on Web pages

After the above series of operations, the function we want has been realized. However, there is one last drawback - the web page has a white edge.

This problem is not a native code problem. You need to modify the embedded Web page (HTML). Add the following code:

<style>
	 body{
        margin:0px
    }
</style>

Well, now, the embedding of WebView is completed.

Common type document preview

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

Download documents locally

Because the document preview does not support online files temporarily, we need to download the files locally first. Network download is not the focus of this article, so I won't elaborate here.

However, if we need to successfully use the file preview capability of Tencent TBS, we need to use Android manifest XML makes the following Declaration:

<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>

Among them, provide_ file_ The contents of paths are as follows:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <paths>
        <external-path
            name="sdcard"
            path="" />
        <files-path
            name="my_files"
            path="cache" />
    </paths>
</resources>

About provide_ file_ For the definition rules of paths, please also search: "FileProvider path configuration policy".

Launch file preview view

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

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);

OK, so far, we have completed the embedding of the web page and the preview of common documents.

This sharing is over. I hope the above content will help you.

Tags: Android Design Pattern

Posted by wudiemperor on Thu, 05 May 2022 01:11:53 +0300