android framework - Tencent TBSX5WebView - alternative system WebView

Tencent TBSX5WebView - Alternative system comes with WebView

Official website: https://x5.tencent.com/docs/index.html

introduce:

Tencent Browsing Service (TBS, Tencent Browsing Service) integrates Tencent's underlying browsing technology and Tencent platform resources and capabilities to provide an overall browsing service solution. Tencent Browsing Service is aimed at application developers and developers. It provides browsing enhancement, content framework, advertising system, H5 game distribution, big data and other services, which can help application developers greatly improve application experience and effectively improve development, operation and commercialization. efficiency.

advantage

The traditional system kernel (Webview) has problems such as high adaptation cost, insecurity, instability, traffic consumption, slow speed, poor video playback, and poor file capabilities. This is a common problem that mobile application developers face when developing Hybrid Apps. . Tencent Browsing Service is based on Tencent X5 core solution (including core and cloud services), which can effectively solve the common problems faced by traditional mobile web technologies, and can greatly expand the service capabilities of browsing scenarios in applications (Hybrid App).

Steps for usage

  1. Add dependencies or download the jar package from the official website to import
  2. General custom WebView control reuse
  3. Add the newly customized control to the layout file
  4. Call the newly defined WebView

Demo - WebView with progress bar

1. Add dependencies or download the jar package from the official website to import

add dependencies

//文件:app\build.gradle
implementation 'com.tencent.tbs.tbssdk:sdk:43697'

Add permissions

//文件:app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_SETTINGS" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS"
        tools:ignore="ProtectedPermissions" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
        tools:ignore="ProtectedPermissions" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <!-- 硬件加速对X5视频播放非常重要,建议开启 -->
    <uses-permission android:name="android.permission.GET_TASKS" />

Add service: This Service only triggers and executes the dex2oat task when the TBS kernel loads Dex for the first time, and ends automatically after the task is completed

//文件:app/src/main/AndroidManifest.xml
<service
            android:name="com.tencent.smtt.export.external.DexClassLoaderProviderService"
            android:label="dexopt"
            android:process=":dexopt" />

To enjoy the full playback experience of the page video, the activity of the page needs to declare android:configChanges="orientation|screenSize|keyboardHidden"
to avoid the problem of blocking the input cursor after the input method interface pops up: android:windowSoftInputMode="stateHidden|adjustResize"

//文件:app/src/main/AndroidManifest.xml
<activity
            android:name=".TBSX5WebView.BaseTencentWebActivity"
            android:configChanges="orientation|screenSize|keyboardHidden">
            android:windowSoftInputMode="stateHidden|adjustResize"
</activity>

On non-hard-painted mobile phones and web pages that declare that a controller is required, the video window will be transparent when the video is switched to full screen and full screen is switched back to the page. The following settings are required.

文件:\src\main\res\values\styles.xml
<item name="android:windowIsTranslucent">false</item>
2. General custom WebView controls are reused

File: X5WebView.java

import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
//注意WebView要继承com.tencent.smtt.sdk.WebView包下的
//并非android.webkit.WebView包
public class X5WebView extends WebView {
	//设置顶部加载进度条
    private ProgressBar mprogressBar;
	//给自定义类创建构造方法,一般Alt+insert -> constructor -> 全部构造
	// initWebView(context)为WebView作配置
    public X5WebView(Context context) {
        super(context);
        initWebView(context);
    }

