简体   繁体   English

使用cordova-plugin-crosswalk-webview从JS调用本机Java代码

[英]Calling native java code from JS with cordova-plugin-crosswalk-webview

I can successfully call native java code from JS in a Cordova 5.4.0 application using @JavascriptInterface. 我可以使用@JavascriptInterface在Cordova 5.4.0应用程序中从JS成功调用本地Java代码。 But after adding cordova-plugin-crosswalk-webview, it is not working. 但是在添加cordova-plugin-crosswalk-webview之后,它不起作用。 After searching, I have modify my code as:- 搜索后,我将代码修改为:-

public class MainActivity extends CordovaActivity{
    @Override
    public void onCreate(Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      loadUrl("file://android_assets/www/index.html");
      ((XWalkView)appView.getEngine().getView()).addJavascriptInterface(this,"MainActivity");
    }

   @JavascriptInterface
   public void getMessage() {
        Toast.makeText(getApplicationContext(), "this is my Toast message!!!  =)",Toast.LENGTH_LONG).show();
   }

}

And calling native code from js as: 并从js调用本机代码为:

window.MainActivity.getMessage();

I also imported 我也进口了

import org.xwalk.core.JavascriptInterface;
import org.xwalk.core.XWalkView;

Also tried replacing 还尝试更换

@JavascriptInterface

with

@org.xwalk.core.JavascriptInterface

Now the app even not opening. 现在,该应用程序甚至无法打开。 It crash. 它崩溃了。 Help Plz. 帮助Plz。

Calling the addJavaScriptInterface() inside the onXWalkReady() instead of doing this in the onCreate() callback solved this issue to me. addJavaScriptInterface()内部调用onXWalkReady()而不是在onCreate()回调中执行此操作,对我来说解决了这个问题。

PS: Method chaining is not a good practice. PS:方法链接不是一个好习惯。

config.xml首选项name="android-minSdkVersion" value="16" 更新为首选项name="android-minSdkVersion" value="17并使用import org.xwalk.core.JavascriptInterface;使用cordova版本6.3.0或更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM