Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 238
user1051599 Avatar asked Jan 24 '12 05:01

user1051599


1 Answers

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()");
like image 198
Boris Strandjev Avatar answered Sep 24 '22 18:09

Boris Strandjev