PhoneGap Framework Detailed

Source: Internet
Author: User

First, take a look at the PhoneGap initialization process and the native and JS interaction flowchart.

Description: Socket server mode, phonegap.js source implementation of the implementation of a XHR request 1 milliseconds, when the native JS queue has JS statement data, is the real 1 milliseconds to call; When there is no data, Scoket server blocks for 10 milliseconds, which means that xhr waits 10 seconds to receive the result and the next polling.

1. Activity inheritance Droidgap (extends phonegapactivity)

Load whitelist configuration and log configuration from Phonegap.xml


2, Loadurl (each activity is initialized once)

"Initialize WebView
"Initialize Callbackserver
"Plugin Manager PlugInManager

3. Load plug-in configuration:

"reads the Plugins.xml configuration and stores it with a map.

<plugins><plugin name= "Camera" value= "Com.phonegap.CameraLauncher"/><plugin name= "Contacts" value= " Com.phonegap.ContactManager "/><plugin name=" Crypto "value=" Com.phonegap.CryptoHandler "/><plugin name= "File" value= "com.phonegap.FileUtils"/><plugin name= "Network Status" value= "Com.phonegap.NetworkManager"/ ></plugins>

Description
Name is an alias, and JavaScript is invoked by an alias when it is called.
Value:java Concrete Implementation Class

Web page invocation (for example, find a Lenovo person)
Phonegap.exec (SUCCESSCB, ERRORCB, "Contacts", "Search", [fields, Options]);


4, plug-in implementation

"Programming Java classes, inheriting the Plugin class (Plugin implements the IPlugin interface), and implements the Execute method.
For example, the contact management plugin:

public class Contactmanager extends plugin{/** * Action: Used to specify a specific action search for contact * args: Method parameters * CALLB Ackid:js and Java specify an identity, */Public Pluginresult Execute (string action, Jsonarray args, string callbackid) {try {if (actio N.equals ("search")) {Jsonarray res = contactaccessor.search (Args.getjsonarray (0), Args.optjsonobject (1)); return new Pluginresult (Status, Res, "Navigator.contacts.cast");}    else if (action.equals ("Save")) {String id = contactaccessor.save (args.getjsonobject (0));                                  if (id! = NULL) {Jsonobject res = Contactaccessor.getcontactbyid (ID);                                 if (res! = NULL) {return new Pluginresult (status, RES); }}}else if (Action.equals ("Remove")) {if (Contactaccessor.remove (args.getstring (0))) {return new pluginres Ult (status, result);}}            If we get to the this point a error has occurred jsonobject r = new Jsonobject ();R.put ("code", Unknown_error); return new Pluginresult (PluginResult.Status.ERROR, R);} catch (Jsonexception e) {log.e (Log_tag, E.getmessage (), e); return new Pluginresult (PluginResult.Status.JSON_EXCEPTION    );} }}

  


5. Polling and server initialization


When Android Droidgap is initialized, polling = True if the Loadurl URL does not start with file://, otherwise it is the socket server way

Code See Callbackserver.java Class init method

public void init (String url) {    //system.out.println ("Callbackserver.start (" +url+ ")");    Determine if XHR or polling is to be used    if ((URL! = null) &&!url.startswith ("file://")) {       This.usepo Lling = true;       This.stopserver ();    }    else if (android.net.Proxy.getDefaultHost () = null) {        this.usepolling = true;        This.stopserver ();    }    else {        this.usepolling = false;        This.startserver ();    }}

  


6, phonegap.js Key code description

PhoneGap. js starts with prompt ("usepolling", "Gap_callbackserver:") to get the call method: XHR Polling or prompt polling, if it is XHR, The XHR call is started to get the HTTP server port and token.


Method PhoneGap.Channel.join Start JS server or polling call

Usepolling defaults to False. Get the call method through var polling = prompt ("usepolling", "Gap_callbackserver:").

PhoneGap.Channel.join (function () {    //Start listening for XHR callbacks    setTimeout (function () {      if ( phonegap.usepolling) {        phonegap.jscallbackpolling ();      }      else {        Console.log (' phonegap.channel.join>>>>>>>>>>>>>>>> >>>>>>>>> ');
//phonegap JS first start get JS call native mode var polling = prompt ("usepolling", "Gap_callbackserver:"); phonegap.usepolling = polling; if (polling = = "true") { phonegap.usepolling = true; phonegap.jscallbackpolling (); } else { phonegap.usepolling = false; Phonegap.jscallback ();}} }, 1);}

  

XHR Polling: Phonegap.jscallback method

Communicate with the Java-side socket via XHR, execute jscallback once per millisecond, get JavaScript execution result code from the Android socket, and execute JavaScript dynamically with Eval

XHR call, get socket port and token (UUID) via prompt

if (Phonegap.jscallbackport = = = null) {Phonegap.jscallbackport =prompt ("Getport", "Gap_callbackserver:");Console.log (' Phonegap.jscallback getport>>>>>>>>>>>>>>>>> >>>>>>>>: ' + Phonegap.jscallbackport);} if (Phonegap.jscallbacktoken = = = null) {Phonegap.jscallbacktoken =prompt ("GetToken", "Gap_callbackserver:");Console.log (' Phonegap.jscallback gettoken>>>>>>>>>>>>>>>>> >>>>>>>>: ' + Phonegap.jscallbacktoken);} Xmlhttp.open ("GET", "http://127.0.0.1:" + phonegap.jscallbackport + "/" + Phonegap.jscallbacktoken, true); xmlhttp.send (); XHR Returns the result code fragment var msg = decodeURIComponent (Xmlhttp.responsetext); SetTimeout (function () {try {var t = eval (msg);} catch (E) {//If we ' re getting an error here, seeing the message would help in debugging Console.log ("Jscallback:messag  E from Server: "+ msg"; Console.log ("Jscallback Error:" + E);}}, 1);setTimeout (Phonegap.jscallback, 1);
}

  

Prompt Polling: Phonegap.jscallbackpolling method

phonegap.jscallbackpolling = function () {    //Exit If shutting down app    if (phonegap.shuttingdown) {
   
    return;    }    If polling flag was changed, the stop using polling from    now on if (! phonegap.usepolling) {      phonegap.jscallback ();      return;    }    var msg = prompt ("", "Gap_poll:");    if (msg) {      setTimeout (function () {        try {          var t = eval ("" + msg);        }        catch (e) {          console.log ("Jscallbackpolling:message from Server:" + msg);          Console.log ("jscallbackpolling Error:" + E);        }      }, 1);      
    setTimeout (phonegap.jscallbackpolling, 1);    }    else {      setTimeout (phonegap.jscallbackpolling, phonegap.jscallbackpollingperiod);    }  };
   

  

7. Summary

  1. phonegap Android Plugin manager PlugInManager initialization, every activity is initialized once, data is cached once, resulting in the same data cache multiple times. --It's unclear why this is achieved? is the PHONEGAP framework for a single webview implementation, if you know why, please inform.

2, the same as the 1th, the Socket server each activity will be initialized, if the Loadurl URL type is different, will not cause the Scoket Server-like body confusion, to be verified !

3, PhoneGap use prompt and XHR polling mechanism, one will lead to serious mobile phone power consumption, the second is to understand that the prompt call is blocking JS execution, which will affect the page loading speed.

PhoneGap has been renamed Cordova, in the latest version Cordova framework has removed the socket server mode, Detailed view: http://www.cnblogs.com/hubcarl/p/4202784.html

PhoneGap Framework Detailed

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.