SlideShare une entreprise Scribd logo
1  sur  14
Télécharger pour lire hors ligne
The	
  Art	
  of	
  Building	
  Bridges
Android	
  WebView	
  Bridge	
  in	
  Depth
Bartłomiej	
  Pisulak
Three	
  types	
  of	
  Mobile	
  Apps
Market	
  Share
According	
  to	
  Gartner	
  more	
  than	
  50%	
  of	
  mobile	
  apps	
  deployed	
  will	
  be	
  hybrid
Architecture
It’s	
  all	
  about	
  WebView…
So	
  what’s	
  the	
  difference?
The	
  Bridge
Bridge	
  between	
  Native	
  and	
  JS
JS	
  -­‐>	
  Native	
  
Native	
  -­‐>	
  JS
JS_Object

JavaScript	
  -­‐>	
  Java
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
Let’s	
  build	
  an	
  interface:
JS_Object

JavaScript	
  -­‐>	
  Java
JS WebView
Quite	
  good	
  performance	
  
Use	
  native	
  bridging	
  suggested	
  by	
  Google	
  
Error	
  prone
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
WebSettings settings =
webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new
WebAppInterface(this), "Android");
Prompt

JavaScript	
  -­‐>	
  Java
JS WebChromeClient
Doesn’t	
  crash	
  the	
  emulator	
  
It’s	
  very	
  slow	
  
Overrides	
  default	
  prompt	
  behaviour	
  in	
  WebView	
  
Criticised	
  as	
  antipattern
<script type="text/javascript">
prompt("toast", "This is Toast message");
</script> @Override
public boolean onJsPrompt (WebView view, String
url, String message, String defaultValue,
JsPromptResult result) {
// message determines action
if(message == "toast") {
// make toast ...
}
}
loadUrl()

Java	
  -­‐>	
  JavaScript	
  
Native JS
Quite	
  fast	
  
Breaks	
  inputs	
  behaviour
