安卓开发腾讯X5第三库使用心得

最近放暑假,没有时间研究和学习,最近开学后,研究了一下webview,发现原生的webview加载好慢,而已有些图片和动画加载不出来,看文档说要硬件加速等等,官方的介绍:https://developer.android.com/guide/topics/graphics/hardware-accel.html
后来百度发现有个腾讯X5的第三方库:https://x5.tencent.com/tbs/
但是看了他的接入文档:https://x5.tencent.com/tbs/guide/sdkInit.html,还是一脸蒙蔽,按照他的做了后面发现接入的还是不行,最后下载他的demo,按照demo的做法,最后终于成功了,他的只要配置了几个地方
1:将他的库复制到lib目录下
这里写图片描述

2:新建jniLibs目录
这里写图片描述

3:最后在APP的build.gradle文件下添加几行代码

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.guet.andream.andreamtwo"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        ndk {
            abiFilters "armeabi", "armeabi-v7a", "x86", "mips"
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.github.ybq:Android-SpinKit:1.1.0'
}

4:在APP启动时进行初始化

public class App extends Application {@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    //搜集本地tbs内核信息并上报服务器,服务器返回结果决定使用哪个内核。

    QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

        @Override
        public void onViewInitFinished(boolean arg0) {
            // TODO Auto-generated method stub
            //x5內核初始化完成的回调,为true表示x5内核加载成功,否则表示x5内核加载失败,会自动切换到系统内核。
            Log.d("app", " onViewInitFinished is " + arg0);
        }

        @Override
        public void onCoreInitFinished() {
            // TODO Auto-generated method stub
        }
    };
    //x5内核初始化接口
    QbSdk.initX5Environment(getApplicationContext(),  cb);
}
}

这样就配置完了

后面就可以进行开发了,话不多说直线上代码
代码部分,首先是布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.guet.andream.andreamtwo.MainActivity">
   <com.guet.andream.andreamtwo.X5WebView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/web_filechooser">
   </com.guet.andream.andreamtwo.X5WebView>
   <com.github.ybq.android.spinkit.SpinKitView
       xmlns:app="http://schemas.android.com/apk/res-auto"
       android:id="@+id/spin_kit"
       style="@style/SpinKitView.Large.Circle"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="center"
       android:layout_centerVertical="true"
       android:layout_centerHorizontal="true"
       app:SpinKit_Color="@color/colorAccent" />
   <TextView
       android:layout_width="wrap_content"
       android:text="加载中...."
       android:id="@+id/loadText"
       android:textColor="@color/colorAccent"
       android:textSize="18sp"
       android:layout_below="@+id/spin_kit"
       android:layout_centerHorizontal="true"
       android:layout_height="wrap_content" />
   <View
       android:layout_width="match_parent"
       android:layout_height="25dp"
       android:background="#fff"
       android:id="@+id/hiddenView"
       android:layout_alignParentBottom="true"
      />
</RelativeLayout>

接下来的是自定义webview

public class X5WebView extends WebView {
    private WebViewClient client = new WebViewClient() {
        /**
         * 防止加载网页时调起系统浏览器
         */
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    };

    @SuppressLint("SetJavaScriptEnabled")
    public X5WebView(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
        this.setWebViewClient(client);
        initWebViewSettings();
        this.getView().setClickable(true);
    }

    private void initWebViewSettings() {
        WebSettings webSetting = this.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);

        // this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension
        // settings 的设计
    }

    public X5WebView(Context arg0) {
        super(arg0);
        setBackgroundColor(85621);
    }

}

接下来的是activity的代码

public class MainActivity extends AppCompatActivity {
    private X5WebView webView;
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;
    private ProgressBar progressBar;
    private View hiddenView;
    private TextView loadText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (X5WebView) findViewById(R.id.web_filechooser);
         progressBar = (ProgressBar)findViewById(R.id.spin_kit);
        hiddenView=findViewById(R.id.hiddenView);
        loadText= (TextView) findViewById(R.id.loadText);
//配置加载动画
        FadingCircle doubleBounce = new FadingCircle();
        progressBar.setIndeterminateDrawable(doubleBounce);


        webView.setWebChromeClient(new WebChromeClient() {
            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                Log.i("test", "openFileChooser 1");
                MainActivity.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
                Log.i("test", "openFileChooser 2");
                MainActivity.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.e("test", "openFileChooser 3");
                MainActivity.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  >= 5.0
            public boolean onShowFileChooser(com.tencent.smtt.sdk.WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                Log.e("test", "openFileChooser 4:" + filePathCallback.toString());
                MainActivity.this.uploadFiles = filePathCallback;
                openFileChooseProcess();
                return true;
            }

        });
        webView.getSettings().setUseWideViewPort(true); //自适应屏幕
        webView.loadUrl("https://jianfengandream.kuaizhan.com/");

        //webView加载监听
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);

                progressBar.setVisibility(View.GONE);
                hiddenView.setVisibility(View.GONE);
                loadText.setVisibility(View.GONE);
            }

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
            }
        });
        //webView加载百分比监听
        webView.setWebChromeClient(new WebChromeClient()
        {
            @Override
            public void onProgressChanged(WebView webView, int i) {
                super.onProgressChanged(webView, i);
                Log.e("---TEST---", String.valueOf(i));


            }
        });

    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        }
        else {
            finish();
            return true;
        }
    }
    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "test"), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }

        }
    }

    /**
     * 确保注销配置能够被释放
     */
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (this.webView != null) {
            webView.destroy();
        }
        super.onDestroy();
    }
}

最后是效果图
这里写图片描述

如有什么不对的地方请指出,有啥疑问可以咨询
源码:http://download.csdn.net/download/qq_36480491/9968302

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
腾讯X5内核是一款支持多进程、支持硬件加速、支持自定义内核扩展的WebView内核。在Android开发中,使用腾讯X5内核可以提高WebView的性能和稳定性,下面是一些优化和实践总结: 1. 引入腾讯X5内核 引入腾讯X5内核需要在项目中添加相应的依赖,然后在代码中进行初始化和使用。具体步骤可以参考腾讯官方文档。 2. 启用硬件加速使用腾讯X5内核时,可以启用硬件加速来提高WebView的渲染速度。具体可以通过设置WebView的LayerType属性来实现,例如: ``` webView.setLayerType(View.LAYER_TYPE_HARDWARE, null); ``` 3. 使用预加载 预加载可以在用户点击链接之前就开始加载下一页的内容,以提高用户体验和减少页面加载时间。腾讯X5内核提供了预加载功能,可以通过设置WebView的预加载模式来实现,例如: ``` webView.getX5WebViewExtension().setPageCacheCapacity(5); // 设置最大缓存页面数为5 webView.getX5WebViewExtension().setPreload(true); // 开启预加载模式 ``` 4. 优化JSBridge通信 JSBridge是一种用于WebView和Native代码之间通信的技术,但是在使用过程中容易出现性能问题。为了优化JSBridge通信,可以使用腾讯X5内核提供的基于V8引擎的JSBridge,它可以提高通信效率和稳定性。 5. 避免WebView内存泄漏 在使用WebView时,需要注意避免内存泄漏问题。具体可以通过以下方式来避免: - 及时释放WebView对象 - 使用静态内部类或弱引用来持有WebView对象 - 在Activity的onDestroy()方法中调用WebView的destroy()方法 总之,腾讯X5内核是一款非常强大的WebView内核,可以帮助我们优化WebView的性能和稳定性。在使用中,需要注意以上几点优化和实践。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值