日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

Crosswalk入门

發(fā)布時(shí)間:2023/12/20 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Crosswalk入门 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Crosswalk入門(mén)

  • CSDN資訊:Crosswalk的介紹
  • Crosswalk官方地址

上面的鏈接可以看到Crosswalk的介紹,Crosswalk種種吹牛逼的描述我就不寫(xiě)了。
寫(xiě)一下我的使用感受:

  • 不用費(fèi)力搞什么自己封裝了,直接像用WebView一樣使用。
    在使用android-chromium這個(gè)庫(kù)時(shí),不僅要自己封裝API來(lái)方便使用,還要操心Chromium的初始化,甚至還需要在清單文件里寫(xiě)一堆關(guān)于Chromium的東西,用來(lái)幫助Chromium建立單獨(dú)的進(jìn)程(Crosswalk只會(huì)創(chuàng)建Chromium的線程,不需要獨(dú)立進(jìn)程)。
  • Crosswalk由組織維護(hù),比個(gè)人維護(hù)強(qiáng)多了。
  • 跟隨最新的Chromium不斷更新,js等不用擔(dān)心有函數(shù)沒(méi)法使用。而且不斷更新過(guò)程中,肯定也會(huì)修復(fù)以前存在的bug,穩(wěn)定性也是不用擔(dān)心的。
  • 最新穩(wěn)定版Crosswalk基于Chromium38編譯。
    注:此庫(kù)也可以配合Cordova(PhoneGap)使用。
    OK,感受說(shuō)完,上教程。

    集成到應(yīng)用中

  • 下載zip包,解壓后導(dǎo)入。
  • 關(guān)聯(lián)此Library。
  • 在清單文件中寫(xiě)入下列權(quán)限

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    注:使用過(guò)程中,觀察Logcat可以看到報(bào)需要藍(lán)牙權(quán)限,可以不用管它,不添加藍(lán)牙權(quán)限可以正常使用。
    此外,使用XWalkView必須開(kāi)啟硬件加速。

    XWalkView needs hardware acceleration to render web pages. As a result, the AndroidManifest.xml of the caller's app must be appended with the attribute "android:hardwareAccelerated" and its value must be set as "true".

    android:hardwareAccelerated : The default value is "true" if you've set either minSdkVersion or targetSdkVersion to "14" or higher; otherwise, it's "false".

    在清單文件Application中聲明即可。

    <application android:name="android.app.Application" android:label="XWalkUsers" android:hardwareAccelerated="true">
  • 基本使用

    Crosswalk中用來(lái)替代WebView的控件叫XWalkView。

    layout文件寫(xiě)法

    和其他自定義控件一樣。

    <org.xwalk.core.XWalkView android:id="@+id/activity_main" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> </org.xwalk.core.XWalkView>

    代碼中使用

    重中之重:防止內(nèi)存泄漏

    和其他Android的控件不同,這個(gè)類(lèi)需要監(jiān)聽(tīng)系統(tǒng)事件。例如:生命周期、intent、Activity result。
    控件內(nèi)置的Web引擎需要獲取并處理這些信息。并且當(dāng)XWalkView 不再需要使用的時(shí)候,在onDestroy方法中XWalkView必須顯式的調(diào)用destroy方法,否則容易造成Web引擎的內(nèi)存泄漏。
    原文如下:

    Unlike other Android views, this class has to listen to system events like application life cycle, intents, and activity result. The web engine inside this view need to get and handle them. And the onDestroy() method of XWalkView MUST be called explicitly when an XWalkView won't be used anymore, otherwise it will cause the memory leak from the native side of the web engine. It's similar to the destroy() method of Android WebView.

    這段文字來(lái)自XWalkView官方API文檔。奇怪的是官方的范例中并沒(méi)有在意這些事情,直接像WebView一樣使用,更沒(méi)有使用destroy方法。
    考慮到之前使用android-chromium庫(kù)也是需要顯式調(diào)用。這里還是加上,避免內(nèi)存泄漏。

    import android.app.Activity;import android.os.Bundle;import org.xwalk.core.XWalkView;public class MyActivity extends Activity {private XWalkView mXWalkView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mXWalkView = (XWalkView) findViewById(R.id.activity_main);mXWalkView.load("http://crosswalk-project.org/", null);}@Overrideprotected void onPause() {super.onPause();if (mXWalkView != null) {mXWalkView.pauseTimers();mXWalkView.onHide();}}@Overrideprotected void onResume() {super.onResume();if (mXWalkView != null) {mXWalkView.resumeTimers();mXWalkView.onShow();}}@Overrideprotected void onDestroy() {super.onDestroy();if (mXWalkView != null) {mXWalkView.onDestroy();}}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {if (mXWalkView != null) {mXWalkView.onActivityResult(requestCode, resultCode, data);}}@Overrideprotected void onNewIntent(Intent intent) {if (mXWalkView != null) {mXWalkView.onNewIntent(intent);}}}

    loadUrl去哪了?

    上面的代碼中其實(shí)已經(jīng)劇透了,使用load方法即可。

    // url mXWalkView.load("http://crosswalk-project.org/", null);// this loads a file from the assets/ directory mXWalkView.load("file:///android_asset/index.html", null);

    public void load (String url, String content)
    Load a web page/app from a given base URL or a content. If url is null or empty and content is null or empty, then this function will do nothing. If content is not null, load the web page/app from the content. If content is not null and the url is not set, return "about:blank" ifi calling getUrl(). If content is null, try to load the content from the url. It supports URL schemes like 'http:', 'https:' and 'file:'. It can also load files from Android assets, e.g. 'file:///android_asset/'.
    Parameters
    url the url for web page/app.
    content the content for the web page/app. Could be empty.

    WebViewClient?

    對(duì)應(yīng)WebView的WebViewClient,XWalkView中有XWalkResourceClient。

    mXWalkView.setResourceClient(new XWalkResourceClient(mXWalkView){@Overridepublic void onLoadFinished(XWalkView view, String url) {super.onLoadFinished(view, url);}@Overridepublic void onLoadStarted(XWalkView view, String url) {super.onLoadStarted(view, url);} });

    調(diào)用JavaScript

    不像WebView一樣獲取setting設(shè)置setJavaScriptEnabled為true才能執(zhí)行。
    Crosswalk可以直接執(zhí)行js。

    mXWalkView.load("javascript:document.body.contentEditable=true;", null);

    當(dāng)然,按照Kitkat引入的方式,使用evaluateJavascript方法也是可以的。(大神們推薦)

    JavaScript回調(diào)Java

  • 定義js回調(diào)接口

    public class JsInterface {public JsInterface() {}@JavascriptInterfacepublic String sayHello() {return "Hello World!";} }

    Caution: If you've set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available to your JavaScript (the method must also be public). If you do not provide the annotation, the method is not accessible by your web page when running on Android 4.2 or higher.
    From developer.android.com

    備注:這里的@JavaScriptInterface所在的包是import org.xwalk.core.JavascriptInterface;

  • XWalkView設(shè)置JavaScript可用且綁定對(duì)象

    //綁定 mXWalkView.addJavascriptInterface(new JsInterface(), "NativeInterface");
  • 調(diào)用html執(zhí)行JavaScript或直接執(zhí)行Javascript調(diào)用Java

    mXWalkView.load("file:///android_asset/index.html", null);

    index.html源碼:

    <a href="#" onclick="clicked()">Say Hello</a> <script> function clicked() {alert(NativeInterface.sayHello()); } </script>
  • 高級(jí)使用

    調(diào)試

    Kitkat開(kāi)始,Android提供了和Chrome聯(lián)調(diào)功能??梢院芊奖愕脑贑hrome中調(diào)試WebView中的代碼。
    Crosswalk使用Chromium內(nèi)核當(dāng)然也具備這個(gè)功能。
    開(kāi)啟調(diào)試的語(yǔ)句如下:

    // turn on debuggingXWalkPreferences.setValue(XWalkPreferences.REMOTE_DEBUGGING, true);

    對(duì)于Crosswalk來(lái)說(shuō),這個(gè)設(shè)置是全局的。

    使用動(dòng)畫(huà)或者設(shè)置隱藏可見(jiàn)注意

    默認(rèn)XWalkView不能使用動(dòng)畫(huà),甚至setVisibility也不行。

    XWalkView represents an Android view for web apps/pages. Thus most of attributes for Android view are valid for this class. Since it internally uses android.view.SurfaceView for rendering web pages by default, it can't be resized, rotated, transformed and animated due to the limitations of SurfaceView. Alternatively, if the preference key ANIMATABLE_XWALK_VIEW is set to True, XWalkView can be transformed and animated because TextureView is intentionally used to render web pages for animation support. Besides, XWalkView won't be rendered if it's invisible.

    開(kāi)啟動(dòng)畫(huà)模式:

    @Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// ANIMATABLE_XWALK_VIEW preference key MUST be set before XWalkView creation.XWalkPreferences.setValue(XWalkPreferences.ANIMATABLE_XWALK_VIEW, true);setContentView(R.layout.animatable_xwview_layout); } @Override public void onDestroy() {super.onDestroy();// Reset the preference for animatable XWalkView.XWalkPreferences.setValue(XWalkPreferences.ANIMATABLE_XWALK_VIEW, false); }

    由于設(shè)置也像調(diào)試一樣是全局的,在onDestroy時(shí)記得關(guān)閉。

    暫停JS timer

    html代碼

    <!DOCTYPE html> <html> <body><p>A script on this page starts this clock:</p> <p id="demo"></p><script>var myVar = setInterval(function(){ myTimer(); }, 1000);function myTimer(){var d = new Date();var t = d.toLocaleTimeString();document.getElementById("demo").innerHTML = t;} </script></body> </html>

    XWalkView對(duì)應(yīng)方法:

    mButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {if (mXWalkView != null) {if (!isPaused) {// Pause JS timermXWalkView.pauseTimers();isPaused = true;mButton.setImageResource(android.R.drawable.ic_media_play);} else {// Resume JS timermXWalkView.resumeTimers();isPaused = false;mButton.setImageResource(android.R.drawable.ic_media_pause);}}} });

    這也在防止內(nèi)存泄漏,監(jiān)聽(tīng)系統(tǒng)事件示例代碼中提到過(guò):

    @Override protected void onPause() {super.onPause();if (mXWalkView != null) {mXWalkView.pauseTimers();mXWalkView.onHide();} }@Override protected void onResume() {super.onResume();if (mXWalkView != null) {mXWalkView.resumeTimers();mXWalkView.onShow();} }

    歷史記錄

    mPrevButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// Go backwardif (mXWalkView != null &&mXWalkView.getNavigationHistory().canGoBack()) {mXWalkView.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.BACKWARD, 1);}XWalkNavigationItem navigationItem = mXWalkView.getNavigationHistory().getCurrentItem();showNavigationItemInfo(navigationItem);} });mNextButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// Go forwardif (mXWalkView != null &&mXWalkView.getNavigationHistory().canGoForward()) {mXWalkView.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.FORWARD, 1);}XWalkNavigationItem navigationItem = mXWalkView.getNavigationHistory().getCurrentItem();showNavigationItemInfo(navigationItem);} });private void showNavigationItemInfo(XWalkNavigationItem navigationItem){url = navigationItem.getUrl();// Get the url of current navigation item.originalUrl = navigationItem.getOriginalUrl();// Get the original url of current navigation itemtitle = navigationItem.getTitle();text1.setText(title);text2.setText(url);text3.setText(originalUrl); }

    自動(dòng)視頻暫停

    // The web page below will display a video. // When home button is pressed, the activity will be in background, and the video will be paused. mXWalkView.load("http://www.w3.org/2010/05/video/mediaevents.html", null);

    loadAppFromManifest

    mXWalkView.loadAppFromManifest("file:///android_asset/manifest.json", null);

    manifest.json

    {"name": "ManifestTest","start_url": "index.html","description": "Manifest test","version": "1.0.0" } 作者:GavinCT?
    出處:http://www.cnblogs.com/ct2011/

    總結(jié)

    以上是生活随笔為你收集整理的Crosswalk入门的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。