<script type="text/javascript">
onLocationUpdate(int lat, int lng) {
alert("Success: lat=" + lat + " lng: " + lng);
}
</script>
@Override
public void onLocationChanged(Location
location) {
String lat =
Double.toString(location.getLatitude());
String lng =
Double.toString(location.getLongitude());
webView.loadUrl("javascript:onLocationUpda
te(" + lat + "," + lng + ");");
}
Online	
  Event

Java	
  -­‐>	
  JavaScript	
  
Native JS
It’s	
  fast	
  
Even	
  faster	
  than	
  loadUrl()	
  
Doesn’t	
  break	
  anything	
  (yet)	
  
Problem	
  in	
  case	
  of	
  bridging	
  more	
  than	
  one	
  WebView
<script type="text/javascript">
var handleEvent = function() {
// get result from native code
// using exposed interface
}
window.addEventListener("online", handleEvent);
window.addEventListener("offline", handleEvent);
</script>
boolean flipFlop;
// (...)
@Override
public void informJavaScriptAboutResult() {
flipFlop = !flipFlop;
webView.setNetworkAvailable(flipFlop);
}
Private	
  API

Java	
  -­‐>	
  JavaScript	
  
Class webViewClass = WebView.class;
try {
Field f = webViewClass.getDeclaredField("mProvider");
f.setAccessible(true);
webViewObject = f.get(webView);
webViewClass = webViewObject.getClass();
} catch (Throwable e) {
// ...
}
try {
Field f = webViewClass.getDeclaredField("mWebViewCore");
f.setAccessible(true);
webViewCore = f.get(webViewObject);
if (webViewCore != null) {
sendMessageMethod = webViewCore.getClass().getDeclaredMethod("sendMessage", Message.class);
sendMessageMethod.setAccessible(true);
}
} catch (Throwable e) {
// ...
}
Be	
  careful	
  while	
  using	
  reflection…
Private	
  API

Java	
  -­‐>	
  JavaScript	
  
Native JS
Super	
  fast	
  
Not	
  supported	
  officially	
  
Works	
  on	
  Android	
  3.2+	
  
May	
  break	
  in	
  the	
  future
<script type="text/javascript">
onLocationUpdate(int lat, int lng) {
alert("Success: lat=" + lat + " lng: " + lng);
}
</script>
try {
String js = "onLocationUpdate(" +
lat + "," + lng + ");";
Message execJsMessage =
Message.obtain(null, EXECUTE_JS, js);
sendMessageMethod.invoke(webViewCore,
execJsMessage);
} catch (Throwable e) {
// ...
}
To	
  Sum	
  Up
Hybrid	
  is	
  the	
  future
Choose	
  proper	
  bridge
QA
Bartłomiej	
  Pisulak	
  
Software	
  Engineer	
  |	
  IT	
  Trainer	
  
http://www.pisulak.pl/

Contenu connexe

Tendances

Intro To JQuery & ASP.NET
Intro To JQuery & ASP.NETIntro To JQuery & ASP.NET
Intro To JQuery & ASP.NETChris Love
 
HTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebHTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebRobert Nyman
 
JavaScript patterns chapter 8 of mine
JavaScript patterns chapter 8 of mineJavaScript patterns chapter 8 of mine
JavaScript patterns chapter 8 of mineChien-Wei Huang
 
1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_queryFajar Baskoro
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScriptShahDhruv21
 
WebSockets Jump Start
WebSockets Jump StartWebSockets Jump Start
WebSockets Jump StartHaim Michael
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events WebStackAcademy
 
MozTW 離線報
MozTW 離線報MozTW 離線報
MozTW 離線報Toomore
 
HTML5 - The 2012 of the Web - Adobe MAX
HTML5 - The 2012 of the Web - Adobe MAXHTML5 - The 2012 of the Web - Adobe MAX
HTML5 - The 2012 of the Web - Adobe MAXRobert Nyman
 
Javascript dom event
Javascript dom eventJavascript dom event
Javascript dom eventBunlong Van
 
The Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event HandlingThe Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event HandlingYorick Phoenix
 
Cross-Platform Desktop Apps with JavaScript
Cross-Platform Desktop Apps with JavaScriptCross-Platform Desktop Apps with JavaScript
Cross-Platform Desktop Apps with JavaScriptBlagoja Evkoski
 

Tendances (20)

Intro To JQuery & ASP.NET
Intro To JQuery & ASP.NETIntro To JQuery & ASP.NET
Intro To JQuery & ASP.NET
 
HTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebHTML5 - The 2012 of the Web
HTML5 - The 2012 of the Web
 
Os mobile
Os mobileOs mobile
Os mobile
 
Os mobile
Os mobileOs mobile
Os mobile
 
Knockoutjs
KnockoutjsKnockoutjs
Knockoutjs
 
JavaScript patterns chapter 8 of mine
JavaScript patterns chapter 8 of mineJavaScript patterns chapter 8 of mine
JavaScript patterns chapter 8 of mine
 
1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_query
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Js unit testing
Js unit testingJs unit testing
Js unit testing
 
WebSockets Jump Start
WebSockets Jump StartWebSockets Jump Start
WebSockets Jump Start
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
MozTW 離線報
MozTW 離線報MozTW 離線報
MozTW 離線報
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
HTML5 - The 2012 of the Web - Adobe MAX
HTML5 - The 2012 of the Web - Adobe MAXHTML5 - The 2012 of the Web - Adobe MAX
HTML5 - The 2012 of the Web - Adobe MAX
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Javascript dom event
Javascript dom eventJavascript dom event
Javascript dom event
 
The Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event HandlingThe Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event Handling
 
Knockout js session
Knockout js sessionKnockout js session
Knockout js session
 
Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
 
Cross-Platform Desktop Apps with JavaScript
Cross-Platform Desktop Apps with JavaScriptCross-Platform Desktop Apps with JavaScript
Cross-Platform Desktop Apps with JavaScript
 

En vedette

Social Media in Teaching and Learning
Social Media in Teaching and LearningSocial Media in Teaching and Learning
Social Media in Teaching and Learningsociamigo
 
Presentazione iniziale - Parole chiave - Idee - Brevetti esistenti
Presentazione iniziale - Parole chiave - Idee - Brevetti esistentiPresentazione iniziale - Parole chiave - Idee - Brevetti esistenti
Presentazione iniziale - Parole chiave - Idee - Brevetti esistentiA.C.M.E. Devise
 
6-month new associate review
6-month new associate review6-month new associate review
6-month new associate reviewApril Clements
 
Plow Through Your Winter Problems-CA
Plow Through Your Winter Problems-CAPlow Through Your Winter Problems-CA
Plow Through Your Winter Problems-CADGCommunications
 
Молодая гвардия
Молодая гвардияМолодая гвардия
Молодая гвардияpnextorg
 
Textual Analysis of Double Page Spread 1
Textual Analysis of Double Page Spread 1Textual Analysis of Double Page Spread 1
Textual Analysis of Double Page Spread 1Dylan0akes
 
Esseen palautus
Esseen palautusEsseen palautus
Esseen palautusHooKooM
 
Наш герой - Птушкин Валерий Васильевич
Наш герой - Птушкин Валерий ВасильевичНаш герой - Птушкин Валерий Васильевич
Наш герой - Птушкин Валерий Васильевичpnextorg
 
Plow Through Your Winter Problems
Plow Through Your Winter ProblemsPlow Through Your Winter Problems
Plow Through Your Winter ProblemsDGCommunications
 
Illuminate Your Landscape with Lighting | Tips from The Grounds Guys®
Illuminate Your Landscape with Lighting | Tips from The Grounds Guys®Illuminate Your Landscape with Lighting | Tips from The Grounds Guys®
Illuminate Your Landscape with Lighting | Tips from The Grounds Guys®DGCommunications
 
Женщина и война
Женщина и войнаЖенщина и война
Женщина и войнаpnextorg
 
Perkasa Karya - Katalog
Perkasa Karya - KatalogPerkasa Karya - Katalog
Perkasa Karya - KatalogPerkasa Karya
 

En vedette (15)

Social Media in Teaching and Learning
Social Media in Teaching and LearningSocial Media in Teaching and Learning
Social Media in Teaching and Learning
 
Presentazione iniziale - Parole chiave - Idee - Brevetti esistenti
Presentazione iniziale - Parole chiave - Idee - Brevetti esistentiPresentazione iniziale - Parole chiave - Idee - Brevetti esistenti
Presentazione iniziale - Parole chiave - Idee - Brevetti esistenti
 
6-month new associate review
6-month new associate review6-month new associate review
6-month new associate review
 
Plow Through Your Winter Problems-CA
Plow Through Your Winter Problems-CAPlow Through Your Winter Problems-CA
Plow Through Your Winter Problems-CA
 
Молодая гвардия
Молодая гвардияМолодая гвардия
Молодая гвардия
 
Question 2
Question 2Question 2
Question 2
 
Textual Analysis of Double Page Spread 1
Textual Analysis of Double Page Spread 1Textual Analysis of Double Page Spread 1
Textual Analysis of Double Page Spread 1
 
Esseen palautus
Esseen palautusEsseen palautus
Esseen palautus
 
Наш герой - Птушкин Валерий Васильевич
Наш герой - Птушкин Валерий ВасильевичНаш герой - Птушкин Валерий Васильевич
Наш герой - Птушкин Валерий Васильевич
 
Plow Through Your Winter Problems
Plow Through Your Winter ProblemsPlow Through Your Winter Problems
Plow Through Your Winter Problems
 
Illuminate Your Landscape with Lighting | Tips from The Grounds Guys®
Illuminate Your Landscape with Lighting | Tips from The Grounds Guys®Illuminate Your Landscape with Lighting | Tips from The Grounds Guys®
Illuminate Your Landscape with Lighting | Tips from The Grounds Guys®
 
Tragedi trisakti
Tragedi trisaktiTragedi trisakti
Tragedi trisakti
 
Женщина и война
Женщина и войнаЖенщина и война
Женщина и война
 
00. pti introduction
00. pti   introduction00. pti   introduction
00. pti introduction
 
Perkasa Karya - Katalog
Perkasa Karya - KatalogPerkasa Karya - Katalog
Perkasa Karya - Katalog
 

Similaire à The art of Building Bridges for Android Hybrid Apps

Gdg dev fest hybrid apps your own mini-cordova
Gdg dev fest hybrid apps  your own mini-cordovaGdg dev fest hybrid apps  your own mini-cordova
Gdg dev fest hybrid apps your own mini-cordovaAyman Mahfouz
 
Hybrid apps: Java conversing with JavaScript
Hybrid apps: Java  conversing with  JavaScriptHybrid apps: Java  conversing with  JavaScript
Hybrid apps: Java conversing with JavaScriptAyman Mahfouz
 
Custom HTML5-Native Bridge for Android
Custom HTML5-Native Bridge for AndroidCustom HTML5-Native Bridge for Android
Custom HTML5-Native Bridge for Androidmhant
 
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitJava Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitIMC Institute
 
The WebView Role in Hybrid Applications
The WebView Role in Hybrid ApplicationsThe WebView Role in Hybrid Applications
The WebView Role in Hybrid ApplicationsHaim Michael
 
Hybrid App using WordPress
Hybrid App using WordPressHybrid App using WordPress
Hybrid App using WordPressHaim Michael
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CNjojule
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...PROIDEA
 
Qt & Webkit
Qt & WebkitQt & Webkit
Qt & WebkitQT-day
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Robert DeLuca
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication developmentGanesh Gembali
 

Similaire à The art of Building Bridges for Android Hybrid Apps (20)

Gdg dev fest hybrid apps your own mini-cordova
Gdg dev fest hybrid apps  your own mini-cordovaGdg dev fest hybrid apps  your own mini-cordova
Gdg dev fest hybrid apps your own mini-cordova
 
React native by example by Vadim Ruban
React native by example by Vadim RubanReact native by example by Vadim Ruban
React native by example by Vadim Ruban
 
Hybrid apps: Java conversing with JavaScript
Hybrid apps: Java  conversing with  JavaScriptHybrid apps: Java  conversing with  JavaScript
Hybrid apps: Java conversing with JavaScript
 
Custom HTML5-Native Bridge for Android
Custom HTML5-Native Bridge for AndroidCustom HTML5-Native Bridge for Android
Custom HTML5-Native Bridge for Android
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
Mlocjs buzdin
Mlocjs buzdinMlocjs buzdin
Mlocjs buzdin
 
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitJava Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
 
GWT
GWTGWT
GWT
 
The WebView Role in Hybrid Applications
The WebView Role in Hybrid ApplicationsThe WebView Role in Hybrid Applications
The WebView Role in Hybrid Applications
 
Hybrid App using WordPress
Hybrid App using WordPressHybrid App using WordPress
Hybrid App using WordPress
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CN
 
handout-05b
handout-05bhandout-05b
handout-05b
 
handout-05b
handout-05bhandout-05b
handout-05b
 
Vaadin & Web Components
Vaadin & Web ComponentsVaadin & Web Components
Vaadin & Web Components
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
Qt & Webkit
Qt & WebkitQt & Webkit
Qt & Webkit
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication development
 
Hybrid app
Hybrid appHybrid app
Hybrid app
 

The art of Building Bridges for Android Hybrid Apps

  • 1. The  Art  of  Building  Bridges Android  WebView  Bridge  in  Depth Bartłomiej  Pisulak
  • 2. Three  types  of  Mobile  Apps
  • 3. Market  Share According  to  Gartner  more  than  50%  of  mobile  apps  deployed  will  be  hybrid
  • 4. Architecture It’s  all  about  WebView… So  what’s  the  difference?
  • 5. The  Bridge Bridge  between  Native  and  JS JS  -­‐>  Native   Native  -­‐>  JS
  • 6. JS_Object
 JavaScript  -­‐>  Java public class WebAppInterface { Context mContext; /** Instantiate the interface and set the context */ WebAppInterface(Context c) { mContext = c; } /** Show a toast from the web page */ @JavascriptInterface public void showToast(String toast) { Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); } } Let’s  build  an  interface:
  • 7. JS_Object
 JavaScript  -­‐>  Java JS WebView Quite  good  performance   Use  native  bridging  suggested  by  Google   Error  prone <script type="text/javascript"> function showAndroidToast(toast) { Android.showToast(toast); } </script> WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); webView.addJavascriptInterface(new WebAppInterface(this), "Android");
  • 8. Prompt
 JavaScript  -­‐>  Java JS WebChromeClient Doesn’t  crash  the  emulator   It’s  very  slow   Overrides  default  prompt  behaviour  in  WebView   Criticised  as  antipattern <script type="text/javascript"> prompt("toast", "This is Toast message"); </script> @Override public boolean onJsPrompt (WebView view, String url, String message, String defaultValue, JsPromptResult result) { // message determines action if(message == "toast") { // make toast ... } }
  • 9. loadUrl()
 Java  -­‐>  JavaScript   Native JS Quite  fast   Breaks  inputs  behaviour <script type="text/javascript"> onLocationUpdate(int lat, int lng) { alert("Success: lat=" + lat + " lng: " + lng); } </script> @Override public void onLocationChanged(Location location) { String lat = Double.toString(location.getLatitude()); String lng = Double.toString(location.getLongitude()); webView.loadUrl("javascript:onLocationUpda te(" + lat + "," + lng + ");"); }
  • 10. Online  Event
 Java  -­‐>  JavaScript   Native JS It’s  fast   Even  faster  than  loadUrl()   Doesn’t  break  anything  (yet)   Problem  in  case  of  bridging  more  than  one  WebView <script type="text/javascript"> var handleEvent = function() { // get result from native code // using exposed interface } window.addEventListener("online", handleEvent); window.addEventListener("offline", handleEvent); </script> boolean flipFlop; // (...) @Override public void informJavaScriptAboutResult() { flipFlop = !flipFlop; webView.setNetworkAvailable(flipFlop); }
  • 11. Private  API
 Java  -­‐>  JavaScript   Class webViewClass = WebView.class; try { Field f = webViewClass.getDeclaredField("mProvider"); f.setAccessible(true); webViewObject = f.get(webView); webViewClass = webViewObject.getClass(); } catch (Throwable e) { // ... } try { Field f = webViewClass.getDeclaredField("mWebViewCore"); f.setAccessible(true); webViewCore = f.get(webViewObject); if (webViewCore != null) { sendMessageMethod = webViewCore.getClass().getDeclaredMethod("sendMessage", Message.class); sendMessageMethod.setAccessible(true); } } catch (Throwable e) { // ... } Be  careful  while  using  reflection…
  • 12. Private  API
 Java  -­‐>  JavaScript   Native JS Super  fast   Not  supported  officially   Works  on  Android  3.2+   May  break  in  the  future <script type="text/javascript"> onLocationUpdate(int lat, int lng) { alert("Success: lat=" + lat + " lng: " + lng); } </script> try { String js = "onLocationUpdate(" + lat + "," + lng + ");"; Message execJsMessage = Message.obtain(null, EXECUTE_JS, js); sendMessageMethod.invoke(webViewCore, execJsMessage); } catch (Throwable e) { // ... }
  • 13. To  Sum  Up Hybrid  is  the  future Choose  proper  bridge
  • 14. QA Bartłomiej  Pisulak   Software  Engineer  |  IT  Trainer   http://www.pisulak.pl/