【vue+android】vue与Android交互

6,295 阅读2分钟

本文只涉及vue调用android中的函数,若想了解android调用vue中的js代码请参考其他文章😀

如: www.jb51.net/article/140…

Android中显示vue构建的页面

参考: github.com/ljnjiannan/…

创建X5WebView

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(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);
		webSetting.setAllowUniversalAccessFromFileURLs(true);
	}

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

}

创建MyApplication:

public class MyApplication extends Application {

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();

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

            @Override
            public void onViewInitFinished(boolean arg0) {
                Log.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
            }
        };
        //x5内核初始化接口
        mContext = getApplicationContext();
        QbSdk.initX5Environment(mContext, cb);
    }

    //之后创建数据库需要用到context
    public static Context getContext(){
        return mContext;
    }
}

修改mainActivity:

ublic class MainActivity extends AppCompatActivity {

    private X5WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mWebView = (X5WebView)findViewById(R.id.webview);
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.i("consoleMessage", consoleMessage.message());
                return super.onConsoleMessage(consoleMessage);
            }
        });
        
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);

       //AndroidToJs类中保存的是供vue调用的函数,android时vue访问时的对象名,会放在window上,用window.android调用
        mWebView.addJavascriptInterface(new AndroidToJS(), "android");
        mWebView.loadUrl("file:///android_asset/test.html");
    }
}

修改AndroidManifest.xml,注意其中的.MyApplication和.MainActivity即可

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.nannan.vue_android">

    <!--    <uses-permission android:name="android.permission.INTERNET"/>-->
<!--    网络文件时需要设置permission -->

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:name=".MyApplication"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

vue调用Android的接口

将页面放入assets下(vue打包后的文件dist在图中也时放到这,为了方便演示,先用简单的test.html)

使用window.android调用,在vue框架写出来的代码中也是如此!

<body>
    <button onclick="inviteBtn()">点我试试看</button>
    <span></span>

    <script>
        function inviteBtn(){
            window.android.saveData("小白","123");
        }

        let data = window.android.getData();
        document.querySelector("span").innerText = data;
    </script>
</body>

(ps:如下,vue打包后的js文件,也是用window.android调用!) 结果显示:

点击按钮之后:

json与字符串的转换

Android给js返回的数组、map对象等需要转成json字符串!!!

推荐使用 com.alibaba.fastjson.JSON;

下载地址: mvnrepository.com/artifact/co…

androidStudio如何导入jar包: www.cnblogs.com/qiuniao/p/1…

使用方法:

Test test = JSON.parseObject(jsonStr, Test.class);//json字符串转对象
jsonStr=JSON.toJSONString(test);//对象转字符串