SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
Advantages and limitations of PhoneGap
for sensor processing
Gabor Paller
gaborpaller@gmail.com
Sfonge Ltd.
http://www.sfonge.com
Alternative application models for
Android
● Basic Android application model → Java-based
● Well-hidden in the Android Native Development
Kit (NDK) → there is a native application model
too
● Application models based on other languages
have been proposed but have been rarely
deployed
Browser as mobile application
runtime
● Browser is already acting as mobile application runtime
● Just check out the zillions of “how to optimize your website for
mobile” articles
● There were some efforts to make the web application
model the main application model on other platforms
→ Bada, Tizen (both very silent recently)
→ Firefox OS is making headlines now.
● Meanwhile, a modest tool adopted the web model widely
and is in production: PhoneGap
From the helicopter
● With PhoneGap, you create traditional, installable applications
● PhoneGap does not change the operating system in any way, it acts like
a library embedded into the application
● A PhoneGap application is implemented mainly in web technologies:
HTML, JavaScript, JQuery
● Promises:
● Lower the cost of mobile development by employing millions of web programmers
● Improve the portability of applications by making the web model the greatest
common denominator (which it is for web sites)
Test programs mentioned in this presentation are available here:
http://www.sfonge.com/forum/topic/
droidcon-tunis-2013-presentation-advantages-and-limitations-phonegap-sensor-processing-t
White paper that this presentation is based on is available here:
http://www.sfonge.com/epaper/
performance-context-aware-algorithms-implemented-web-technologies
(Both require free registration to Sfonge site)
PhoneGap project
Displayed first
This directory is our playground
PhoneGap library
index.html
Main stylesheet in
css subdirectory
Main page starts here
Loads PhoneGap
Loads application-specific
code
Invokes application-specific
initialization
index.js
● Application initialization:
var app = {
initialize: function() {
...
},
● First listen to onDeviceReady events:
var self = this;
document.addEventListener('deviceready', self.onDeviceReady, false);
● Start invoking PhoneGap functions after the onDeviceReady
event was fired:
onDeviceReady: function() {
...
},
index.js (2)
●
In onDeviceReady, initialize your UI ...
var shakes = document.getElementById("shakes");
app.shakeCounter = 0;
shakes.innerHTML = app.shakeCounter.toString();
● … start listening for lifecycle events ...
document.addEventListener('pause', app.onPause, false);
document.addEventListener('resume', app.onResume, false);
● … and device events (sensor, in our case)
this.accelerometerWatchID = navigator.accelerometer.watchAcceleration(
this.onSuccess,
this.onError,
{ frequency: 50 });
index.js (3)
● And then you can handle sensor events:
onSuccess: function(acceleration) {
var currentTimeStamp = acceleration.timestamp;
var x = acceleration.x;
var y = acceleration.y;
var z = acceleration.z;
…
}
Brief interlude on context-aware applications
Context-aware applications
● Context-aware applications are characterized
by their capability of adapting to changes in
their environment.
● More precisely:
● Capture environmental changes
● Decide whether the change is relevant enough to
adapt
● Adapt the behavior if the change is relevant
Architecture: sensor adapters
● Sensor adapters
● Process the input from probes in the environment
● Simple: listener to operating system events
● Complicated: signal-processing algorithm for a built-
in gyroscope sensor
Architecture: decision logic
● Decision logic
● Rule engine that works on sensor adapter outputs
and produces application adaptation decisions
● Simple: a set of “if” statements
● Complicated: rule inference engine.
Architecture: adaptation logic
● Adaptation logic
● Makes sure that the high-level context variables
produced by the decision logic affect the application
logic in an application-specific way.
● Simple: set of “if” statements built into the
application logic
● Complicated: dynamic component system
Consequence of the application
model
● If the sensor adapter processing is offloaded to
specialized co-processors or native code, the
application model has no impact (no special
processing requirements)
● If the application code includes sensor adapter
processing then the application model better
provide efficient execution because sensor
processing may be CPU-intensive
Example application
● Very simple shake detector
● Based on the accelerometer input
● High-pass filtering to remove effects of slow
motions, e.g. walking
● Peak detector to extract shake signal
● “Application adaptation”: simply count
Recap: gravity and motion
acceleration
Recap: Absolute value
● x, y, z: acceleration vector components
● g – value of the gravity acceleration (can be
approximated as 10)
a=√x2
+ y2
+ z2
−g
5 shakes
Movement
starts:
accelerating
Direction reverses
Final deceleration
Recap: Separating movements in
the frequency domain
Hz
Walking Shaking
Walking
Walking+shaking
64-point Fast Fourier Transform performed at samples 50 and 200
Applying the filter
4 shakes can be reliably recognized
Filter in our example
● 6th-order IIR filter
(N=6, 12 additions
and 12 multiplications
per sample)
yn=∑
i=0
N
ai xn−i−∑
i=1
N
bi yn−i
Measurement
● Two implementations: Java and web
technology (PhoneGap).
● Measurement:
● Phone is restarted
● Nexus S, about 50 Hz sampling rate
● App is started, sampling is started
● Wait 10 sec
● Connect with “adb shell” and launch the “top”
command
● Record the CPU% column
Results:
● CPU consumption:
● Java implementation: 1%
● PhoneGap implementation: 9%
● Battery consumption:
● PhoneGap : 0.1218%/min → 7.3 %/hour → about 13
hours of battery life
● Java: 0.072%/min →4.32%/hour → about 23 hours of
battery life
● 60% more consumption, 40% less battery life
PhoneGap “plugins”
● PhoneGap is built on the plugin concept
● Its own services are also built as plugins and
you can define your own
● Plugins are implemented as whatever is “native”
in the environment, in case of Android in Java
PhoneGap plugin
● Plugin class:
public class SamplingServiceAdapter extends CordovaPlugin {
…
}
● Plugin commands:
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
if (action.equals("start")) {
…
}
● Register your plugin in res/xml/config.xml
<plugin name="Shake" value="aexp.simpleshakejsplugin.SamplingServiceAdapter"/>
Callbacks
● Use CallbackContext to initiate a callback:
PluginResult result = new PluginResult(PluginResult.Status.OK,
this.getStepCountJSON(count));
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
● The result must be in JSON:
JSONObject r = new JSONObject();
r.put("count", count);
● Which conforms in JSON to:
{ count: 2 }
From the JS side
● Sending a command from JS:
cordova.exec(this.onShake,this.onError,"Shake","start",[]);
● Receiving a callback from native:
onShake: function(s) {
var count = s.count; // Remember the JSON format we generate!
…
}
Plugin result
● With plugin implementation, the CPU load is
comparable to native implementation (about
1%, within measurement error)
● No surprise here: if you check the code, you will
see that “CPU-intensive” tasks are implemented
similarly to the Java version.
So what about the “web model”?
● Web model is great for some types of applications (if
you have the competence)
● These are typically UI-intensive applications when some
data is presented to the user and we are then expecting
user interaction
● Try to handle moderately “CPU-intensive” tasks in
the web model and you will be in for an unpleasant
surprise
● CPU load is directly translated to battery life and I haven't
even talked about memory footprint
My advice
● If you are an experienced web developer, go for
the web model and implement your apps in the
web model, you will have quick success
● Always consider, whether you have “CPU-
intensive” tasks – those that happen often and
require non-trivial calculations
● When you are considering a web application
platform, always look for native extension
possibility, just in case. If there is none, beware.
Questions?

Contenu connexe

En vedette

En vedette (20)

Connect your Android to the real world with Bluetooth Low Energy
Connect your Android to the real world with Bluetooth Low EnergyConnect your Android to the real world with Bluetooth Low Energy
Connect your Android to the real world with Bluetooth Low Energy
 
Sensor fusion between car and smartphone
Sensor fusion between car and smartphoneSensor fusion between car and smartphone
Sensor fusion between car and smartphone
 
Better motion control using accelerometer/gyroscope sensor fusion
Better motion control using accelerometer/gyroscope sensor fusionBetter motion control using accelerometer/gyroscope sensor fusion
Better motion control using accelerometer/gyroscope sensor fusion
 
Interfacing BLE with android based device
Interfacing BLE with android based device  Interfacing BLE with android based device
Interfacing BLE with android based device
 
R U aBLE? BLE Application Hacking
R U aBLE? BLE Application HackingR U aBLE? BLE Application Hacking
R U aBLE? BLE Application Hacking
 
Bluetooth android application For interfacing with arduino
Bluetooth android application For interfacing with arduinoBluetooth android application For interfacing with arduino
Bluetooth android application For interfacing with arduino
 
Android Gadgets, Bluetooth Low Energy, and the WunderBar
Android Gadgets, Bluetooth Low Energy, and the WunderBarAndroid Gadgets, Bluetooth Low Energy, and the WunderBar
Android Gadgets, Bluetooth Low Energy, and the WunderBar
 
Wearable Device (Bluetooth Low Energy BLE ) connect with Android
Wearable Device (Bluetooth Low Energy BLE ) connect with  AndroidWearable Device (Bluetooth Low Energy BLE ) connect with  Android
Wearable Device (Bluetooth Low Energy BLE ) connect with Android
 
Android bluetooth
Android bluetoothAndroid bluetooth
Android bluetooth
 
Android mobile phone controlled bluetooth robot
Android mobile phone controlled bluetooth robotAndroid mobile phone controlled bluetooth robot
Android mobile phone controlled bluetooth robot
 
BLE Talk
BLE TalkBLE Talk
BLE Talk
 
BTLE (Bluetooth Low Energy) and CoreBluetooth
BTLE (Bluetooth Low Energy) and CoreBluetooth BTLE (Bluetooth Low Energy) and CoreBluetooth
BTLE (Bluetooth Low Energy) and CoreBluetooth
 
Gcm tutorial
Gcm tutorialGcm tutorial
Gcm tutorial
 
Motion recognition with Android devices
Motion recognition with Android devicesMotion recognition with Android devices
Motion recognition with Android devices
 
Java project-presentation
Java project-presentationJava project-presentation
Java project-presentation
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
BLUETOOTH CONTROL ROBOT WITH ANDROID APPLICATION
BLUETOOTH CONTROL ROBOT WITH ANDROID APPLICATIONBLUETOOTH CONTROL ROBOT WITH ANDROID APPLICATION
BLUETOOTH CONTROL ROBOT WITH ANDROID APPLICATION
 
Bluetooth Low Energy - A Case Study
Bluetooth Low Energy - A Case StudyBluetooth Low Energy - A Case Study
Bluetooth Low Energy - A Case Study
 
Android Bluetooth Introduction
Android Bluetooth IntroductionAndroid Bluetooth Introduction
Android Bluetooth Introduction
 
Android presentation slide
Android presentation slideAndroid presentation slide
Android presentation slide
 

Similaire à Advantages and limitations of PhoneGap for sensor processing

Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
Yekmer Simsek
 
Gatling - Bordeaux JUG
Gatling - Bordeaux JUGGatling - Bordeaux JUG
Gatling - Bordeaux JUG
slandelle
 

Similaire à Advantages and limitations of PhoneGap for sensor processing (20)

Kogito: cloud native business automation
Kogito: cloud native business automationKogito: cloud native business automation
Kogito: cloud native business automation
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of Signals
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
Android 5.0 internals and inferiority complex droidcon.de 2015
Android 5.0 internals and inferiority complex droidcon.de 2015Android 5.0 internals and inferiority complex droidcon.de 2015
Android 5.0 internals and inferiority complex droidcon.de 2015
 
PhoneGap
PhoneGapPhoneGap
PhoneGap
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Mobile optimization
Mobile optimizationMobile optimization
Mobile optimization
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "
 
Android Pro Recipes
Android Pro RecipesAndroid Pro Recipes
Android Pro Recipes
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Angular Js Basics
Angular Js BasicsAngular Js Basics
Angular Js Basics
 
Advanced android app development
Advanced android app developmentAdvanced android app development
Advanced android app development
 
Slide Deck - Shift Left Beyond App Performance Improvement at Gojek_.pptx
Slide Deck - Shift Left Beyond App Performance Improvement at Gojek_.pptxSlide Deck - Shift Left Beyond App Performance Improvement at Gojek_.pptx
Slide Deck - Shift Left Beyond App Performance Improvement at Gojek_.pptx
 
Introduction to Jhipster
Introduction to JhipsterIntroduction to Jhipster
Introduction to Jhipster
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
 
Gatling - Bordeaux JUG
Gatling - Bordeaux JUGGatling - Bordeaux JUG
Gatling - Bordeaux JUG
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Node
NodeNode
Node
 
End to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaEnd to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux Saga
 

Plus de Gabor Paller

Plus de Gabor Paller (8)

Towards a floating plastic waste early warning system
Towards a floating plastic waste early warning systemTowards a floating plastic waste early warning system
Towards a floating plastic waste early warning system
 
Dataflow-based heterogeneous code generator for IoT applications
Dataflow-based heterogeneous code generator for IoT applicationsDataflow-based heterogeneous code generator for IoT applications
Dataflow-based heterogeneous code generator for IoT applications
 
Sigfox szenzorfejlesztéssel kapcsolatos tapasztalatok
Sigfox szenzorfejlesztéssel kapcsolatos tapasztalatokSigfox szenzorfejlesztéssel kapcsolatos tapasztalatok
Sigfox szenzorfejlesztéssel kapcsolatos tapasztalatok
 
Energy-efficient operation of GSM-connected infrared rodent sensors
Energy-efficient operation of GSM-connected infrared rodent sensorsEnergy-efficient operation of GSM-connected infrared rodent sensors
Energy-efficient operation of GSM-connected infrared rodent sensors
 
AgroDat poster at Sensornets 2015 conference
AgroDat poster at Sensornets 2015 conferenceAgroDat poster at Sensornets 2015 conference
AgroDat poster at Sensornets 2015 conference
 
LiveFolders as feeds
LiveFolders as feedsLiveFolders as feeds
LiveFolders as feeds
 
Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer tool
 
The dedexer disassembler
The dedexer disassemblerThe dedexer disassembler
The dedexer disassembler
 

Dernier

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Dernier (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

Advantages and limitations of PhoneGap for sensor processing

  • 1. Advantages and limitations of PhoneGap for sensor processing Gabor Paller gaborpaller@gmail.com Sfonge Ltd. http://www.sfonge.com
  • 2. Alternative application models for Android ● Basic Android application model → Java-based ● Well-hidden in the Android Native Development Kit (NDK) → there is a native application model too ● Application models based on other languages have been proposed but have been rarely deployed
  • 3. Browser as mobile application runtime ● Browser is already acting as mobile application runtime ● Just check out the zillions of “how to optimize your website for mobile” articles ● There were some efforts to make the web application model the main application model on other platforms → Bada, Tizen (both very silent recently) → Firefox OS is making headlines now. ● Meanwhile, a modest tool adopted the web model widely and is in production: PhoneGap
  • 4. From the helicopter ● With PhoneGap, you create traditional, installable applications ● PhoneGap does not change the operating system in any way, it acts like a library embedded into the application ● A PhoneGap application is implemented mainly in web technologies: HTML, JavaScript, JQuery ● Promises: ● Lower the cost of mobile development by employing millions of web programmers ● Improve the portability of applications by making the web model the greatest common denominator (which it is for web sites)
  • 5. Test programs mentioned in this presentation are available here: http://www.sfonge.com/forum/topic/ droidcon-tunis-2013-presentation-advantages-and-limitations-phonegap-sensor-processing-t White paper that this presentation is based on is available here: http://www.sfonge.com/epaper/ performance-context-aware-algorithms-implemented-web-technologies (Both require free registration to Sfonge site)
  • 6. PhoneGap project Displayed first This directory is our playground PhoneGap library
  • 7. index.html Main stylesheet in css subdirectory Main page starts here Loads PhoneGap Loads application-specific code Invokes application-specific initialization
  • 8. index.js ● Application initialization: var app = { initialize: function() { ... }, ● First listen to onDeviceReady events: var self = this; document.addEventListener('deviceready', self.onDeviceReady, false); ● Start invoking PhoneGap functions after the onDeviceReady event was fired: onDeviceReady: function() { ... },
  • 9. index.js (2) ● In onDeviceReady, initialize your UI ... var shakes = document.getElementById("shakes"); app.shakeCounter = 0; shakes.innerHTML = app.shakeCounter.toString(); ● … start listening for lifecycle events ... document.addEventListener('pause', app.onPause, false); document.addEventListener('resume', app.onResume, false); ● … and device events (sensor, in our case) this.accelerometerWatchID = navigator.accelerometer.watchAcceleration( this.onSuccess, this.onError, { frequency: 50 });
  • 10. index.js (3) ● And then you can handle sensor events: onSuccess: function(acceleration) { var currentTimeStamp = acceleration.timestamp; var x = acceleration.x; var y = acceleration.y; var z = acceleration.z; … }
  • 11. Brief interlude on context-aware applications
  • 12. Context-aware applications ● Context-aware applications are characterized by their capability of adapting to changes in their environment. ● More precisely: ● Capture environmental changes ● Decide whether the change is relevant enough to adapt ● Adapt the behavior if the change is relevant
  • 13. Architecture: sensor adapters ● Sensor adapters ● Process the input from probes in the environment ● Simple: listener to operating system events ● Complicated: signal-processing algorithm for a built- in gyroscope sensor
  • 14. Architecture: decision logic ● Decision logic ● Rule engine that works on sensor adapter outputs and produces application adaptation decisions ● Simple: a set of “if” statements ● Complicated: rule inference engine.
  • 15. Architecture: adaptation logic ● Adaptation logic ● Makes sure that the high-level context variables produced by the decision logic affect the application logic in an application-specific way. ● Simple: set of “if” statements built into the application logic ● Complicated: dynamic component system
  • 16. Consequence of the application model ● If the sensor adapter processing is offloaded to specialized co-processors or native code, the application model has no impact (no special processing requirements) ● If the application code includes sensor adapter processing then the application model better provide efficient execution because sensor processing may be CPU-intensive
  • 17. Example application ● Very simple shake detector ● Based on the accelerometer input ● High-pass filtering to remove effects of slow motions, e.g. walking ● Peak detector to extract shake signal ● “Application adaptation”: simply count
  • 18. Recap: gravity and motion acceleration
  • 19. Recap: Absolute value ● x, y, z: acceleration vector components ● g – value of the gravity acceleration (can be approximated as 10) a=√x2 + y2 + z2 −g
  • 21. Recap: Separating movements in the frequency domain Hz Walking Shaking Walking Walking+shaking 64-point Fast Fourier Transform performed at samples 50 and 200
  • 22. Applying the filter 4 shakes can be reliably recognized
  • 23. Filter in our example ● 6th-order IIR filter (N=6, 12 additions and 12 multiplications per sample) yn=∑ i=0 N ai xn−i−∑ i=1 N bi yn−i
  • 24. Measurement ● Two implementations: Java and web technology (PhoneGap). ● Measurement: ● Phone is restarted ● Nexus S, about 50 Hz sampling rate ● App is started, sampling is started ● Wait 10 sec ● Connect with “adb shell” and launch the “top” command ● Record the CPU% column
  • 25. Results: ● CPU consumption: ● Java implementation: 1% ● PhoneGap implementation: 9% ● Battery consumption: ● PhoneGap : 0.1218%/min → 7.3 %/hour → about 13 hours of battery life ● Java: 0.072%/min →4.32%/hour → about 23 hours of battery life ● 60% more consumption, 40% less battery life
  • 26. PhoneGap “plugins” ● PhoneGap is built on the plugin concept ● Its own services are also built as plugins and you can define your own ● Plugins are implemented as whatever is “native” in the environment, in case of Android in Java
  • 27. PhoneGap plugin ● Plugin class: public class SamplingServiceAdapter extends CordovaPlugin { … } ● Plugin commands: public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { if (action.equals("start")) { … } ● Register your plugin in res/xml/config.xml <plugin name="Shake" value="aexp.simpleshakejsplugin.SamplingServiceAdapter"/>
  • 28. Callbacks ● Use CallbackContext to initiate a callback: PluginResult result = new PluginResult(PluginResult.Status.OK, this.getStepCountJSON(count)); result.setKeepCallback(true); callbackContext.sendPluginResult(result); ● The result must be in JSON: JSONObject r = new JSONObject(); r.put("count", count); ● Which conforms in JSON to: { count: 2 }
  • 29. From the JS side ● Sending a command from JS: cordova.exec(this.onShake,this.onError,"Shake","start",[]); ● Receiving a callback from native: onShake: function(s) { var count = s.count; // Remember the JSON format we generate! … }
  • 30. Plugin result ● With plugin implementation, the CPU load is comparable to native implementation (about 1%, within measurement error) ● No surprise here: if you check the code, you will see that “CPU-intensive” tasks are implemented similarly to the Java version.
  • 31. So what about the “web model”? ● Web model is great for some types of applications (if you have the competence) ● These are typically UI-intensive applications when some data is presented to the user and we are then expecting user interaction ● Try to handle moderately “CPU-intensive” tasks in the web model and you will be in for an unpleasant surprise ● CPU load is directly translated to battery life and I haven't even talked about memory footprint
  • 32. My advice ● If you are an experienced web developer, go for the web model and implement your apps in the web model, you will have quick success ● Always consider, whether you have “CPU- intensive” tasks – those that happen often and require non-trivial calculations ● When you are considering a web application platform, always look for native extension possibility, just in case. If there is none, beware.