Commit 3922103d authored by Chris Scott's avatar Chris Scott

Initial commit

parent 4756a06c
This diff is collapsed.
Example Background GeoLocation app.
=============================================
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.transistorsoft.backgroundgeolocation" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>Cordova Background GeoLocation</name>
<description>
A minimal example of cordova BackgroundGeoLocation plugin.
</description>
<author email="chris@transistorsoft.com" href="http://transistorsoft.com">
Chris Scott -- Transistor Software
</author>
<content src="index.html" />
<access origin="*" />
</widget>
{
"images" : [
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x",
"filename" : "Icon-Small@2x.png"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x",
"filename" : "Icon-Small@3x.png"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x",
"filename" : "Icon-40@2x.png"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x",
"filename" : "Icon-40@3x.png"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x",
"filename" : "Icon-60@2x.png"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x",
"filename" : "Icon-60@3x.png"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x",
"filename" : "Icon-Small.png"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x",
"filename" : "Icon-Small@2x.png"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x",
"filename" : "Icon-40.png"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x",
"filename" : "Icon-40@2x.png"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x",
"filename" : "Icon-76.png"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x",
"filename" : "Icon-76@2x.png"
}
],
"info" : {
"version" : 1,
"author" : "makeappicon"
}
}
\ No newline at end of file
chris@transistorsoft.com
<!--
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
-->
# Cordova Hooks
Cordova Hooks represent special scripts which could be added by application and plugin developers or even by your own build system to customize cordova commands. Hook scripts could be defined by adding them to the special predefined folder (`/hooks`) or via configuration files (`config.xml` and `plugin.xml`) and run serially in the following order:
* Application hooks from `/hooks`;
* Application hooks from `config.xml`;
* Plugin hooks from `plugins/.../plugin.xml`.
__Remember__: Make your scripts executable.
__Note__: `.cordova/hooks` directory is also supported for backward compatibility, but we don't recommend using it as it is deprecated.
## Supported hook types
The following hook types are supported:
after_build/
after_compile/
after_docs/
after_emulate/
after_platform_add/
after_platform_rm/
after_platform_ls/
after_plugin_add/
after_plugin_ls/
after_plugin_rm/
after_plugin_search/
after_plugin_install/ <-- Plugin hooks defined in plugin.xml are executed exclusively for a plugin being installed
after_prepare/
after_run/
after_serve/
before_build/
before_compile/
before_docs/
before_emulate/
before_platform_add/
before_platform_rm/
before_platform_ls/
before_plugin_add/
before_plugin_ls/
before_plugin_rm/
before_plugin_search/
before_plugin_install/ <-- Plugin hooks defined in plugin.xml are executed exclusively for a plugin being installed
before_plugin_uninstall/ <-- Plugin hooks defined in plugin.xml are executed exclusively for a plugin being uninstalled
before_prepare/
before_run/
before_serve/
pre_package/ <-- Windows 8 and Windows Phone only.
## Ways to define hooks
### Via '/hooks' directory
To execute custom action when corresponding hook type is fired, use hook type as a name for a subfolder inside 'hooks' directory and place you script file here, for example:
# script file will be automatically executed after each build
hooks/after_build/after_build_custom_action.js
### Config.xml
Hooks can be defined in project's `config.xml` using `<hook>` elements, for example:
<hook type="before_build" src="scripts/appBeforeBuild.bat" />
<hook type="before_build" src="scripts/appBeforeBuild.js" />
<hook type="before_plugin_install" src="scripts/appBeforePluginInstall.js" />
<platform name="wp8">
<hook type="before_build" src="scripts/wp8/appWP8BeforeBuild.bat" />
<hook type="before_build" src="scripts/wp8/appWP8BeforeBuild.js" />
<hook type="before_plugin_install" src="scripts/wp8/appWP8BeforePluginInstall.js" />
...
</platform>
<platform name="windows8">
<hook type="before_build" src="scripts/windows8/appWin8BeforeBuild.bat" />
<hook type="before_build" src="scripts/windows8/appWin8BeforeBuild.js" />
<hook type="before_plugin_install" src="scripts/windows8/appWin8BeforePluginInstall.js" />
...
</platform>
### Plugin hooks (plugin.xml)
As a plugin developer you can define hook scripts using `<hook>` elements in a `plugin.xml` like that:
<hook type="before_plugin_install" src="scripts/beforeInstall.js" />
<hook type="after_build" src="scripts/afterBuild.js" />
<platform name="wp8">
<hook type="before_plugin_install" src="scripts/wp8BeforeInstall.js" />
<hook type="before_build" src="scripts/wp8BeforeBuild.js" />
...
</platform>
`before_plugin_install`, `after_plugin_install`, `before_plugin_uninstall` plugin hooks will be fired exclusively for the plugin being installed/uninstalled.
## Script Interface
### Javascript
If you are writing hooks in Javascript you should use the following module definition:
```javascript
module.exports = function(context) {
...
}
```
You can make your scipts async using Q:
```javascript
module.exports = function(context) {
var Q = context.requireCordovaModule('q');
var deferral = new Q.defer();
setTimeout(function(){
console.log('hook.js>> end');
deferral.resolve();
}, 1000);
return deferral.promise;
}
```
`context` object contains hook type, executed script full path, hook options, command-line arguments passed to Cordova and top-level "cordova" object:
```json
{
"hook": "before_plugin_install",
"scriptLocation": "c:\\script\\full\\path\\appBeforePluginInstall.js",
"cmdLine": "The\\exact\\command\\cordova\\run\\with arguments",
"opts": {
"projectRoot":"C:\\path\\to\\the\\project",
"cordova": {
"platforms": ["wp8"],
"plugins": ["com.plugin.withhooks"],
"version": "0.21.7-dev"
},
"plugin": {
"id": "com.plugin.withhooks",
"pluginInfo": {
...
},
"platform": "wp8",
"dir": "C:\\path\\to\\the\\project\\plugins\\com.plugin.withhooks"
}
},
"cordova": {...}
}
```
`context.opts.plugin` object will only be passed to plugin hooks scripts.
You can also require additional Cordova modules in your script using `context.requireCordovaModule` in the following way:
```javascript
var Q = context.requireCordovaModule('q');
```
__Note__: new module loader script interface is used for the `.js` files defined via `config.xml` or `plugin.xml` only.
For compatibility reasons hook files specified via `/hooks` folders are run via Node child_process spawn, see 'Non-javascript' section below.
### Non-javascript
Non-javascript scripts are run via Node child_process spawn from the project's root directory and have the root directory passes as the first argument. All other options are passed to the script using environment variables:
* CORDOVA_VERSION - The version of the Cordova-CLI.
* CORDOVA_PLATFORMS - Comma separated list of platforms that the command applies to (e.g.: android, ios).
* CORDOVA_PLUGINS - Comma separated list of plugin IDs that the command applies to (e.g.: org.apache.cordova.file, org.apache.cordova.file-transfer)
* CORDOVA_HOOK - Path to the hook that is being executed.
* CORDOVA_CMDLINE - The exact command-line arguments passed to cordova (e.g.: cordova run ios --emulate)
If a script returns a non-zero exit code, then the parent cordova command will be aborted.
## Writing hooks
We highly recommend writting your hooks using Node.js so that they are
cross-platform. Some good examples are shown here:
[http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/](http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/)
Also, note that even if you are working on Windows, and in case your hook scripts aren't bat files (which is recommended, if you want your scripts to work in non-Windows operating systems) Cordova CLI will expect a shebang line as the first line for it to know the interpreter it needs to use to launch the script. The shebang line should match the following example:
#!/usr/bin/env [name_of_interpreter_executable]
#!/usr/bin/env node
var platformDir = {
ios: {
icon: "{$projectName}/Resources/icons",
screen: "{$projectName}/Resources/splash",
nameMap: {
"Icon.png": "Icon.png",
"Icon@2x.png": "Icon@2x.png",
"Icon-40.png": "Icon-40.png",
"Icon-40@2x.png": "Icon-40@2x.png",
"Icon-60.png":"Icon-60.png",
"Icon-60@2x.png":"Icon-60@2x.png",
"Icon-Small-50.png":"Icon-50.png",
"Icon-Small-50@2x.png":"Icon-50@2x.png",
"Icon.png":"Icon.png",
"Icon@2x.png":"Icon@2x.png",
"Icon-72.png":"Icon-72.png",
"Icon-72@2x.png": "Icon-72@2x.png",
"Icon-76.png":"Icon-76.png",
"Icon-76@2x.png": "Icon-76@2x.png",
"Icon-Small.png": "Icon-Small.png",
"Icon-Small@2x.png":"Icon-Small@2x.png",
"screen-iphone-portrait.png": "Default~iphone.png",
"screen-iphone-portrait@2x.png": "Default@2x~iphone.png",
"screen-iphone-portrait-568h@2x.png": "Default-568h@2x~iphone.png",
"Default-Portrait~ipad.png": "Default-Portrait~ipad.png",
"Default-Portrait@2x~ipad.png": "Default-Portrait@2x~ipad.png"
}
},
android: {
icon:"res/drawable-{$density}",
screen:"res/drawable-{$density}",
nameMap: {
"icon-36-ldpi.png": "icon.png",
"icon-48-mdpi.png": "icon.png",
"icon-72-hdpi.png": "icon.png",
"icon-96-xhdpi.png": "icon.png",
"screen-ldpi-portrait.png": "ic_launcher.png",
"screen-mdpi-portrait.png": "ic_launcher.png",
"screen-hdpi-portrait.png": "ic_launcher.png",
"screen-xhdpi-portrait.png": "ic_launcher.png"
}
},
blackberry10: {},
wp7: {},
wp8: {}
}
var projectName = process.env['PWD'].split('/').pop();
var fs = require ('fs');
var path = require('path');
var platform = process.env.CORDOVA_PLATFORMS;
var platformConfig = platformDir[platform];
var srcRoot = path.join(process.cwd(), 'config', 'res');
var iconSrcPath = path.join(srcRoot, 'icon', platform);
var screenSrcPath = path.join(srcRoot, 'screen', platform);
var destRoot = path.join('platforms', platform);
var iconDestPath = path.join(destRoot, platformDir[platform].icon);
var screenDestPath = path.join(destRoot, platformDir[platform].screen);
fs.readFile("./config.xml", function(err, data) {
if (err) {
throw err;
}
var m = data.toString().match(/<name>(.*)<\/name>/);
if (!m) {
throw "Resource Copier script could not determine proeject name";
}
projectName = m[1];
console.log("- Copying icons and screen", platform);
copyImages(iconSrcPath, iconDestPath, platformConfig.icon);
copyImages(screenSrcPath, screenDestPath, platformConfig.screen);
});
/**
* Copy Images
*/
function copyImages(srcPath, destTpl) {
var re = /-([a-zA-Z]+dpi)/;
fs.readdir(srcPath, function(err, rs) {
if (err) {
console.log('ERROR could not find image dir at ', srcPath);
return;
}
for (var n=0,len=rs.length;n<len;n++) {
var filename = rs[n];
if (!platformConfig.nameMap[filename]) {
continue;
}
var sourcePath = path.join(srcPath, filename);
var m = filename.match(re);
var density;
if (m) {
density = m[1];
}
var dict = {
projectName: projectName,
density: density
};
var destRoot = destTpl.replace (/{\$([^}]+)}/, function (match, p1) {
return dict[p1];
});
var sourceFile = path.join(srcPath, filename);
var targetFile = path.join(destRoot, platformConfig.nameMap[filename]);
console.log(filename, '->', targetFile);
copyFile(sourceFile, targetFile, function() {
});
}
});
}
/**
* copyFile
*/
function copyFile(source, target, cb) {
var cbCalled = false;
var rd = fs.createReadStream(source);
rd.on("error", function(err) {
done(err);
});
var wr = fs.createWriteStream(target);
wr.on("error", function(err) {
done(err);
});
wr.on("close", function(ex) {
done();
});
rd.pipe(wr);
function done(err) {
if (!cbCalled) {
cb(err);
cbCalled = true;
}
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
* {
-webkit-tap-highlight-color: rgba(0,0,0,0); /* make transparent link selection, adjust last value opacity 0 to 1.0 */
}
body {
-webkit-touch-callout: none; /* prevent callout to copy image, etc when tap to hold */
-webkit-text-size-adjust: none; /* prevent webkit from resizing text to fit */
-webkit-user-select: none; /* prevent copy paste, to allow, change 'none' to 'text' */
background-color:#E4E4E4;
background-image:linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
background-image:-webkit-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
background-image:-ms-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
background-image:-webkit-gradient(
linear,
left top,
left bottom,
color-stop(0, #A7A7A7),
color-stop(0.51, #E4E4E4)
);
background-attachment:fixed;
font-family:'HelveticaNeue-Light', 'HelveticaNeue', Helvetica, Arial, sans-serif;
font-size:12px;
height:100%;
margin:0px;
padding:0px;
width:100%;
}
/* Landscape layout (with min-width) */
@media screen and (min-aspect-ratio: 1/1) and (min-width:400px) {
.app {
background-position:left center;
padding:75px 0px 75px 170px; /* padding-top + padding-bottom + text area = image height */
margin:-90px 0px 0px -198px; /* offset vertical: half of image height */
/* offset horizontal: half of image width and text area width */
}
}
.header {
padding-top: 15px;
background-color: #fedd1e;
}
.header h3 {
text-transform:uppercase;
font-size:24px;
}
.header p, .header h3 {
font-weight:normal;
margin:0px;
overflow:visible;
padding:0px;
text-align:center;
}
.header p {
font-size: 1.3em;
}
#footer {
background-color: #fedd1e;
}
\ No newline at end of file
This diff is collapsed.
<!DOCTYPE html>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/bootstrap-min.css" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>BG GeoLocation</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=true&libraries=geometry">
</script>
</head>
<body>
<div id="header" class="header">
<h3>BG GeoLocation</h3>
<p>transistorsoft.com</p>
</div>
<div id="map-canvas"></div>
<nav id="footer" class="navbar navbar-default navbar-fixed-bottom" role="navigation">
<button id="btn-home" class="btn navbar-btn btn-default glyphicon glyphicon-screenshot"></button>
<button id="btn-reset" class="btn btn-default glyphicon">Reset</button>
<button id="btn-pace" data-id="false" class="btn navbar-btn">Aggressive</button>
<button id="btn-enabled" class="btn navbar-btn" data-id="true">Start</button>
</nav>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
This diff is collapsed.
This diff is collapsed.
<!DOCTYPE html>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
</head>
<body>
<div class="app">
<h1>PhoneGap</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
</div>
</div>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
if (window.plugins.backgroundGeoLocation) {
app.configureBackgroundGeoLocation();
}
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
},
configureBackgroundGeoLocation: function() {
// Your app must execute AT LEAST ONE call for the current position via standard Cordova geolocation,
// in order to prompt the user for Location permission.
window.navigator.geolocation.getCurrentPosition(function(location) {
console.log('Location from Phonegap');
});
var bgGeo = window.plugins.backgroundGeoLocation;
/**
* This would be your own callback for Ajax-requests after POSTing background geolocation to your server.
*/
var yourAjaxCallback = function(response) {
////
// IMPORTANT: You must execute the #finish method here to inform the native plugin that you're finished,
// and the background-task may be completed. You must do this regardless if your HTTP request is successful or not.
// IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
//
//
bgGeo.finish();
};
/**
* This callback will be executed every time a geolocation is recorded in the background.
*/
var callbackFn = function(location) {
console.log('[js] BackgroundGeoLocation callback: ' + location.latitudue + ',' + location.longitude);
// Do your HTTP request here to POST location to your server.
//
//
yourAjaxCallback.call(this);
};
var failureFn = function(error) {
console.log('BackgroundGeoLocation error');
}
// BackgroundGeoLocation is highly configurable.
bgGeo.configure(callbackFn, failureFn, {
url: 'http://only.for.android.com/update_location.json', // <-- only required for Android; ios allows javascript callbacks for your http
params: { // HTTP POST params sent to your server when persisting locations.
auth_token: 'user_secret_auth_token',
foo: 'bar'
},
headers: {
'X-Foo': 'bar'
},
desiredAccuracy: 10,
stationaryRadius: 20,
distanceFilter: 30,
notificationTitle: 'Background tracking', // <-- android only, customize the title of the notification
notificationText: 'ENABLED', // <-- android only, customize the text of the notification
activityType: "AutomotiveNavigation", // <-- iOS-only
debug: true // <-- enable this hear sounds for background-geolocation life-cycle.
});
// Turn ON the background-geolocation system. The user will be tracked whenever they suspend the app.
bgGeo.start();
// If you wish to turn OFF background-tracking, call the #stop method.
// bgGeo.stop()
}
};
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
id="com.transistorsoft.cordova.background-geolocation"
version="0.3.6">
<name>CDVBackgroundGeoLocation</name>
<description>Cordova Background GeoLocation Plugin</description>
<license>MIT</license>
<keywords>phonegap,background geolocation</keywords>
<engines>
<engine name="cordova" version=">=3.0.0" />
</engines>
<dependency id="org.apache.cordova.geolocation" />
<dependency id="org.apache.cordova.dialogs" />
<dependency id="com.google.playservices" url="https://github.com/MobileChromeApps/google-play-services.git" />
<js-module src="www/BackgroundGeoLocation.js" name="BackgroundGeoLocation">
<clobbers target="plugins.backgroundGeoLocation" />
</js-module>
<!-- android -->
<platform name="android">
<source-file src="src/android/libs/eventbus-2.4.0.jar" target-dir="libs" />
<source-file src="src/android/BackgroundGeolocationPlugin.java" target-dir="src/com/transistorsoft/cordova/bggeo" />
<source-file src="src/android/BackgroundGeolocationService.java" target-dir="src/com/transistorsoft/cordova/bggeo" />
<source-file src="src/android/notification.png" target-dir="res/drawable" />
<config-file target="AndroidManifest.xml" parent="/manifest/application">
<service android:name="com.transistorsoft.cordova.bggeo.BackgroundGeolocationService" />
</config-file>
<config-file target="AndroidManifest.xml" parent="/manifest">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
</config-file>
<config-file target="res/xml/config.xml" parent="/*">
<feature name="BackgroundGeoLocation">
<param name="android-package" value="com.transistorsoft.cordova.bggeo.BackgroundGeolocationPlugin"/>
</feature>
</config-file>
</platform>
<platform name="ios">
<!-- required background modes: App registers for location updates -->
<config-file target="*-Info.plist" parent="NSLocationAlwaysUsageDescription">
<string>This app requires background location tracking</string>
</config-file>
<config-file target="*-Info.plist" parent="UIBackgroundModes">
<array>
<string>location</string>
</array>
</config-file>
<config-file target="config.xml" parent="/*">
<feature name="BackgroundGeoLocation">
<param name="ios-package" value="CDVBackgroundGeoLocation"/>
</feature>
</config-file>
<framework src="AudioToolbox.framework" weak="true" />
<framework src="AVFoundation.framework" weak="true" />
<source-file src="src/ios/CDVBackgroundGeoLocation.m" />
<header-file src="src/ios/CDVBackgroundGeoLocation.h" />
</platform>
<!-- wp8 -->
<platform name="wp8">
<config-file target="config.xml" parent="/*">
<feature name="BackgroundGeoLocation">
<param name="wp-package" value="BackgroundGeoLocation" onload="true" />
<param name="onload" value="true" />
</feature>
</config-file>
<config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Tasks/DefaultTask">
<BackgroundExecution>
<ExecutionType Name="LocationTracking" />
</BackgroundExecution>
</config-file>
<config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities">
<Capability Name="ID_CAP_LOCATION" />
</config-file>
<source-file src="src/wp8/BackgroundGeoLocation.cs" />
<source-file src="src/wp8/BackgroundGeoLocationOptions.cs" />
<source-file src="src/wp8/DebugAudioNotifier.cs" />
<source-file src="src/wp8/ExtensionMethods.cs" />
<source-file src="src/wp8/IBackgroundGeoLocation.cs" />
</platform>
</plugin>
File added
This diff is collapsed.
package com.tenforwardconsulting.cordova.bgloc;
import de.greenrobot.event.EventBus;
import com.google.android.gms.location.DetectedActivity;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.ActivityRecognitionResult;
import android.app.IntentService;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.util.Log;
public class BackgroundGeolocationService extends IntentService {
private static final String TAG = "BackgroundGeolocationService";
public LocationService() {
super("com.transistorsoft.cordova.bggeo.BackgroundGeolocationService");
}
@Override
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity probableActivity = result.getMostProbableActivity();
Log.i(TAG, "Activity detected:" + getActivityName(probableActivity.getType()) + ", confidence:" + probableActivity.getConfidence());
if (probableActivity.getConfidence() < 80) {
return;
}
Boolean isMoving = false;
switch (probableActivity.getType()) {
case DetectedActivity.IN_VEHICLE:
case DetectedActivity.ON_BICYCLE:
case DetectedActivity.ON_FOOT:
isMoving = true;
break;
case DetectedActivity.STILL:
break;
case DetectedActivity.UNKNOWN:
break;
case DetectedActivity.TILTING:
break;
}
boolean isPushPluginActive = BackgroundGpsPlugin.isActive();
if (isMoving && !isPushPluginActive) {
forceMainActivityReload();
}
EventBus.getDefault().post(probableActivity);
} else {
final Location location = intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
if (location != null) {
Log.i(TAG, "Location received: " + location.toString());
boolean isPushPluginActive = BackgroundGpsPlugin.isActive();
if (!isPushPluginActive) {
forceMainActivityReload();
}
EventBus.getDefault().post(location);
}
}
}
private String getActivityName(int activityType) {
switch (activityType) {
case DetectedActivity.IN_VEHICLE:
return "in_vehicle";
case DetectedActivity.ON_BICYCLE:
return "on_bicycle";
case DetectedActivity.ON_FOOT:
return "on_foot";
case DetectedActivity.STILL:
return "still";
case DetectedActivity.UNKNOWN:
return "unknown";
case DetectedActivity.TILTING:
return "tilting";
}
return "unknown";
}
/**
* Forces the main activity to re-launch if it's unloaded.
*/
private void forceMainActivityReload() {
Log.w(TAG, "- Forcing main-activity reload");
PackageManager pm = getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage(getApplicationContext().getPackageName());
launchIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(launchIntent);
}
}
\ No newline at end of file
//
// CDVBackgroundGeoLocation.h
//
// Created by Chris Scott <chris@transistorsoft.com>
//
#import <Cordova/CDVPlugin.h>
#import "CDVLocation.h"
#import <AudioToolbox/AudioToolbox.h>
@interface CDVBackgroundGeoLocation : CDVPlugin <CLLocationManagerDelegate>
@property (nonatomic, strong) NSString* syncCallbackId;
@property (nonatomic, strong) NSMutableArray* stationaryRegionListeners;
- (void) configure:(CDVInvokedUrlCommand*)command;
- (void) start:(CDVInvokedUrlCommand*)command;
- (void) stop:(CDVInvokedUrlCommand*)command;
- (void) finish:(CDVInvokedUrlCommand*)command;
- (void) onPaceChange:(CDVInvokedUrlCommand*)command;
- (void) setConfig:(CDVInvokedUrlCommand*)command;
- (void) addStationaryRegionListener:(CDVInvokedUrlCommand*)command;
- (void) getStationaryLocation:(CDVInvokedUrlCommand *)command;
- (void) onSuspend:(NSNotification *)notification;
- (void) onResume:(NSNotification *)notification;
- (void) onAppTerminate;
@end
This diff is collapsed.
using System;
using Windows.Devices.Geolocation;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
using WPCordovaClassLib.Cordova.JSON;
using System.Diagnostics;
namespace Cordova.Extension.Commands
{
public class BackgroundGeoLocation : BaseCommand, IBackgroundGeoLocation
{
private string ConfigureCallbackToken { get; set; }
private BackgroundGeoLocationOptions BackgroundGeoLocationOptions { get; set; }
/// <summary>
/// Geolocator and RunningInBackground are required properties to run in background
/// For more information read http://msdn.microsoft.com/library/windows/apps/jj662935(v=vs.105).aspx
/// </summary>
public static Geolocator Geolocator { get; set; }
public static bool RunningInBackground { get; set; }
/// <summary>
/// When start() is fired immediate after configure() in javascript, configure may not be finished yet, IsConfigured and IsConfiguring are used to keep track of this
/// </summary>
private bool IsConfigured { get; set; }
private bool IsConfiguring { get; set; }
public BackgroundGeoLocation()
{
IsConfiguring = false;
IsConfigured = false;
}
public void configure(string args)
{
IsConfiguring = true;
ConfigureCallbackToken = CurrentCommandCallbackId;
RunningInBackground = false;
BackgroundGeoLocationOptions = this.ParseBackgroundGeoLocationOptions(args);
IsConfigured = BackgroundGeoLocationOptions.ParsingSucceeded;
IsConfiguring = false;
}
private BackgroundGeoLocationOptions ParseBackgroundGeoLocationOptions(string configureArgs)
{
var parsingSucceeded = true;
var options = JsonHelper.Deserialize<string[]>(configureArgs);
double stationaryRadius;
double distanceFilter;
UInt32 locationTimeout;
UInt32 desiredAccuracy;
bool debug;
if (!double.TryParse(options[3], out stationaryRadius))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, string.Format("Invalid value for stationaryRadius:{0}", options[3])));
parsingSucceeded = false;
}
if (!double.TryParse(options[4], out distanceFilter))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, string.Format("Invalid value for distanceFilter:{0}", options[4])));
parsingSucceeded = false;
}
if (!UInt32.TryParse(options[5], out locationTimeout))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, string.Format("Invalid value for locationTimeout:{0}", options[5])));
parsingSucceeded = false;
}
if (!UInt32.TryParse(options[6], out desiredAccuracy))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, string.Format("Invalid value for desiredAccuracy:{0}", options[6])));
parsingSucceeded = false;
}
if (!bool.TryParse(options[7], out debug))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, string.Format("Invalid value for debug:{0}", options[7])));
parsingSucceeded = false;
}
return new BackgroundGeoLocationOptions
{
Url = options[1],
StationaryRadius = stationaryRadius,
DistanceFilterInMeters = distanceFilter,
LocationTimeoutInMilliseconds = locationTimeout,
DesiredAccuracyInMeters = desiredAccuracy,
Debug = debug,
ParsingSucceeded = parsingSucceeded
};
}
public void start(string nothing)
{
while (!IsConfigured && IsConfiguring)
{
// Wait for configure() to complete...
}
if (!IsConfigured || !BackgroundGeoLocationOptions.ParsingSucceeded)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.INVALID_ACTION, "Cannot start: Run configure() with proper values!"));
stop();
return;
}
StopGeolocatorIfActive();
Geolocator = new Geolocator
{
// Default: 50 meters
MovementThreshold = BackgroundGeoLocationOptions.DistanceFilterInMeters,
// JS Interface takes seconds, MS takes miliseconds, default 60 seconds
ReportInterval = BackgroundGeoLocationOptions.LocationTimeoutInMilliseconds * 1000,
// In our case this property has always a value, if left empty or below zero the default will be 100 meter but can be overridden via parameter DesiredAccuracy
DesiredAccuracyInMeters = BackgroundGeoLocationOptions.DesiredAccuracyInMeters
};
Geolocator.PositionChanged += OnGeolocatorOnPositionChanged;
RunningInBackground = true;
}
private void OnGeolocatorOnPositionChanged(Geolocator sender, PositionChangedEventArgs configureCallbackTokenargs)
{
if (Geolocator.LocationStatus == PositionStatus.Disabled || Geolocator.LocationStatus == PositionStatus.NotAvailable)
{
DispatchMessage(PluginResult.Status.ERROR, string.Format("Cannot start: LocationStatus/PositionStatus: {0}! {1}", Geolocator.LocationStatus, IsConfigured), true, ConfigureCallbackToken);
return;
}
var callbackJsonResult = configureCallbackTokenargs.Position.Coordinate.ToJson();
if (BackgroundGeoLocationOptions.Debug)
{
DebugAudioNotifier.GetDebugAudioNotifier().PlaySound(DebugAudioNotifier.Tone.High, TimeSpan.FromSeconds(3));
Debug.WriteLine("PositionChanged token{0}, Coordinates: {1}", ConfigureCallbackToken, callbackJsonResult);
}
DispatchMessage(PluginResult.Status.OK, callbackJsonResult, true, ConfigureCallbackToken);
}
public void stop()
{
RunningInBackground = false;
StopGeolocatorIfActive();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
private void StopGeolocatorIfActive()
{
if (Geolocator == null) return;
Geolocator.PositionChanged -= OnGeolocatorOnPositionChanged;
Geolocator = null;
}
public void finish()
{
DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
}
public void onPaceChange(bool isMoving)
{
throw new NotImplementedException();
}
public void setConfig(string setConfigArgs)
{
if (string.IsNullOrWhiteSpace(setConfigArgs))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.INVALID_ACTION, "Cannot set config because of an empty input"));
return;
}
var parsingSucceeded = true;
var options = JsonHelper.Deserialize<string[]>(setConfigArgs);
double stationaryRadius;
double distanceFilter;
UInt32 locationTimeout;
UInt32 desiredAccuracy;
if (!double.TryParse(options[0], out stationaryRadius))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, string.Format("Invalid value for stationaryRadius:{0}", options[2])));
parsingSucceeded = false;
}
if (!double.TryParse(options[1], out distanceFilter))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, string.Format("Invalid value for distanceFilter:{0}", options[3])));
parsingSucceeded = false;
}
if (!UInt32.TryParse(options[2], out locationTimeout))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, string.Format("Invalid value for locationTimeout:{0}", options[4])));
parsingSucceeded = false;
}
if (!UInt32.TryParse(options[3], out desiredAccuracy))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, string.Format("Invalid value for desiredAccuracy:{0}", options[5])));
parsingSucceeded = false;
}
if (!parsingSucceeded) return;
BackgroundGeoLocationOptions.StationaryRadius = stationaryRadius;
BackgroundGeoLocationOptions.DistanceFilterInMeters = distanceFilter;
BackgroundGeoLocationOptions.LocationTimeoutInMilliseconds = locationTimeout * 1000;
BackgroundGeoLocationOptions.DesiredAccuracyInMeters = desiredAccuracy;
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
public void getStationaryLocation()
{
throw new NotImplementedException();
}
private void DispatchMessage(PluginResult.Status status, string message, bool keepCallback, string callBackId)
{
var pluginResult = new PluginResult(status, message) { KeepCallback = keepCallback };
DispatchCommandResult(pluginResult, callBackId);
}
}
}
using System;
namespace Cordova.Extension.Commands
{
public class BackgroundGeoLocationOptions
{
public string Url;
public double StationaryRadius;
public double DistanceFilterInMeters;
public UInt32 LocationTimeoutInMilliseconds;
public UInt32 DesiredAccuracyInMeters;
public bool Debug;
public bool ParsingSucceeded { get; set; }
}
}
\ No newline at end of file
using System;
using System.Windows;
using System.Windows.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
namespace Cordova.Extension.Commands
{
public class DebugAudioNotifier : IDisposable
{
private static DebugAudioNotifier _audioNotifier;
private DynamicSoundEffectInstance _dynamicSound;
private DispatcherTimer _timer;
private TimeSpan _timeLeft;
private const int SampleRate = 48000;
private Tone _frequency = Tone.Low;
private int _bufferSize;
private byte[] _soundBuffer;
private int _totalTime;
public enum Tone
{
Low = 300,
High = 900
}
private DebugAudioNotifier()
{
}
public static DebugAudioNotifier GetDebugAudioNotifier()
{
return _audioNotifier ?? (_audioNotifier = new DebugAudioNotifier());
}
public void PlaySound(Tone tone, TimeSpan duration)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (_timer == null)
{
_timer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(33)
};
_timer.Tick += delegate { try { FrameworkDispatcher.Update(); } catch { } };
}
if (_timer.IsEnabled) _timer.Stop();
_timeLeft = duration;
FrameworkDispatcher.Update();
_frequency = tone;
_dynamicSound = new DynamicSoundEffectInstance(SampleRate, AudioChannels.Mono);
_dynamicSound.BufferNeeded += dynamicSound_BufferNeeded;
_dynamicSound.Play();
_bufferSize = _dynamicSound.GetSampleSizeInBytes(TimeSpan.FromSeconds(1));
_soundBuffer = new byte[_bufferSize];
_timer.Start();
});
}
private void dynamicSound_BufferNeeded(object sender, EventArgs e)
{
for (var i = 0; i < _bufferSize - 1; i += 2)
{
var time = _totalTime / (double)SampleRate;
var sample = (short)(Math.Sin(2 * Math.PI * (int)_frequency * time) * short.MaxValue);
_soundBuffer[i] = (byte)sample;
_soundBuffer[i + 1] = (byte)(sample >> 8);
_totalTime++;
}
_timeLeft = _timeLeft.Subtract(TimeSpan.FromSeconds(_totalTime / SampleRate));
if (_timeLeft.Ticks <= 0)
{
_totalTime = 0;
return;
}
_dynamicSound.SubmitBuffer(_soundBuffer);
}
public void Dispose()
{
_dynamicSound.Dispose();
}
}
}
\ No newline at end of file
using System;
using System.Globalization;
using Windows.Devices.Geolocation;
namespace Cordova.Extension.Commands
{
public static class ExtensionMethods
{
public static string ToJson(this Geocoordinate geocoordinate)
{
var numberFormatInfo = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
numberFormatInfo.NaNSymbol = "0";
numberFormatInfo.NumberDecimalSeparator = ".";
return string.Format("{{ " +
"\"accuracy\": {0}," +
"\"latitude\": {1}," +
"\"longitude\": {2}," +
"\"altitude\": {3}," +
"\"altitudeAccuracy\": {4}," +
"\"heading\": {5}," +
"\"velocity\": {6}," +
"\"timestamp\": {7}" +
"}}"
, geocoordinate.Accuracy.ToString(numberFormatInfo)
, geocoordinate.Latitude.ToString(numberFormatInfo)
, geocoordinate.Longitude.ToString(numberFormatInfo)
, geocoordinate.Altitude.HasValue ? geocoordinate.Altitude.Value.ToString(numberFormatInfo) : "0"
, geocoordinate.AltitudeAccuracy.HasValue ? geocoordinate.AltitudeAccuracy.Value.ToString(numberFormatInfo) : "0"
, geocoordinate.Heading.HasValue ? geocoordinate.Heading.Value.ToString(numberFormatInfo) : "0"
, geocoordinate.Speed.HasValue ? geocoordinate.Speed.Value.ToString(numberFormatInfo) : "0"
, geocoordinate.Timestamp.DateTime.ToJavaScriptMilliseconds());
}
public static long ToJavaScriptMilliseconds(this DateTime dt)
{
return (long)dt
.ToUniversalTime()
.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
.TotalMilliseconds;
}
}
}
\ No newline at end of file
namespace Cordova.Extension.Commands
{
public interface IBackgroundGeoLocation
{
void configure(string optionsString);
void start(string asd);
void stop();
void finish();
void onPaceChange(bool isMoving);
void setConfig(string config);
void getStationaryLocation();
}
}
\ No newline at end of file
var exec = require("cordova/exec");
module.exports = {
/**
* @property {Object} stationaryRegion
*/
stationaryRegion: null,
/**
* @property {Object} config
*/
config: {},
configure: function(success, failure, config) {
this.config = config;
config.stationaryRadius = (config.stationaryRadius >= 0) ? config.stationaryRadius : 50; // meters
config.distanceFilter = (config.distanceFilter >= 0) ? config.distanceFilter : 500; // meters
config.locationTimeout = (config.locationTimeout >= 0) ? config.locationTimeout : 60; // seconds
config.desiredAccuracy = (config.desiredAccuracy >= 0) ? config.desiredAccuracy : 100; // meters
config.debug = config.debug || false;
config.notificationTitle = config.notificationTitle || "Background tracking";
config.notificationText = config.notificationText || "ENABLED";
config.activityType = config.activityType || "OTHER";
config.stopOnTerminate = config.stopOnTerminate || false;
exec(success || function() {},
failure || function() {},
'BackgroundGeoLocation',
'configure',
[config]
);
},
start: function(success, failure, config) {
exec(success || function() {},
failure || function() {},
'BackgroundGeoLocation',
'start',
[]);
},
stop: function(success, failure, config) {
exec(success || function() {},
failure || function() {},
'BackgroundGeoLocation',
'stop',
[]);
},
finish: function(success, failure) {
exec(success || function() {},
failure || function() {},
'BackgroundGeoLocation',
'finish',
[]);
},
changePace: function(isMoving, success, failure) {
exec(success || function() {},
failure || function() {},
'BackgroundGeoLocation',
'onPaceChange',
[isMoving]);
},
/**
* @param {Integer} stationaryRadius
* @param {Integer} desiredAccuracy
* @param {Integer} distanceFilter
* @param {Integer} timeout
*/
setConfig: function(success, failure, config) {
this.apply(this.config, config);
exec(success || function() {},
failure || function() {},
'BackgroundGeoLocation',
'setConfig',
[config]);
},
/**
* Returns current stationaryLocation if available. null if not
*/
getStationaryLocation: function(success, failure) {
exec(success || function() {},
failure || function() {},
'BackgroundGeoLocation',
'getStationaryLocation',
[]);
},
/**
* Add a stationary-region listener. Whenever the devices enters "stationary-mode", your #success callback will be executed with #location param containing #radius of region
* @param {Function} success
* @param {Function} failure [optional] NOT IMPLEMENTED
*/
onStationary: function(success, failure) {
var me = this;
success = success || function() {};
var callback = function(region) {
me.stationaryRegion = region;
success.apply(me, arguments);
};
exec(callback,
failure || function() {},
'BackgroundGeoLocation',
'addStationaryRegionListener',
[]);
},
apply: function(destination, source) {
source = source || {};
for (var property in source) {
if (source.hasOwnProperty(property)) {
destination[property] = source[property];
}
}
return destination;
}
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment