HTML and Java interaction, leveraging the Jsbridge open source framework

Source: Internet
Author: User

HTML, JS Register Listener and callback

        functionConnectwebviewjavascriptbridge (callback) {if(window. Webviewjavascriptbridge) {callback (Webviewjavascriptbridge)}Else{Document.addeventlistener (' Webviewjavascriptbridgeready '                    , function() {Callback (Webviewjavascriptbridge)},false                ); }} Connectwebviewjavascriptbridge (function(bridge) {Bridge.init (function(message, Responsecallback) {alert (' Init method JS received message: ' +message); if(Message.indexof ("url=") >=0){                    varurl = message.substring (4, message.length); Alert ("Received URL:" +URL); document.getElementById ("Show"). InnerHTML = "This is a picture ; }                if(responsecallback) {Responsecallback (' JS returns the message ');JS's return, Java charge
} });
    
Bridge.registerhandler ("Functioninjs", function (data, responsecallback) {//"Submitfromweb") protocol string negotiated for HTML and Java
       Alert (' Registerhandler method JS received message: ' +data);
     if (' Java call js ' ==data) {
     Showalert ("JS own method");
     }
     if (responsecallback) {
     Responsecallback (' JS returned message ');//js's return, Java is charged
     }
});

In Java, registering listeners and callbacks

 Webview.setdefaulthandler (new   DefaultHandler () {@Override  public  void   handler (String data, callbackfunction function) {LOG.D (TA                G,  "Setdefaulthandler method Java received message:" + data);                     if  ("OpenFile" .equals (data)) {                    Pickfile ();                 return  ;  if  (Function! = null   "Java returned message"  Java return, JS charge 
} } }); Webview.setwebchromeclient (mopenfilewebchromeclient);//html Animation requires a registered action object for WebView use
Webview.registerhandler ("Submitfromweb", new Bridgehandler () {//"Submitfromweb" protocol string negotiated for HTML and Java
  @Override
public void handler (String data, callbackfunction function) {
       LOG.I (TAG, "Registerhandler method Java received message:" + data);

Function.oncallback ("message returned by Java"),//java return, JS charge
     }

});

Java sends a message to JS, does not receive the JS response

Webview.send ("Java to JS send Message");

Java to send a message to JS, accept the JS response

if (Button.equals (v)) {            Webview.callhandler (new  callbackfunction () {                @Override                 publicvoid  oncallback (String data) {                    //  TODO auto-generated Method Stub                    log.i (TAG, "JS returned message:" + data);                }            );

JS sends messages to Java and does not receive Java responses

  function Testclick () {            var data = "JS-sent Message";            Window. Webviewjavascriptbridge.send (data);        }

JS sends messages to Java and accepts Java responses

function testClick33 () {            var data = "JS-sent Message";             function (responsedata) {                    alert (' Java returned message: ' +ResponseData} '                );        } function TestClick1 () {      window. Webviewjavascriptbridge.callhandler (           ' submitfromweb '             JS calls Java method '               function (responsedata) {               alert (' Java returned message: ' +responsedata} '       );}

The writing of open files in JS

<input type= "file"  value= "select Files"/>

In Java, you need to set

Webview.setwebchromeclient (mopenfilewebchromeclient);
Openfilewebchromeclient class
 Public classOpenfilewebchromeclientextendswebchromeclient { Public Static Final intRequest_file_picker = 1;  PublicValuecallback<uri>Mfilepathcallback;  PublicValuecallback<uri[]>mfilepathcallbacks;        Activity Mcontext;  Publicopenfilewebchromeclient (Activity mcontext) {Super();  This. Mcontext =Mcontext; }        //Android < 3.0 call this method         Public voidOpenfilechooser (valuecallback<uri>filepathcallback) {Mfilepathcallback=Filepathcallback; Intent Intent=NewIntent (intent.action_get_content);            Intent.addcategory (intent.category_openable); Intent.settype ("*/*"); Mcontext.startactivityforresult (Intent.createchooser (Intent,"File Chooser"), Request_file_picker); }        //3.0 + Call this method         Public voidOpenfilechooser (Valuecallback filepathcallback, String accepttype) {MF Ilepathcallback=Filepathcallback; Intent Intent=NewIntent (intent.action_get_content);            Intent.addcategory (intent.category_openable); Intent.settype ("*/*"); Mcontext.startactivityforresult (Intent.createchooser (Intent,"File Chooser"), Request_file_picker); }        ///JS upload file <input type= "file" Name= "Filefield" id= "Filefield"/> Event capture//Android > 4.1.1 Call this method         Public voidOpenfilechooser (valuecallback<uri>Filepathcallback, String accepttype, string capture) {Mfilepathcallback=Filepathcallback; Intent Intent=NewIntent (intent.action_get_content);            Intent.addcategory (intent.category_openable); Intent.settype ("*/*"); Mcontext.startactivityforresult (Intent.createchooser (Intent,"File Chooser"), Request_file_picker); } @Override Public BooleanOnshowfilechooser (WebView WebView, Valuecallback<Uri[]>Filepathcallback, Webchromeclient.filechooserparams filechooserparams) {Mfilepathcallbacks=Filepathcallback; Intent Intent=NewIntent (intent.action_get_content);            Intent.addcategory (intent.category_openable); Intent.settype ("*/*"); Mcontext.startactivityforresult (Intent.createchooser (Intent,"File Chooser"), Request_file_picker); return true; }    }

In Java, the Onactivityresult method of the current activity

 protected voidOnactivityresult (intRequestcode,intResultCode, Intent Intent) {        if(Requestcode = =Openfilewebchromeclient.request_file_picker) {            if(Mopenfilewebchromeclient.mfilepathcallback! =NULL) {Uri result= Intent = =NULL|| ResultCode! = ACTIVITY.RESULT_OK?NULL: Intent.getdata (); if(Result! =NULL) {String path=Mediautility.getpath (Getapplicationcontext (), result); Uri URI= Uri.fromfile (NewFile (path));                Mopenfilewebchromeclient.mfilepathcallback. Onreceivevalue (URI); } Else{mopenfilewebchromeclient.mfilepathcallback. Onreceivevalue (NULL); }            }            if(Mopenfilewebchromeclient.mfilepathcallbacks! =NULL) {Uri result= Intent = =NULL|| ResultCode! = ACTIVITY.RESULT_OK?NULL: Intent.getdata (); if(Result! =NULL) {String path=Mediautility.getpath (Getapplicationcontext (), result); Uri URI= Uri.fromfile (NewFile (path)); Mopenfilewebchromeclient.mfilepathcallbacks. Onreceivevalue (Newuri[] {Uri}); } Else{mopenfilewebchromeclient.mfilepathcallbacks. Onreceivevalue (NULL); }} mopenfilewebchromeclient.mfilepathcallback=NULL; Mopenfilewebchromeclient.mfilepathcallbacks=NULL; }    }

If there is a problem in subsequent use, add again

HTML and Java interaction, leveraging the Jsbridge open source framework

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.