0

Giới thiệu VasSonic-Hybrid framework

Giới thiệu

Mình hay vào githup theo dõi trending để xem và cập nhật các thư viện cũng như các công nghệ mới được update và có ví dụ minh họa trực tiếp nhất . Ngày hôm nay mình xin phép được giới thiệu 1 framework nhỏ gọn giúp ích khá nhiều trong việc hiển thị web trên nhiều nền tảng cả Android, IOS. Như lời giới thiệu của nhóm phát triển :

VasSonic là một Hybrid framework nhẹ và có hiệu suất cao được phát triển bởi Tencent VAS team, mục đích nhằm tăng tốc việc load trang web lần đầu tiên. Nó không chỉ hỗ trợ các trang web tĩnh, động load online mà hỗ trợ load cả các tài nguyên web offline từ asset. (VasSonic is a lightweight and high-performance Hybrid framework developed by tencent VAS team, which is intended to speed up the first screen of websites working on Android and iOS platform. Not only does VasSonic supports the static or dynamic websites which are rendered by server, but it is also compatible with web offline resource perfectly.)

VasSonic có thể tùy chỉnh URL connection nên thay vi việc đợi load xong data mới hiển thị hoặc kết nối sau khi khởi tạo view thì VasSonic có thể kết nối song song và vừa load vừa hiển thị 1 phần data dựa trên Webkit hoặc Blink kernel tăng tốc độ hiển thị data, từ đó mà dữ liệu hiển thị 1 cách mượt mà hơn. ( VasSonic uses custom url connection instead of original network connection to request the index html, so it can request resource in advance or parallel to avoid waiting for the view initialization. In this parallel case, VasSonic can read and render partial data by WebKit or Blink kernel without spending too much time waiting for the end of data stream.)

Việc sử dụng VasSonic khá đơn giản. Bộ thư viện khá nhẹ.

Demo

Để thể hiện được sức mạnh và sự đơn giản của framework này mình và các bạn cùng bắt tay thực hiện demo sau nhé.

Demo 1 :

Demo này khá đơn giản , chúng ta chỉ cần kéo source từ githup của VasSonic : https://github.com/Tencent/VasSonic việc khởi chạy khá đơn giản. Khi start bạn thưc sự kiểm chứng được sức mạnh cũng như tốc độ của framwork này :

Pic 1: Before Using VasSonic

Pic 2: After Using VasSonic

Sau khi thực hiện xong demo 1 ta chuyển sang thực hiện 1 project demo sử dụng VasSonic nhằm hiểu rõ hơn về framework này

Demo 2 :

  • Bước 1 : Tạo 1 project đơn giản trong Android studio
  • Bước 2 : Trong file gradle bạn add VasSonic dependency
compile 'com.tencent.sonic:sdk:1.0.0'
  • Bước 3 : Tạo 1 class exten SonicRuntime
public class HostSonicRuntime extends SonicRuntime {
    public HostSonicRuntime(Context context) {
        super(context);
    }
    /**
     * @return User's UA
     */
    @Override
    public String getUserAgent() {
        return "";
    }
    /**
     * @return the ID of user.
     */
    @Override
    public String getCurrentUserAccount() {
        return "";
    }
    /**
     * @return the file path which is used to save Sonic caches.
     */
    @Override
    public File getSonicCacheDir() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator         + "sonic/";
        File file = new File(path.trim());
        if(!file.exists()){
            file.mkdir();
        }
        return file;
    }
}
  • Bước 4 : Khởi tạo 1 sub class kế thừa : SonicSessionClient
/**
 *
 * SonicSessionClient  is a thin API class that delegates its public API to a backend WebView class instance, such as loadUrl and loadDataWithBaseUrl.
 */
public class SonicSessionClientImpl extends SonicSessionClient {
    private WebView webView;
    public void bindWebView(WebView webView) {
        this.webView = webView;
    }
    
    @Override
    public void loadUrl(String url, Bundle extraData) {
        webView.loadUrl(url);
    }

    @Override
    public void loadDataWithBaseUrl(String baseUrl, String data, String mimeType, String encoding,                
                                    String historyUrl) {
        webView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
    }
}
  • Bước 5 : Khởi tạo activity demo :
public class BrowserActivity extends Activity {

    public final static String PARAM_URL = "param_url";

    public final static String PARAM_MODE = "param_mode";

    private SonicSession sonicSession;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        String url = intent.getStringExtra(PARAM_URL);
        int mode = intent.getIntExtra(PARAM_MODE, -1);
        if (TextUtils.isEmpty(url) || -1 == mode) {
            finish();
            return;
        }

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

        // step 1: Initialize sonic engine if necessary, or maybe u can do this when application created
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }

        SonicSessionClientImpl sonicSessionClient = null;

        // step 2: Create SonicSession
        sonicSession = SonicEngine.getInstance().createSession(url,  new SonicSessionConfig.Builder().build());
        if (null != sonicSession) {
            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
        } else {
            // this only happen when a same sonic session is already running,
            // u can comment following codes to feedback as a default mode.
            throw new UnknownError("create session fail!");
        }

        // step 3: BindWebView for sessionClient and bindClient for SonicSession
        // in the real world, the init flow may cost a long time as startup
        // runtime、init configs....
        setContentView(R.layout.activity_browser);
        WebView webView = (WebView) findViewById(R.id.webview);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (sonicSession != null) {
                    sonicSession.getSessionClient().pageFinish(url);
                }
            }

            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (sonicSession != null) {
                //step 6: Call sessionClient.requestResource when host allow the application 
                // to return the local data .
                    return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
                }
                return null;
            }
        });

        WebSettings webSettings = webView.getSettings();

        // step 4: bind javascript
        // note:if api level lower than 17(android 4.2), addJavascriptInterface has security
        // issue, please use x5 or see https://developer.android.com/reference/android/webkit/
        // WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)
        webSettings.setJavaScriptEnabled(true);
        webView.removeJavascriptInterface("searchBoxJavaBridge_");
        intent.putExtra(SonicJavaScriptInterface.PARAM_LOAD_URL_TIME, System.currentTimeMillis());
        webView.addJavascriptInterface(new SonicJavaScriptInterface(sonicSessionClient, intent), "sonic");

        // init webview settings
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);


        // step 5: webview is ready now, just tell session client to bind
        if (sonicSessionClient != null) {
            sonicSessionClient.bindWebView(webView);
            sonicSessionClient.clientReady();
        } else { // default mode
            webView.loadUrl(url);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
        super.onDestroy();
    }

Kết thúc :

Trên đây là phần giới thiệu của mình về 1 thư viện nhỏ nhưng có tính ứng dụng khá cao, rất mong được sự góp ý của các bạn. Bài viết của mình được sử dụng từ githup : https://github.com/Tencent/VasSonic các bạn có thể truy cập để cập nhật cũng như tìm hiểu sâu hơn thư viện này.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí