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

前端 未结 2 958
时光取名叫无心
时光取名叫无心 2020-12-09 23:33

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?

相关标签:
2条回答
  • 2020-12-09 23:57

    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()");
    
    0 讨论(0)
  • 2020-12-09 23:58

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

    0 讨论(0)
提交回复
热议问题