Pass and return the values from javascript and android and use as a phone gap plugin

我是研究僧i 提交于 2019-12-28 13:56:59

问题


I want to create a plugin for phone which pass and returns the value between javascript and android.

Can anybody suggest any ideas on how to do this?


回答1:


Actually, this is not very difficult. Here, I will show you how to call native code from javascript within the page and vice-versa:

Calling native code from within web view:
When creating the web view add javascript interface (basically java class whose methods will be exposed to be called via javascript in the web view.

JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");

The definition of the javascript interface class itself (this is exemplary class I took from another answer of mine and opens video in native intent)

public class JavaScriptInterface {
    private Activity activity;

    public JavaScriptInterface(Activity activiy) {
        this.activity = activiy;
    }

    public void startVideo(String videoAddress){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse(videoAddress), "video/3gpp"); // The Mime type can actually be determined from the file
        activity.startActivity(intent);
    }
}

Now if you want to call this code form the HTML of the page you provide the following method:

<script>
    function playVideo(video){
        window.JSInterface.startVideo(video);
    }
</script>

Easy isn't it?

Calling javascript code from native code:
This is also simple suppose in the code of the HTML loaded in WebView you have javascript function defined:

<script>
    function function(){
        //... do something
    }
</script>

Then you call this function through the WebView in the native code like that:

webView.loadUrl("javascript:function()");



回答2:


Here's a tutorial for creating a PhoneGap Plugin. Also the instructions for the ChildBrowser plugin are especially good.



来源:https://stackoverflow.com/questions/8982570/pass-and-return-the-values-from-javascript-and-android-and-use-as-a-phone-gap-pl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!