    public X5WebView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        initWebView(context);
    }

    public X5WebView(Context context, AttributeSet attributeSet, int i) {
        super(context, attributeSet, i);
        initWebView(context);
    }

    public X5WebView(Context context, AttributeSet attributeSet, int i, boolean b) {
        super(context, attributeSet, i, b);
        initWebView(context);
    }

    public X5WebView(Context context, AttributeSet attributeSet, int i, Map<String, Object> map, boolean b) {
        super(context, attributeSet, i, map, b);
        initWebView(context);
    }

	// initWebView(context)为WebView作配置
    private void initWebView(Context context) {
        //添加进度条
        mprogressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        //LayoutParams实现xml布局动态设置,主要设置View的位置(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 10);
        mprogressBar.setLayoutParams(layoutParams);
        mprogressBar.setProgress(0);
        addView(mprogressBar);

        //设置Settings,可直接照搬
        WebSettings settings = this.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setUseWideViewPort(true);
        settings.setSupportMultipleWindows(true);
        settings.setAppCacheEnabled(true);
        //此项影响网页的加载功能
        settings.setDomStorageEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setAppCacheMaxSize(Long.MAX_VALUE);
        settings.setPluginState(WebSettings.PluginState.ON_DEMAND);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        //初始化WebViewClient
        setWebViewClient(new WebViewClient(){
            //页面内跳转,禁止调用浏览器打开新链接
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                webView.loadUrl(s);
                return super.shouldOverrideUrlLoading(webView, s);
            }
        });

        //初始化WebChromeClient
        setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int i) {
                super.onProgressChanged(webView, i);
                if (i == 100) {
                    mprogressBar.setVisibility(GONE);
                } else {
                    if (mprogressBar.getVisibility() == GONE){
                        mprogressBar.setVisibility(VISIBLE);
                    }
                    mprogressBar.setProgress(i);
                }
            }
        });
    }
}

3. Add the newly customized controls to the layout file

File: activity_base_tencen_web.xml
A ToolBar is added here to return to the main interface button and use other browsers (not required)
Note: learn the use of ToolBar in advance
Effect

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    tools:context=".TBSX5WebView.BaseTencentWebActivity">

	//ToolBar(非必须)
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
    </android.support.v7.widget.Toolbar>

    <com.hong.frampractice.TBSX5WebView.X5WebView
        android:id="@+id/myX5WebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
4. Call the newly defined WebView
public class BaseTencentWebActivity extends AppCompatActivity {

    X5WebView myX5WebView;
    String baseurl = "https://www.baidu.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_tencen_web);
        
        //x5内核初始化接口
        initQbsdk();
        //如果用到布局文件的ToolBar才需要设置(非必须)
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setTitle("实现文档");
        
        myX5WebView = findViewById(R.id.myX5WebView);
        //清理缓存和历史(非必须)
        myX5WebView.clearCache(true);
        myX5WebView.clearHistory();
        //视频为了避免闪屏和透明问题,需要如下设置
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
		//启用硬件加速
        initHardwareAccelerate();
		//加载url
        myX5WebView.loadUrl(baseurl);

    }
	//x5内核初始化接口
    private void initQbsdk() {
        QbSdk.initX5Environment(this, new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                //x5內核初始化完成的回调,为true表示x5内核加载成功,否则表示x5内核加载失败,会自动切换到系统内核。
                Log.d("app", "腾讯X5内核初始化回调 onViewInitFinished is " + arg0);
            }
            @Override
            public void onCoreInitFinished() {
                Log.d("app", "腾讯X5内核初始化回调 onCoreInitFinished");
            }
        });
    }

    //启用硬件加速:由于硬件加速自身并非完美无缺,所以Android提供选项来打开或者关闭硬件加速,默认是关闭。可以在4个级别上打开或者关闭硬件加速
    private void initHardwareAccelerate() {
        try {
            if (Build.VERSION.SDK_INT >= 11) {
            	//Window级别硬件加速
                getWindow()
                        .setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
            }
        } catch (Exception e) {
        }
    }

    //设置返回键监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (myX5WebView != null && myX5WebView.canGoBack()) {
                myX5WebView.goBack();
                return true;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    //释放资源,防止内存泄露
    @Override
    protected void onDestroy() {
        if (myX5WebView != null) {
            myX5WebView.destroy();
        }
        super.onDestroy();
    }
	
	//设置ToolBar菜单选项
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_webview, menu);
        return true;
    }

    //Toolbar选择选项监听
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                break;
            case R.id.share:
                Intent intent = new Intent();
                intent.setData(Uri.parse(baseurl));
                intent.setAction(Intent.ACTION_VIEW);
                startActivity(intent);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

Effect

insert image description here

Reminder from the official official access document

  1. X5 does not provide 64-bit so files for the time being. In order to ensure that 64-bit mobile phones can load the x5 kernel normally, please refer to the following link to modify the relevant configuration https://x5.tencent.com/tbs/technical.html#/detail/sdk/1/ 34cf1488-7dc2-41ca-a77f-0014112bcab7
  2. Adjust the use of cookies:
    The calls of com.tencent.smtt.sdk.CookieManager and com.tencent.smtt.sdk.CookieSyncManager related interfaces need to be placed after the X5 WebView is created after accessing the SDK (that is, the X5 kernel is loaded complete); otherwise, cookie-related operations can only affect the system kernel.
  3. The following interfaces are forbidden to call (directly or reflectively) to prevent the video screen from being displayed:
    webview.setLayerType()
    webview.setDrawingCacheEnabled(true);
  4. Instructions for app custom UA
    If the app needs to customize UA, it is recommended to add the app UA after the SDK default UA Example:
    webSetting.setUserAgentString(webSetting.getUserAgentString() + APP_NAME_UA);
    where APP_NAME_UA is the app custom UA
  5. Handling of app confusion
    Since the TBS jar we provided has been confused, we can no longer confuse our TBS jar when App is confused, or we can add our confusion strategy proguard to the App confusion strategy. Note: If the App does not Obfuscating the TBS jar according to this rule may result in the inability to use the x5 kernel
  6. Tbs video player access instructions
    TBS not only provides a powerful web browsing function, but also provides a powerful page H5 video playback support, the player supports pages, small windows, full-screen playback experience, and powerful decoding capabilities, including mp4, rmvb , flv, avi and other 26 video formats are supported.
    The playback scene of the TBS player is not limited to H5 page playback, but can also access general video stream links, such as local files and network video stream links. If a developer wants to play a video link, without developing the player himself, the general method is to put the video playback link in an Intent and throw it to the system player for playback. Then when you integrate TBS, You only need to access the video playback call interface in a simple way, so that you don't need to write any code about the player, you can enjoy a local player experience, and you don't need Intent to call across Apps and processes to play videos .

The following are the steps of video playback access:
1. The first step
AndroidManifest requires the following registration:

<activity
	android:name="com.tencent.smtt.sdk.VideoActivity"
	android:configChanges="orientation|screenSize|keyboardHidden"
	android:exported="false"
	android:launchMode="singleTask"
	android:alwaysRetainTaskState="true">
	<intent-filter>
		<action android:name="com.tencent.smtt.tbs.video.PLAY" />
		<category android:name="android.intent.category.DEFAULT" />
	</intent-filter>
</activity>


Note: VideoActivity is a built -in component of TBS, which requires the App to be configured
as
above.

public static boolean canUseTbsPlayer(Context context)
//判断当前Tbs播放器是否已经可以使用。
public static void openVideo(Context context, String videoUrl)
//直接调用播放接口,传入视频流的url
public static void openVideo(Context context, String videoUrl, Bundle extraData)
//extraData对象是根据定制需要传入约定的信息,没有需要可以传如null
//extraData可以传入key: "screenMode", 值: 102, 来控制默认的播放UI
//类似: extraData.putInt("screenMode", 102); 来实现默认全屏+控制栏等UI
  1. Optimize exception reporting:
    In order to improve the stability of the partner's webview scene, discover and solve x5-related problems in a timely manner, when a crash or other abnormal situation occurs on the client and is reported to the server, please be sure to bring relevant information about the x5 kernel. The x5 kernel exception information acquisition interface is: com.tencent.smtt.sdk.WebView.getCrashExtraMessage(context). Take bugly log reporting as an example:
  UserStrategy strategy = new UserStrategy(appContext);
  strategy.setCrashHandleCallback(new CrashReport.CrashHandleCallback() {
    public Map<String, String> onCrashHandleStart(int crashType, String errorType, String errorMessage, String errorStack) {
      LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
      String x5CrashInfo = com.tencent.smtt.sdk.WebView.getCrashExtraMessage(appContext);
      map.put("x5crashInfo", x5CrashInfo);
      return map;
    }
    @Override
    public byte[] onCrashHandleStart2GetExtraDatas(int crashType, String errorType, String errorMessage, String errorStack) {
      try {
        return "Extra data.".getBytes("UTF-8");
      } catch (Exception e) {
        return null;
      }
    }
  });
  CrashReport.initCrashReport(appContext, APPID, true, strategy);

Guess you like

Origin blog.csdn.net/weixin_44565784/article/details/100057603