add Cordova plug-ins:

Battery
Camera
Device
Accelerometer
Compass
Notification
NetworkStatus
Vibration
This commit is contained in:
Yaroslav Dmytrotsa 2015-08-07 11:56:49 +03:00
parent 1d8e2d62d0
commit 51931a7f14
40 changed files with 7316 additions and 12 deletions

View File

@ -124,12 +124,12 @@
<orderEntry type="library" exported="" name="persistence-api-1.0.2" level="project" />
<orderEntry type="library" exported="" name="netty-all-4.0.28.Final" level="project" />
<orderEntry type="library" exported="" name="multidex-1.0.1" level="project" />
<orderEntry type="library" exported="" name="commons-io-2.4" level="project" />
<orderEntry type="library" exported="" name="log4j-1.2.17" level="project" />
<orderEntry type="library" exported="" name="commons-io-2.4" level="project" />
<orderEntry type="library" exported="" name="library-1.1" level="project" />
<orderEntry type="library" exported="" name="guava-18.0" level="project" />
<orderEntry type="library" exported="" name="jackson-annotations-2.5.0" level="project" />
<orderEntry type="library" exported="" name="javassist-3.15.0-GA" level="project" />
<orderEntry type="library" exported="" name="jackson-annotations-2.5.0" level="project" />
<orderEntry type="library" exported="" name="json-smart-1.3.1" level="project" />
<orderEntry type="library" exported="" name="javax.annotation-10.0-b28" level="project" />
<orderEntry type="library" exported="" name="core-1.51.0.0" level="project" />

View File

@ -4,14 +4,18 @@
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:name=".app.SyngApplication"
android:allowBackup="true"

View File

@ -38,6 +38,19 @@
<!-- <link rel="ethereum-dapp-icon" href="/apple-touch-icon-precomposed.png"> -->
<!-- <link rel="apple-touch-icon" href="/apple-touch-icon-precomposed.png"> -->
<!-- <link rel="apple-touch-startup-image" href="/startup.png"> -->
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function alertDismissed() {
}
function onDeviceReady() {
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
}
</script>
</head>
<body>
</body>

View File

@ -0,0 +1,36 @@
/*
* 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.
*/
/**
* Exports the ExposedJsApi.java object if available, otherwise exports the PromptBasedNativeApi.
*/
var nativeApi = this._cordovaNative || require('cordova/android/promptbasednativeapi');
var currentApi = nativeApi;
module.exports = {
get: function() { return currentApi; },
setPreferPrompt: function(value) {
currentApi = value ? require('cordova/android/promptbasednativeapi') : nativeApi;
},
// Used only by tests.
set: function(value) {
currentApi = value;
}
};

View File

@ -0,0 +1,35 @@
/*
* 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.
*/
/**
* Implements the API of ExposedJsApi.java, but uses prompt() to communicate.
* This is used pre-JellyBean, where addJavascriptInterface() is disabled.
*/
module.exports = {
exec: function(bridgeSecret, service, action, callbackId, argsJson) {
return prompt(argsJson, 'gap:'+JSON.stringify([bridgeSecret, service, action, callbackId]));
},
setNativeToJsBridgeMode: function(bridgeSecret, value) {
prompt(value, 'gap_bridge_mode:' + bridgeSecret);
},
retrieveJsMessages: function(bridgeSecret, fromOnlineEvent) {
return prompt(+fromOnlineEvent, 'gap_poll:' + bridgeSecret);
}
};

View File

@ -0,0 +1,287 @@
/*
*
* 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.
*
*/
/**
* Execute a cordova command. It is up to the native side whether this action
* is synchronous or asynchronous. The native side can return:
* Synchronous: PluginResult object as a JSON string
* Asynchronous: Empty string ""
* If async, the native side will cordova.callbackSuccess or cordova.callbackError,
* depending upon the result of the action.
*
* @param {Function} success The success callback
* @param {Function} fail The fail callback
* @param {String} service The name of the service to use
* @param {String} action Action to be run in cordova
* @param {String[]} [args] Zero or more arguments to pass to the method
*/
var cordova = require('cordova'),
nativeApiProvider = require('cordova/android/nativeapiprovider'),
utils = require('cordova/utils'),
base64 = require('cordova/base64'),
channel = require('cordova/channel'),
jsToNativeModes = {
PROMPT: 0,
JS_OBJECT: 1
},
nativeToJsModes = {
// Polls for messages using the JS->Native bridge.
POLLING: 0,
// For LOAD_URL to be viable, it would need to have a work-around for
// the bug where the soft-keyboard gets dismissed when a message is sent.
LOAD_URL: 1,
// For the ONLINE_EVENT to be viable, it would need to intercept all event
// listeners (both through addEventListener and window.ononline) as well
// as set the navigator property itself.
ONLINE_EVENT: 2,
// Uses reflection to access private APIs of the WebView that can send JS
// to be executed.
// Requires Android 3.2.4 or above.
PRIVATE_API: 3
},
jsToNativeBridgeMode, // Set lazily.
nativeToJsBridgeMode = nativeToJsModes.ONLINE_EVENT,
pollEnabled = false,
bridgeSecret = -1;
var messagesFromNative = [];
var isProcessing = false;
var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve();
var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); };
function androidExec(success, fail, service, action, args) {
if (bridgeSecret < 0) {
// If we ever catch this firing, we'll need to queue up exec()s
// and fire them once we get a secret. For now, I don't think
// it's possible for exec() to be called since plugins are parsed but
// not run until until after onNativeReady.
throw new Error('exec() called without bridgeSecret');
}
// Set default bridge modes if they have not already been set.
// By default, we use the failsafe, since addJavascriptInterface breaks too often
if (jsToNativeBridgeMode === undefined) {
androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT);
}
// Process any ArrayBuffers in the args into a string.
for (var i = 0; i < args.length; i++) {
if (utils.typeName(args[i]) == 'ArrayBuffer') {
args[i] = base64.fromArrayBuffer(args[i]);
}
}
var callbackId = service + cordova.callbackId++,
argsJson = JSON.stringify(args);
if (success || fail) {
cordova.callbacks[callbackId] = {success:success, fail:fail};
}
var msgs = nativeApiProvider.get().exec(bridgeSecret, service, action, callbackId, argsJson);
// If argsJson was received by Java as null, try again with the PROMPT bridge mode.
// This happens in rare circumstances, such as when certain Unicode characters are passed over the bridge on a Galaxy S2. See CB-2666.
if (jsToNativeBridgeMode == jsToNativeModes.JS_OBJECT && msgs === "@Null arguments.") {
androidExec.setJsToNativeBridgeMode(jsToNativeModes.PROMPT);
androidExec(success, fail, service, action, args);
androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT);
} else if (msgs) {
messagesFromNative.push(msgs);
// Always process async to avoid exceptions messing up stack.
nextTick(processMessages);
}
}
androidExec.init = function() {
bridgeSecret = +prompt('', 'gap_init:' + nativeToJsBridgeMode);
channel.onNativeReady.fire();
};
function pollOnceFromOnlineEvent() {
pollOnce(true);
}
function pollOnce(opt_fromOnlineEvent) {
if (bridgeSecret < 0) {
// This can happen when the NativeToJsMessageQueue resets the online state on page transitions.
// We know there's nothing to retrieve, so no need to poll.
return;
}
var msgs = nativeApiProvider.get().retrieveJsMessages(bridgeSecret, !!opt_fromOnlineEvent);
if (msgs) {
messagesFromNative.push(msgs);
// Process sync since we know we're already top-of-stack.
processMessages();
}
}
function pollingTimerFunc() {
if (pollEnabled) {
pollOnce();
setTimeout(pollingTimerFunc, 50);
}
}
function hookOnlineApis() {
function proxyEvent(e) {
cordova.fireWindowEvent(e.type);
}
// The network module takes care of firing online and offline events.
// It currently fires them only on document though, so we bridge them
// to window here (while first listening for exec()-releated online/offline
// events).
window.addEventListener('online', pollOnceFromOnlineEvent, false);
window.addEventListener('offline', pollOnceFromOnlineEvent, false);
cordova.addWindowEventHandler('online');
cordova.addWindowEventHandler('offline');
document.addEventListener('online', proxyEvent, false);
document.addEventListener('offline', proxyEvent, false);
}
hookOnlineApis();
androidExec.jsToNativeModes = jsToNativeModes;
androidExec.nativeToJsModes = nativeToJsModes;
androidExec.setJsToNativeBridgeMode = function(mode) {
if (mode == jsToNativeModes.JS_OBJECT && !window._cordovaNative) {
mode = jsToNativeModes.PROMPT;
}
nativeApiProvider.setPreferPrompt(mode == jsToNativeModes.PROMPT);
jsToNativeBridgeMode = mode;
};
androidExec.setNativeToJsBridgeMode = function(mode) {
if (mode == nativeToJsBridgeMode) {
return;
}
if (nativeToJsBridgeMode == nativeToJsModes.POLLING) {
pollEnabled = false;
}
nativeToJsBridgeMode = mode;
// Tell the native side to switch modes.
// Otherwise, it will be set by androidExec.init()
if (bridgeSecret >= 0) {
nativeApiProvider.get().setNativeToJsBridgeMode(bridgeSecret, mode);
}
if (mode == nativeToJsModes.POLLING) {
pollEnabled = true;
setTimeout(pollingTimerFunc, 1);
}
};
function buildPayload(payload, message) {
var payloadKind = message.charAt(0);
if (payloadKind == 's') {
payload.push(message.slice(1));
} else if (payloadKind == 't') {
payload.push(true);
} else if (payloadKind == 'f') {
payload.push(false);
} else if (payloadKind == 'N') {
payload.push(null);
} else if (payloadKind == 'n') {
payload.push(+message.slice(1));
} else if (payloadKind == 'A') {
var data = message.slice(1);
payload.push(base64.toArrayBuffer(data));
} else if (payloadKind == 'S') {
payload.push(window.atob(message.slice(1)));
} else if (payloadKind == 'M') {
var multipartMessages = message.slice(1);
while (multipartMessages !== "") {
var spaceIdx = multipartMessages.indexOf(' ');
var msgLen = +multipartMessages.slice(0, spaceIdx);
var multipartMessage = multipartMessages.substr(spaceIdx + 1, msgLen);
multipartMessages = multipartMessages.slice(spaceIdx + msgLen + 1);
buildPayload(payload, multipartMessage);
}
} else {
payload.push(JSON.parse(message));
}
}
// Processes a single message, as encoded by NativeToJsMessageQueue.java.
function processMessage(message) {
var firstChar = message.charAt(0);
if (firstChar == 'J') {
// This is deprecated on the .java side. It doesn't work with CSP enabled.
eval(message.slice(1));
} else if (firstChar == 'S' || firstChar == 'F') {
var success = firstChar == 'S';
var keepCallback = message.charAt(1) == '1';
var spaceIdx = message.indexOf(' ', 2);
var status = +message.slice(2, spaceIdx);
var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1);
var callbackId = message.slice(spaceIdx + 1, nextSpaceIdx);
var payloadMessage = message.slice(nextSpaceIdx + 1);
var payload = [];
buildPayload(payload, payloadMessage);
cordova.callbackFromNative(callbackId, success, status, payload, keepCallback);
} else {
console.log("processMessage failed: invalid message: " + JSON.stringify(message));
}
}
function processMessages() {
// Check for the reentrant case.
if (isProcessing) {
return;
}
if (messagesFromNative.length === 0) {
return;
}
isProcessing = true;
try {
var msg = popMessageFromQueue();
// The Java side can send a * message to indicate that it
// still has messages waiting to be retrieved.
if (msg == '*' && messagesFromNative.length === 0) {
nextTick(pollOnce);
return;
}
processMessage(msg);
} finally {
isProcessing = false;
if (messagesFromNative.length > 0) {
nextTick(processMessages);
}
}
}
function popMessageFromQueue() {
var messageBatch = messagesFromNative.shift();
if (messageBatch == '*') {
return '*';
}
var spaceIdx = messageBatch.indexOf(' ');
var msgLen = +messageBatch.slice(0, spaceIdx);
var message = messageBatch.substr(spaceIdx + 1, msgLen);
messageBatch = messageBatch.slice(spaceIdx + msgLen + 1);
if (messageBatch) {
messagesFromNative.unshift(messageBatch);
}
return message;
}
module.exports = androidExec;

View File

@ -0,0 +1,91 @@
/*
*
* 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.
*
*/
module.exports = {
id: 'android',
bootstrap: function() {
var channel = require('cordova/channel'),
cordova = require('cordova'),
exec = require('cordova/exec'),
modulemapper = require('cordova/modulemapper');
// Get the shared secret needed to use the bridge.
exec.init();
// TODO: Extract this as a proper plugin.
modulemapper.clobbers('cordova/plugin/android/app', 'navigator.app');
var APP_PLUGIN_NAME = Number(cordova.platformVersion.split('.')[0]) >= 4 ? 'CoreAndroid' : 'App';
// Inject a listener for the backbutton on the document.
var backButtonChannel = cordova.addDocumentEventHandler('backbutton');
backButtonChannel.onHasSubscribersChange = function() {
// If we just attached the first handler or detached the last handler,
// let native know we need to override the back button.
exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [this.numHandlers == 1]);
};
// Add hardware MENU and SEARCH button handlers
cordova.addDocumentEventHandler('menubutton');
cordova.addDocumentEventHandler('searchbutton');
function bindButtonChannel(buttonName) {
// generic button bind used for volumeup/volumedown buttons
var volumeButtonChannel = cordova.addDocumentEventHandler(buttonName + 'button');
volumeButtonChannel.onHasSubscribersChange = function() {
exec(null, null, APP_PLUGIN_NAME, "overrideButton", [buttonName, this.numHandlers == 1]);
};
}
// Inject a listener for the volume buttons on the document.
bindButtonChannel('volumeup');
bindButtonChannel('volumedown');
// Let native code know we are all done on the JS side.
// Native code will then un-hide the WebView.
channel.onCordovaReady.subscribe(function() {
exec(onMessageFromNative, null, APP_PLUGIN_NAME, 'messageChannel', []);
exec(null, null, APP_PLUGIN_NAME, "show", []);
});
}
};
function onMessageFromNative(msg) {
var cordova = require('cordova');
var action = msg.action;
switch (action)
{
// Button events
case 'backbutton':
case 'menubutton':
case 'searchbutton':
// App life cycle events
case 'pause':
case 'resume':
// Volume events
case 'volumedownbutton':
case 'volumeupbutton':
cordova.fireDocumentEvent(action);
break;
default:
throw new Error('Unknown event action ' + action);
}
}

View File

@ -0,0 +1,108 @@
/*
*
* 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 exec = require('cordova/exec');
var APP_PLUGIN_NAME = Number(require('cordova').platformVersion.split('.')[0]) >= 4 ? 'CoreAndroid' : 'App';
module.exports = {
/**
* Clear the resource cache.
*/
clearCache:function() {
exec(null, null, APP_PLUGIN_NAME, "clearCache", []);
},
/**
* Load the url into the webview or into new browser instance.
*
* @param url The URL to load
* @param props Properties that can be passed in to the activity:
* wait: int => wait msec before loading URL
* loadingDialog: "Title,Message" => display a native loading dialog
* loadUrlTimeoutValue: int => time in msec to wait before triggering a timeout error
* clearHistory: boolean => clear webview history (default=false)
* openExternal: boolean => open in a new browser (default=false)
*
* Example:
* navigator.app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000});
*/
loadUrl:function(url, props) {
exec(null, null, APP_PLUGIN_NAME, "loadUrl", [url, props]);
},
/**
* Cancel loadUrl that is waiting to be loaded.
*/
cancelLoadUrl:function() {
exec(null, null, APP_PLUGIN_NAME, "cancelLoadUrl", []);
},
/**
* Clear web history in this web view.
* Instead of BACK button loading the previous web page, it will exit the app.
*/
clearHistory:function() {
exec(null, null, APP_PLUGIN_NAME, "clearHistory", []);
},
/**
* Go to previous page displayed.
* This is the same as pressing the backbutton on Android device.
*/
backHistory:function() {
exec(null, null, APP_PLUGIN_NAME, "backHistory", []);
},
/**
* Override the default behavior of the Android back button.
* If overridden, when the back button is pressed, the "backKeyDown" JavaScript event will be fired.
*
* Note: The user should not have to call this method. Instead, when the user
* registers for the "backbutton" event, this is automatically done.
*
* @param override T=override, F=cancel override
*/
overrideBackbutton:function(override) {
exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [override]);
},
/**
* Override the default behavior of the Android volume button.
* If overridden, when the volume button is pressed, the "volume[up|down]button"
* JavaScript event will be fired.
*
* Note: The user should not have to call this method. Instead, when the user
* registers for the "volume[up|down]button" event, this is automatically done.
*
* @param button volumeup, volumedown
* @param override T=override, F=cancel override
*/
overrideButton:function(button, override) {
exec(null, null, APP_PLUGIN_NAME, "overrideButton", [button, override]);
},
/**
* Exit and terminate the application.
*/
exitApp:function() {
return exec(null, null, APP_PLUGIN_NAME, "exitApp", []);
}
};

1980
app/src/main/assets/www/cordova.js vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,138 @@
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"file": "plugins/cordova-plugin-whitelist/whitelist.js",
"id": "cordova-plugin-whitelist.whitelist",
"runs": true
},
{
"file": "plugins/cordova-plugin-device/www/device.js",
"id": "cordova-plugin-device.device",
"clobbers": [
"device"
]
},
{
"file": "plugins/cordova-plugin-network-information/www/network.js",
"id": "cordova-plugin-network-information.network",
"clobbers": [
"navigator.connection",
"navigator.network.connection"
]
},
{
"file": "plugins/cordova-plugin-network-information/www/Connection.js",
"id": "cordova-plugin-network-information.Connection",
"clobbers": [
"Connection"
]
},
{
"file": "plugins/cordova-plugin-battery-status/www/battery.js",
"id": "cordova-plugin-battery-status.battery",
"clobbers": [
"navigator.battery"
]
},
{
"file": "plugins/cordova-plugin-device-motion/www/Acceleration.js",
"id": "cordova-plugin-device-motion.Acceleration",
"clobbers": [
"Acceleration"
]
},
{
"file": "plugins/cordova-plugin-device-motion/www/accelerometer.js",
"id": "cordova-plugin-device-motion.accelerometer",
"clobbers": [
"navigator.accelerometer"
]
},
{
"file": "plugins/cordova-plugin-device-orientation/www/CompassError.js",
"id": "cordova-plugin-device-orientation.CompassError",
"clobbers": [
"CompassError"
]
},
{
"file": "plugins/cordova-plugin-device-orientation/www/CompassHeading.js",
"id": "cordova-plugin-device-orientation.CompassHeading",
"clobbers": [
"CompassHeading"
]
},
{
"file": "plugins/cordova-plugin-device-orientation/www/compass.js",
"id": "cordova-plugin-device-orientation.compass",
"clobbers": [
"navigator.compass"
]
},
{
"file": "plugins/cordova-plugin-camera/www/CameraConstants.js",
"id": "cordova-plugin-camera.Camera",
"clobbers": [
"Camera"
]
},
{
"file": "plugins/cordova-plugin-camera/www/CameraPopoverOptions.js",
"id": "cordova-plugin-camera.CameraPopoverOptions",
"clobbers": [
"CameraPopoverOptions"
]
},
{
"file": "plugins/cordova-plugin-camera/www/Camera.js",
"id": "cordova-plugin-camera.camera",
"clobbers": [
"navigator.camera"
]
},
{
"file": "plugins/cordova-plugin-camera/www/CameraPopoverHandle.js",
"id": "cordova-plugin-camera.CameraPopoverHandle",
"clobbers": [
"CameraPopoverHandle"
]
},
{
"file": "plugins/cordova-plugin-dialogs/www/notification.js",
"id": "cordova-plugin-dialogs.notification",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/cordova-plugin-dialogs/www/android/notification.js",
"id": "cordova-plugin-dialogs.notification_android",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/cordova-plugin-vibration/www/vibration.js",
"id": "cordova-plugin-vibration.notification",
"merges": [
"navigator.notification",
"navigator"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"cordova-plugin-whitelist": "1.0.0",
"cordova-plugin-geolocation": "1.0.1",
"cordova-plugin-device": "1.0.1",
"cordova-plugin-network-information": "1.0.1",
"cordova-plugin-battery-status": "1.1.0",
"cordova-plugin-device-motion": "1.1.1",
"cordova-plugin-device-orientation": "1.0.1",
"cordova-plugin-camera": "1.2.0",
"cordova-plugin-dialogs": "1.1.1",
"cordova-plugin-vibration": "1.2.0"
}
// BOTTOM OF METADATA
});

View File

@ -0,0 +1,112 @@
cordova.define("cordova-plugin-battery-status.battery", function(require, exports, module) { /*
*
* 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.
*
*/
/**
* This class contains information about the current battery status.
* @constructor
*/
var cordova = require('cordova'),
exec = require('cordova/exec');
function handlers() {
return battery.channels.batterystatus.numHandlers +
battery.channels.batterylow.numHandlers +
battery.channels.batterycritical.numHandlers;
}
var STATUS_CRITICAL = 5;
var STATUS_LOW = 20;
var Battery = function() {
this._level = null;
this._isPlugged = null;
// Create new event handlers on the window (returns a channel instance)
this.channels = {
batterystatus:cordova.addWindowEventHandler("batterystatus"),
batterylow:cordova.addWindowEventHandler("batterylow"),
batterycritical:cordova.addWindowEventHandler("batterycritical")
};
for (var key in this.channels) {
this.channels[key].onHasSubscribersChange = Battery.onHasSubscribersChange;
}
};
/**
* Event handlers for when callbacks get registered for the battery.
* Keep track of how many handlers we have so we can start and stop the native battery listener
* appropriately (and hopefully save on battery life!).
*/
Battery.onHasSubscribersChange = function() {
// If we just registered the first handler, make sure native listener is started.
if (this.numHandlers === 1 && handlers() === 1) {
exec(battery._status, battery._error, "Battery", "start", []);
} else if (handlers() === 0) {
exec(null, null, "Battery", "stop", []);
}
};
/**
* Callback for battery status
*
* @param {Object} info keys: level, isPlugged
*/
Battery.prototype._status = function (info) {
if (info) {
if (battery._level !== info.level || battery._isPlugged !== info.isPlugged) {
if(info.level == null && battery._level != null) {
return; // special case where callback is called because we stopped listening to the native side.
}
// Something changed. Fire batterystatus event
cordova.fireWindowEvent("batterystatus", info);
if (!info.isPlugged) { // do not fire low/critical if we are charging. issue: CB-4520
// note the following are NOT exact checks, as we want to catch a transition from
// above the threshold to below. issue: CB-4519
if (battery._level > STATUS_CRITICAL && info.level <= STATUS_CRITICAL) {
// Fire critical battery event
cordova.fireWindowEvent("batterycritical", info);
}
else if (battery._level > STATUS_LOW && info.level <= STATUS_LOW) {
// Fire low battery event
cordova.fireWindowEvent("batterylow", info);
}
}
battery._level = info.level;
battery._isPlugged = info.isPlugged;
}
}
};
/**
* Error callback for battery start
*/
Battery.prototype._error = function(e) {
console.log("Error initializing Battery: " + e);
};
var battery = new Battery();
module.exports = battery;
});

View File

@ -0,0 +1,77 @@
cordova.define("cordova-plugin-camera.camera", function(require, exports, module) { /*
*
* 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 argscheck = require('cordova/argscheck'),
exec = require('cordova/exec'),
Camera = require('./Camera');
// XXX: commented out
//CameraPopoverHandle = require('./CameraPopoverHandle');
var cameraExport = {};
// Tack on the Camera Constants to the base camera plugin.
for (var key in Camera) {
cameraExport[key] = Camera[key];
}
/**
* Gets a picture from source defined by "options.sourceType", and returns the
* image as defined by the "options.destinationType" option.
* The defaults are sourceType=CAMERA and destinationType=FILE_URI.
*
* @param {Function} successCallback
* @param {Function} errorCallback
* @param {Object} options
*/
cameraExport.getPicture = function(successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'Camera.getPicture', arguments);
options = options || {};
var getValue = argscheck.getValue;
var quality = getValue(options.quality, 50);
var destinationType = getValue(options.destinationType, Camera.DestinationType.FILE_URI);
var sourceType = getValue(options.sourceType, Camera.PictureSourceType.CAMERA);
var targetWidth = getValue(options.targetWidth, -1);
var targetHeight = getValue(options.targetHeight, -1);
var encodingType = getValue(options.encodingType, Camera.EncodingType.JPEG);
var mediaType = getValue(options.mediaType, Camera.MediaType.PICTURE);
var allowEdit = !!options.allowEdit;
var correctOrientation = !!options.correctOrientation;
var saveToPhotoAlbum = !!options.saveToPhotoAlbum;
var popoverOptions = getValue(options.popoverOptions, null);
var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK);
var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType,
mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions, cameraDirection];
exec(successCallback, errorCallback, "Camera", "takePicture", args);
// XXX: commented out
//return new CameraPopoverHandle();
};
cameraExport.cleanup = function(successCallback, errorCallback) {
exec(successCallback, errorCallback, "Camera", "cleanup", []);
};
module.exports = cameraExport;
});

View File

@ -0,0 +1,55 @@
cordova.define("cordova-plugin-camera.Camera", function(require, exports, module) { /*
*
* 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.
*
*/
module.exports = {
DestinationType:{
DATA_URL: 0, // Return base64 encoded string
FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android)
NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS)
},
EncodingType:{
JPEG: 0, // Return JPEG encoded image
PNG: 1 // Return PNG encoded image
},
MediaType:{
PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, ONLY RETURNS URL
ALLMEDIA : 2 // allow selection from all media types
},
PictureSourceType:{
PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
CAMERA : 1, // Take picture from camera
SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
},
PopoverArrowDirection:{
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants to specify arrow location on popover
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
},
Direction:{
BACK: 0,
FRONT: 1
}
};
});

View File

@ -0,0 +1,35 @@
cordova.define("cordova-plugin-camera.CameraPopoverHandle", function(require, exports, module) { /*
*
* 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 exec = require('cordova/exec');
/**
* A handle to an image picker popover.
*/
var CameraPopoverHandle = function() {
this.setPosition = function(popoverOptions) {
console.log('CameraPopoverHandle.setPosition is only supported on iOS.');
};
};
module.exports = CameraPopoverHandle;
});

View File

@ -0,0 +1,39 @@
cordova.define("cordova-plugin-camera.CameraPopoverOptions", function(require, exports, module) { /*
*
* 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 Camera = require('./Camera');
/**
* Encapsulates options for iOS Popover image picker
*/
var CameraPopoverOptions = function(x,y,width,height,arrowDir){
// information of rectangle that popover should be anchored to
this.x = x || 0;
this.y = y || 32;
this.width = width || 320;
this.height = height || 480;
// The direction of the popover arrow
this.arrowDir = arrowDir || Camera.PopoverArrowDirection.ARROW_ANY;
};
module.exports = CameraPopoverOptions;
});

View File

@ -0,0 +1,31 @@
cordova.define("cordova-plugin-device-motion.Acceleration", function(require, exports, module) { /*
*
* 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 Acceleration = function(x, y, z, timestamp) {
this.x = x;
this.y = y;
this.z = z;
this.timestamp = timestamp || (new Date()).getTime();
};
module.exports = Acceleration;
});

View File

@ -0,0 +1,183 @@
cordova.define("cordova-plugin-device-motion.accelerometer", function(require, exports, module) { /*
*
* 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.
*
*/
/**
* This class provides access to device accelerometer data.
* @constructor
*/
var argscheck = require('cordova/argscheck'),
utils = require("cordova/utils"),
exec = require("cordova/exec"),
Acceleration = require('./Acceleration');
// Is the accel sensor running?
var running = false;
// Keeps reference to watchAcceleration calls.
var timers = {};
// Array of listeners; used to keep track of when we should call start and stop.
var listeners = [];
// Last returned acceleration object from native
var accel = null;
// Tells native to start.
function start() {
exec(function (a) {
var tempListeners = listeners.slice(0);
accel = new Acceleration(a.x, a.y, a.z, a.timestamp);
for (var i = 0, l = tempListeners.length; i < l; i++) {
tempListeners[i].win(accel);
}
}, function (e) {
var tempListeners = listeners.slice(0);
for (var i = 0, l = tempListeners.length; i < l; i++) {
tempListeners[i].fail(e);
}
}, "Accelerometer", "start", []);
running = true;
}
// Tells native to stop.
function stop() {
exec(null, null, "Accelerometer", "stop", []);
accel = null;
running = false;
}
// Adds a callback pair to the listeners array
function createCallbackPair(win, fail) {
return { win: win, fail: fail };
}
// Removes a win/fail listener pair from the listeners array
function removeListeners(l) {
var idx = listeners.indexOf(l);
if (idx > -1) {
listeners.splice(idx, 1);
if (listeners.length === 0) {
stop();
}
}
}
var accelerometer = {
/**
* Asynchronously acquires the current acceleration.
*
* @param {Function} successCallback The function to call when the acceleration data is available
* @param {Function} errorCallback The function to call when there is an error getting the acceleration data. (OPTIONAL)
* @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
*/
getCurrentAcceleration: function (successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'accelerometer.getCurrentAcceleration', arguments);
if (cordova.platformId === "windowsphone") {
exec(function (a) {
accel = new Acceleration(a.x, a.y, a.z, a.timestamp);
successCallback(accel);
}, function (e) {
errorCallback(e);
}, "Accelerometer", "getCurrentAcceleration", []);
return;
}
var p;
var win = function (a) {
removeListeners(p);
successCallback(a);
};
var fail = function (e) {
removeListeners(p);
errorCallback && errorCallback(e);
};
p = createCallbackPair(win, fail);
listeners.push(p);
if (!running) {
start();
}
},
/**
* Asynchronously acquires the acceleration repeatedly at a given interval.
*
* @param {Function} successCallback The function to call each time the acceleration data is available
* @param {Function} errorCallback The function to call when there is an error getting the acceleration data. (OPTIONAL)
* @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
* @return String The watch id that must be passed to #clearWatch to stop watching.
*/
watchAcceleration: function (successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'accelerometer.watchAcceleration', arguments);
// Default interval (10 sec)
var frequency = (options && options.frequency && typeof options.frequency == 'number') ? options.frequency : 10000;
// Keep reference to watch id, and report accel readings as often as defined in frequency
var id = utils.createUUID();
var p = createCallbackPair(function () { }, function (e) {
removeListeners(p);
errorCallback && errorCallback(e);
});
listeners.push(p);
timers[id] = {
timer: window.setInterval(function () {
if (accel) {
successCallback(accel);
}
}, frequency),
listeners: p
};
if (running) {
// If we're already running then immediately invoke the success callback
// but only if we have retrieved a value, sample code does not check for null ...
if (accel) {
successCallback(accel);
}
} else {
start();
}
return id;
},
/**
* Clears the specified accelerometer watch.
*
* @param {String} id The id of the watch returned from #watchAcceleration.
*/
clearWatch: function (id) {
// Stop javascript timer & remove from timer list
if (id && timers[id]) {
window.clearInterval(timers[id].timer);
removeListeners(timers[id].listeners);
delete timers[id];
}
}
};
module.exports = accelerometer;
});

View File

@ -0,0 +1,36 @@
cordova.define("cordova-plugin-device-orientation.CompassError", function(require, exports, module) { /*
*
* 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.
*
*/
/**
* CompassError.
* An error code assigned by an implementation when an error has occurred
* @constructor
*/
var CompassError = function(err) {
this.code = (err !== undefined ? err : null);
};
CompassError.COMPASS_INTERNAL_ERR = 0;
CompassError.COMPASS_NOT_SUPPORTED = 20;
module.exports = CompassError;
});

View File

@ -0,0 +1,31 @@
cordova.define("cordova-plugin-device-orientation.CompassHeading", function(require, exports, module) { /*
*
* 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 CompassHeading = function(magneticHeading, trueHeading, headingAccuracy, timestamp) {
this.magneticHeading = magneticHeading;
this.trueHeading = trueHeading;
this.headingAccuracy = headingAccuracy;
this.timestamp = timestamp || new Date().getTime();
};
module.exports = CompassHeading;
});

View File

@ -0,0 +1,105 @@
cordova.define("cordova-plugin-device-orientation.compass", function(require, exports, module) { /*
*
* 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 argscheck = require('cordova/argscheck'),
exec = require('cordova/exec'),
utils = require('cordova/utils'),
CompassHeading = require('./CompassHeading'),
CompassError = require('./CompassError'),
timers = {},
compass = {
/**
* Asynchronously acquires the current heading.
* @param {Function} successCallback The function to call when the heading
* data is available
* @param {Function} errorCallback The function to call when there is an error
* getting the heading data.
* @param {CompassOptions} options The options for getting the heading data (not used).
*/
getCurrentHeading:function(successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'compass.getCurrentHeading', arguments);
var win = function(result) {
var ch = new CompassHeading(result.magneticHeading, result.trueHeading, result.headingAccuracy, result.timestamp);
successCallback(ch);
};
var fail = errorCallback && function(code) {
var ce = new CompassError(code);
errorCallback(ce);
};
// Get heading
exec(win, fail, "Compass", "getHeading", [options]);
},
/**
* Asynchronously acquires the heading repeatedly at a given interval.
* @param {Function} successCallback The function to call each time the heading
* data is available
* @param {Function} errorCallback The function to call when there is an error
* getting the heading data.
* @param {HeadingOptions} options The options for getting the heading data
* such as timeout and the frequency of the watch. For iOS, filter parameter
* specifies to watch via a distance filter rather than time.
*/
watchHeading:function(successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'compass.watchHeading', arguments);
// Default interval (100 msec)
var frequency = (options !== undefined && options.frequency !== undefined) ? options.frequency : 100;
var filter = (options !== undefined && options.filter !== undefined) ? options.filter : 0;
var id = utils.createUUID();
if (filter > 0) {
// is an iOS request for watch by filter, no timer needed
timers[id] = "iOS";
compass.getCurrentHeading(successCallback, errorCallback, options);
} else {
// Start watch timer to get headings
timers[id] = window.setInterval(function() {
compass.getCurrentHeading(successCallback, errorCallback);
}, frequency);
}
return id;
},
/**
* Clears the specified heading watch.
* @param {String} watchId The ID of the watch returned from #watchHeading.
*/
clearWatch:function(id) {
// Stop javascript timer & remove from timer list
if (id && timers[id]) {
if (timers[id] != "iOS") {
clearInterval(timers[id]);
} else {
// is iOS watch by filter so call into device to stop
exec(null, null, "Compass", "stopHeading", []);
}
delete timers[id];
}
}
};
module.exports = compass;
});

View File

@ -0,0 +1,81 @@
cordova.define("cordova-plugin-device.device", function(require, exports, module) { /*
*
* 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 argscheck = require('cordova/argscheck'),
channel = require('cordova/channel'),
utils = require('cordova/utils'),
exec = require('cordova/exec'),
cordova = require('cordova');
channel.createSticky('onCordovaInfoReady');
// Tell cordova channel to wait on the CordovaInfoReady event
channel.waitForInitialization('onCordovaInfoReady');
/**
* This represents the mobile device, and provides properties for inspecting the model, version, UUID of the
* phone, etc.
* @constructor
*/
function Device() {
this.available = false;
this.platform = null;
this.version = null;
this.uuid = null;
this.cordova = null;
this.model = null;
this.manufacturer = null;
var me = this;
channel.onCordovaReady.subscribe(function() {
me.getInfo(function(info) {
//ignoring info.cordova returning from native, we should use value from cordova.version defined in cordova.js
//TODO: CB-5105 native implementations should not return info.cordova
var buildLabel = cordova.version;
me.available = true;
me.platform = info.platform;
me.version = info.version;
me.uuid = info.uuid;
me.cordova = buildLabel;
me.model = info.model;
me.manufacturer = info.manufacturer || 'unknown';
channel.onCordovaInfoReady.fire();
},function(e) {
me.available = false;
utils.alert("[ERROR] Error initializing Cordova: " + e);
});
});
}
/**
* Get device info
*
* @param {Function} successCallback The function to call when the heading data is available
* @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
*/
Device.prototype.getInfo = function(successCallback, errorCallback) {
argscheck.checkArgs('fF', 'Device.getInfo', arguments);
exec(successCallback, errorCallback, "Device", "getDeviceInfo", []);
};
module.exports = new Device();
});

View File

@ -0,0 +1,76 @@
cordova.define("cordova-plugin-dialogs.notification_android", function(require, exports, module) { /*
*
* 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 exec = require('cordova/exec');
/**
* Provides Android enhanced notification API.
*/
module.exports = {
activityStart : function(title, message) {
// If title and message not specified then mimic Android behavior of
// using default strings.
if (typeof title === "undefined" && typeof message == "undefined") {
title = "Busy";
message = 'Please wait...';
}
exec(null, null, 'Notification', 'activityStart', [ title, message ]);
},
/**
* Close an activity dialog
*/
activityStop : function() {
exec(null, null, 'Notification', 'activityStop', []);
},
/**
* Display a progress dialog with progress bar that goes from 0 to 100.
*
* @param {String}
* title Title of the progress dialog.
* @param {String}
* message Message to display in the dialog.
*/
progressStart : function(title, message) {
exec(null, null, 'Notification', 'progressStart', [ title, message ]);
},
/**
* Close the progress dialog.
*/
progressStop : function() {
exec(null, null, 'Notification', 'progressStop', []);
},
/**
* Set the progress dialog value.
*
* @param {Number}
* value 0-100
*/
progressValue : function(value) {
exec(null, null, 'Notification', 'progressValue', [ value ]);
}
};
});

View File

@ -0,0 +1,114 @@
cordova.define("cordova-plugin-dialogs.notification", function(require, exports, module) { /*
*
* 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 exec = require('cordova/exec');
var platform = require('cordova/platform');
/**
* Provides access to notifications on the device.
*/
module.exports = {
/**
* Open a native alert dialog, with a customizable title and button text.
*
* @param {String} message Message to print in the body of the alert
* @param {Function} completeCallback The callback that is called when user clicks on a button.
* @param {String} title Title of the alert dialog (default: Alert)
* @param {String} buttonLabel Label of the close button (default: OK)
*/
alert: function(message, completeCallback, title, buttonLabel) {
var _title = (title || "Alert");
var _buttonLabel = (buttonLabel || "OK");
exec(completeCallback, null, "Notification", "alert", [message, _title, _buttonLabel]);
},
/**
* Open a native confirm dialog, with a customizable title and button text.
* The result that the user selects is returned to the result callback.
*
* @param {String} message Message to print in the body of the alert
* @param {Function} resultCallback The callback that is called when user clicks on a button.
* @param {String} title Title of the alert dialog (default: Confirm)
* @param {Array} buttonLabels Array of the labels of the buttons (default: ['OK', 'Cancel'])
*/
confirm: function(message, resultCallback, title, buttonLabels) {
var _title = (title || "Confirm");
var _buttonLabels = (buttonLabels || ["OK", "Cancel"]);
// Strings are deprecated!
if (typeof _buttonLabels === 'string') {
console.log("Notification.confirm(string, function, string, string) is deprecated. Use Notification.confirm(string, function, string, array).");
}
// Some platforms take an array of button label names.
// Other platforms take a comma separated list.
// For compatibility, we convert to the desired type based on the platform.
if (platform.id == "amazon-fireos" || platform.id == "android" || platform.id == "ios" ||
platform.id == "windowsphone" || platform.id == "firefoxos" || platform.id == "ubuntu" ||
platform.id == "windows8" || platform.id == "windows") {
if (typeof _buttonLabels === 'string') {
_buttonLabels = _buttonLabels.split(","); // not crazy about changing the var type here
}
} else {
if (Array.isArray(_buttonLabels)) {
var buttonLabelArray = _buttonLabels;
_buttonLabels = buttonLabelArray.toString();
}
}
exec(resultCallback, null, "Notification", "confirm", [message, _title, _buttonLabels]);
},
/**
* Open a native prompt dialog, with a customizable title and button text.
* The following results are returned to the result callback:
* buttonIndex Index number of the button selected.
* input1 The text entered in the prompt dialog box.
*
* @param {String} message Dialog message to display (default: "Prompt message")
* @param {Function} resultCallback The callback that is called when user clicks on a button.
* @param {String} title Title of the dialog (default: "Prompt")
* @param {Array} buttonLabels Array of strings for the button labels (default: ["OK","Cancel"])
* @param {String} defaultText Textbox input value (default: empty string)
*/
prompt: function(message, resultCallback, title, buttonLabels, defaultText) {
var _message = (message || "Prompt message");
var _title = (title || "Prompt");
var _buttonLabels = (buttonLabels || ["OK","Cancel"]);
var _defaultText = (defaultText || "");
exec(resultCallback, null, "Notification", "prompt", [_message, _title, _buttonLabels, _defaultText]);
},
/**
* Causes the device to beep.
* On Android, the default notification ringtone is played "count" times.
*
* @param {Integer} count The number of beeps.
*/
beep: function(count) {
var defaultedCount = count || 1;
exec(null, null, "Notification", "beep", [ defaultedCount ]);
}
};
});

View File

@ -0,0 +1,36 @@
cordova.define("cordova-plugin-network-information.Connection", function(require, exports, module) { /*
*
* 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.
*
*/
/**
* Network status
*/
module.exports = {
UNKNOWN: "unknown",
ETHERNET: "ethernet",
WIFI: "wifi",
CELL_2G: "2g",
CELL_3G: "3g",
CELL_4G: "4g",
CELL:"cellular",
NONE: "none"
};
});

View File

@ -0,0 +1,93 @@
cordova.define("cordova-plugin-network-information.network", function(require, exports, module) { /*
* 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 exec = require('cordova/exec'),
cordova = require('cordova'),
channel = require('cordova/channel'),
utils = require('cordova/utils');
// Link the onLine property with the Cordova-supplied network info.
// This works because we clobber the navigator object with our own
// object in bootstrap.js.
// Browser platform do not need to define this property, because
// it is already supported by modern browsers
if (cordova.platformId !== 'browser' && typeof navigator != 'undefined') {
utils.defineGetter(navigator, 'onLine', function() {
return this.connection.type != 'none';
});
}
function NetworkConnection() {
this.type = 'unknown';
}
/**
* Get connection info
*
* @param {Function} successCallback The function to call when the Connection data is available
* @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL)
*/
NetworkConnection.prototype.getInfo = function(successCallback, errorCallback) {
exec(successCallback, errorCallback, "NetworkStatus", "getConnectionInfo", []);
};
var me = new NetworkConnection();
var timerId = null;
var timeout = 500;
channel.createSticky('onCordovaConnectionReady');
channel.waitForInitialization('onCordovaConnectionReady');
channel.onCordovaReady.subscribe(function() {
me.getInfo(function(info) {
me.type = info;
if (info === "none") {
// set a timer if still offline at the end of timer send the offline event
timerId = setTimeout(function(){
cordova.fireDocumentEvent("offline");
timerId = null;
}, timeout);
} else {
// If there is a current offline event pending clear it
if (timerId !== null) {
clearTimeout(timerId);
timerId = null;
}
cordova.fireDocumentEvent("online");
}
// should only fire this once
if (channel.onCordovaConnectionReady.state !== 2) {
channel.onCordovaConnectionReady.fire();
}
},
function (e) {
// If we can't get the network info we should still tell Cordova
// to fire the deviceready event.
if (channel.onCordovaConnectionReady.state !== 2) {
channel.onCordovaConnectionReady.fire();
}
console.log("Error initializing Network Connection: " + e);
});
});
module.exports = me;
});

View File

@ -0,0 +1,121 @@
cordova.define("cordova-plugin-vibration.notification", function(require, exports, module) { /*
*
* 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 exec = require('cordova/exec');
/**
* Provides access to the vibration mechanism on the device.
*/
module.exports = {
/**
* Vibrates the device for a given amount of time or for a given pattern or immediately cancels any ongoing vibrations (depending on the parameter).
*
* @param {Integer} param The number of milliseconds to vibrate (if 0, cancels vibration)
*
*
* @param {Array of Integer} param Pattern with which to vibrate the device.
* Pass in an array of integers that
* are the durations for which to
* turn on or off the vibrator in
* milliseconds. The FIRST value
* indicates the
* number of milliseconds for which
* to keep the vibrator ON before
* turning it off. The NEXT value indicates the
* number of milliseconds for which
* to keep the vibrator OFF before
* turning it on. Subsequent values
* alternate between durations in
* milliseconds to turn the vibrator
* off or to turn the vibrator on.
* (if empty, cancels vibration)
*/
vibrate: function(param) {
/* Aligning with w3c spec */
//vibrate
if ((typeof param == 'number') && param != 0)
exec(null, null, "Vibration", "vibrate", [param]);
//vibrate with array ( i.e. vibrate([3000]) )
else if ((typeof param == 'object') && param.length == 1)
{
//cancel if vibrate([0])
if (param[0] == 0)
exec(null, null, "Vibration", "cancelVibration", []);
//else vibrate
else
exec(null, null, "Vibration", "vibrate", [param[0]]);
}
//vibrate with a pattern
else if ((typeof param == 'object') && param.length > 1)
{
var repeat = -1; //no repeat
exec(null, null, "Vibration", "vibrateWithPattern", [param, repeat]);
}
//cancel vibration (param = 0 or [])
else
exec(null, null, "Vibration", "cancelVibration", []);
},
/**
* Vibrates the device with a given pattern.
*
* @param {Array of Integer} pattern Pattern with which to vibrate the device.
* Pass in an array of integers that
* are the durations for which to
* turn on or off the vibrator in
* milliseconds. The first value
* indicates the number of milliseconds
* to wait before turning the vibrator
* on. The next value indicates the
* number of milliseconds for which
* to keep the vibrator on before
* turning it off. Subsequent values
* alternate between durations in
* milliseconds to turn the vibrator
* off or to turn the vibrator on.
*
* @param {Integer} repeat Optional index into the pattern array at which
* to start repeating (will repeat until canceled),
* or -1 for no repetition (default).
*/
vibrateWithPattern: function(pattern, repeat) {
repeat = (typeof repeat !== "undefined") ? repeat : -1;
pattern.unshift(0); //add a 0 at beginning for backwards compatibility from w3c spec
exec(null, null, "Vibration", "vibrateWithPattern", [pattern, repeat]);
},
/**
* Immediately cancels any currently running vibration.
*/
cancelVibration: function() {
exec(null, null, "Vibration", "cancelVibration", []);
}
};
});

View File

@ -0,0 +1,29 @@
cordova.define("cordova-plugin-whitelist.whitelist", function(require, exports, module) { /*
* 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.
*
*/
if (!document.querySelector('meta[http-equiv=Content-Security-Policy]')) {
var msg = 'No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.';
console.error(msg);
setInterval(function() {
console.warn(msg);
}, 10000);
}
});

View File

@ -5,14 +5,11 @@ import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import com.squareup.leakcanary.RefWatcher;
@ -30,7 +27,6 @@ import org.apache.cordova.PluginManager;
import java.util.ArrayList;
import java.util.Locale;
import io.syng.R;
import io.syng.app.SyngApplication;
@ -44,6 +40,14 @@ public class WebViewFragment extends Fragment {
protected boolean keepRunning = true;
protected boolean immersiveMode;
private static String js_cordova = ""
+"var script = document.createElement('script'); "
+"script.setAttribute('type','text/javascript'); "
+"script.setAttribute('async','async'); "
+"script.setAttribute('src','file:///android_asset/www/cordova.js'); "
+"(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);"
+"";
// protected View view;
@Override
@ -186,6 +190,8 @@ public class WebViewFragment extends Fragment {
e.printStackTrace();
}
*/
} else if ("onPageFinished".equals(id)) {
webView.getEngine().loadUrl("javascript: " + js_cordova, false);
} else if ("exit".equals(id)) {
getActivity().finish();
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,185 @@
/*
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.
*/
package org.apache.cordova.camera;
import java.io.IOException;
import android.media.ExifInterface;
public class ExifHelper {
private String aperture = null;
private String datetime = null;
private String exposureTime = null;
private String flash = null;
private String focalLength = null;
private String gpsAltitude = null;
private String gpsAltitudeRef = null;
private String gpsDateStamp = null;
private String gpsLatitude = null;
private String gpsLatitudeRef = null;
private String gpsLongitude = null;
private String gpsLongitudeRef = null;
private String gpsProcessingMethod = null;
private String gpsTimestamp = null;
private String iso = null;
private String make = null;
private String model = null;
private String orientation = null;
private String whiteBalance = null;
private ExifInterface inFile = null;
private ExifInterface outFile = null;
/**
* The file before it is compressed
*
* @param filePath
* @throws IOException
*/
public void createInFile(String filePath) throws IOException {
this.inFile = new ExifInterface(filePath);
}
/**
* The file after it has been compressed
*
* @param filePath
* @throws IOException
*/
public void createOutFile(String filePath) throws IOException {
this.outFile = new ExifInterface(filePath);
}
/**
* Reads all the EXIF data from the input file.
*/
public void readExifData() {
this.aperture = inFile.getAttribute(ExifInterface.TAG_APERTURE);
this.datetime = inFile.getAttribute(ExifInterface.TAG_DATETIME);
this.exposureTime = inFile.getAttribute(ExifInterface.TAG_EXPOSURE_TIME);
this.flash = inFile.getAttribute(ExifInterface.TAG_FLASH);
this.focalLength = inFile.getAttribute(ExifInterface.TAG_FOCAL_LENGTH);
this.gpsAltitude = inFile.getAttribute(ExifInterface.TAG_GPS_ALTITUDE);
this.gpsAltitudeRef = inFile.getAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF);
this.gpsDateStamp = inFile.getAttribute(ExifInterface.TAG_GPS_DATESTAMP);
this.gpsLatitude = inFile.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
this.gpsLatitudeRef = inFile.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
this.gpsLongitude = inFile.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
this.gpsLongitudeRef = inFile.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
this.gpsProcessingMethod = inFile.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD);
this.gpsTimestamp = inFile.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP);
this.iso = inFile.getAttribute(ExifInterface.TAG_ISO);
this.make = inFile.getAttribute(ExifInterface.TAG_MAKE);
this.model = inFile.getAttribute(ExifInterface.TAG_MODEL);
this.orientation = inFile.getAttribute(ExifInterface.TAG_ORIENTATION);
this.whiteBalance = inFile.getAttribute(ExifInterface.TAG_WHITE_BALANCE);
}
/**
* Writes the previously stored EXIF data to the output file.
*
* @throws IOException
*/
public void writeExifData() throws IOException {
// Don't try to write to a null file
if (this.outFile == null) {
return;
}
if (this.aperture != null) {
this.outFile.setAttribute(ExifInterface.TAG_APERTURE, this.aperture);
}
if (this.datetime != null) {
this.outFile.setAttribute(ExifInterface.TAG_DATETIME, this.datetime);
}
if (this.exposureTime != null) {
this.outFile.setAttribute(ExifInterface.TAG_EXPOSURE_TIME, this.exposureTime);
}
if (this.flash != null) {
this.outFile.setAttribute(ExifInterface.TAG_FLASH, this.flash);
}
if (this.focalLength != null) {
this.outFile.setAttribute(ExifInterface.TAG_FOCAL_LENGTH, this.focalLength);
}
if (this.gpsAltitude != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_ALTITUDE, this.gpsAltitude);
}
if (this.gpsAltitudeRef != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF, this.gpsAltitudeRef);
}
if (this.gpsDateStamp != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, this.gpsDateStamp);
}
if (this.gpsLatitude != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_LATITUDE, this.gpsLatitude);
}
if (this.gpsLatitudeRef != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, this.gpsLatitudeRef);
}
if (this.gpsLongitude != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, this.gpsLongitude);
}
if (this.gpsLongitudeRef != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, this.gpsLongitudeRef);
}
if (this.gpsProcessingMethod != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD, this.gpsProcessingMethod);
}
if (this.gpsTimestamp != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, this.gpsTimestamp);
}
if (this.iso != null) {
this.outFile.setAttribute(ExifInterface.TAG_ISO, this.iso);
}
if (this.make != null) {
this.outFile.setAttribute(ExifInterface.TAG_MAKE, this.make);
}
if (this.model != null) {
this.outFile.setAttribute(ExifInterface.TAG_MODEL, this.model);
}
if (this.orientation != null) {
this.outFile.setAttribute(ExifInterface.TAG_ORIENTATION, this.orientation);
}
if (this.whiteBalance != null) {
this.outFile.setAttribute(ExifInterface.TAG_WHITE_BALANCE, this.whiteBalance);
}
this.outFile.saveAttributes();
}
public int getOrientation() {
int o = Integer.parseInt(this.orientation);
if (o == ExifInterface.ORIENTATION_NORMAL) {
return 0;
} else if (o == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (o == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (o == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
} else {
return 0;
}
}
public void resetOrientation() {
this.orientation = "" + ExifInterface.ORIENTATION_NORMAL;
}
}

View File

@ -0,0 +1,231 @@
/*
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.
*/
package org.apache.cordova.camera;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.LOG;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
public class FileHelper {
private static final String LOG_TAG = "FileUtils";
private static final String _DATA = "_data";
/**
* Returns the real path of the given URI string.
* If the given URI string represents a content:// URI, the real path is retrieved from the media store.
*
* @param uriString the URI string of the audio/image/video
* @param cordova the current application context
* @return the full path to the file
*/
@SuppressWarnings("deprecation")
public static String getRealPath(Uri uri, CordovaInterface cordova) {
String realPath = null;
if (Build.VERSION.SDK_INT < 11)
realPath = FileHelper.getRealPathFromURI_BelowAPI11(cordova.getActivity(), uri);
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
realPath = FileHelper.getRealPathFromURI_API11to18(cordova.getActivity(), uri);
// SDK > 19 (Android 4.4)
else
realPath = FileHelper.getRealPathFromURI_API19(cordova.getActivity(), uri);
return realPath;
}
/**
* Returns the real path of the given URI.
* If the given URI is a content:// URI, the real path is retrieved from the media store.
*
* @param uri the URI of the audio/image/video
* @param cordova the current application context
* @return the full path to the file
*/
public static String getRealPath(String uriString, CordovaInterface cordova) {
return FileHelper.getRealPath(Uri.parse(uriString), cordova);
}
@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
try {
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.indexOf(":") > -1 ? wholeID.split(":")[1] : wholeID.indexOf(";") > -1 ? wholeID
.split(";")[1] : wholeID;
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column,
sel, new String[] { id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
} catch (Exception e) {
filePath = "";
}
return filePath;
}
@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
try {
CursorLoader cursorLoader = new CursorLoader(context, contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
} catch (Exception e) {
result = null;
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
try {
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
} catch (Exception e) {
result = null;
}
return result;
}
/**
* Returns an input stream based on given URI string.
*
* @param uriString the URI string from which to obtain the input stream
* @param cordova the current application context
* @return an input stream into the data at the given URI or null if given an invalid URI string
* @throws IOException
*/
public static InputStream getInputStreamFromUriString(String uriString, CordovaInterface cordova)
throws IOException {
InputStream returnValue = null;
if (uriString.startsWith("content")) {
Uri uri = Uri.parse(uriString);
returnValue = cordova.getActivity().getContentResolver().openInputStream(uri);
} else if (uriString.startsWith("file://")) {
int question = uriString.indexOf("?");
if (question > -1) {
uriString = uriString.substring(0, question);
}
if (uriString.startsWith("file:///android_asset/")) {
Uri uri = Uri.parse(uriString);
String relativePath = uri.getPath().substring(15);
returnValue = cordova.getActivity().getAssets().open(relativePath);
} else {
// might still be content so try that first
try {
returnValue = cordova.getActivity().getContentResolver().openInputStream(Uri.parse(uriString));
} catch (Exception e) {
returnValue = null;
}
if (returnValue == null) {
returnValue = new FileInputStream(getRealPath(uriString, cordova));
}
}
} else {
returnValue = new FileInputStream(uriString);
}
return returnValue;
}
/**
* Removes the "file://" prefix from the given URI string, if applicable.
* If the given URI string doesn't have a "file://" prefix, it is returned unchanged.
*
* @param uriString the URI string to operate on
* @return a path without the "file://" prefix
*/
public static String stripFileProtocol(String uriString) {
if (uriString.startsWith("file://")) {
uriString = uriString.substring(7);
}
return uriString;
}
public static String getMimeTypeForExtension(String path) {
String extension = path;
int lastDot = extension.lastIndexOf('.');
if (lastDot != -1) {
extension = extension.substring(lastDot + 1);
}
// Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
extension = extension.toLowerCase(Locale.getDefault());
if (extension.equals("3ga")) {
return "audio/3gpp";
}
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
/**
* Returns the mime type of the data specified by the given URI string.
*
* @param uriString the URI string of the data
* @return the mime type of the specified data
*/
public static String getMimeType(String uriString, CordovaInterface cordova) {
String mimeType = null;
Uri uri = Uri.parse(uriString);
if (uriString.startsWith("content://")) {
mimeType = cordova.getActivity().getContentResolver().getType(uri);
} else {
mimeType = getMimeTypeForExtension(uri.getPath());
}
return mimeType;
}
}

View File

@ -0,0 +1,161 @@
/*
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.
*/
package org.apache.cordova.device;
import java.util.TimeZone;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.provider.Settings;
public class Device extends CordovaPlugin {
public static final String TAG = "Device";
public static String platform; // Device OS
public static String uuid; // Device UUID
private static final String ANDROID_PLATFORM = "Android";
private static final String AMAZON_PLATFORM = "amazon-fireos";
private static final String AMAZON_DEVICE = "Amazon";
/**
* Constructor.
*/
public Device() {
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
Device.uuid = getUuid();
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback id used when calling back into JavaScript.
* @return True if the action was valid, false if not.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("getDeviceInfo")) {
JSONObject r = new JSONObject();
r.put("uuid", Device.uuid);
r.put("version", this.getOSVersion());
r.put("platform", this.getPlatform());
r.put("model", this.getModel());
r.put("manufacturer", this.getManufacturer());
callbackContext.success(r);
}
else {
return false;
}
return true;
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Get the OS name.
*
* @return
*/
public String getPlatform() {
String platform;
if (isAmazonDevice()) {
platform = AMAZON_PLATFORM;
} else {
platform = ANDROID_PLATFORM;
}
return platform;
}
/**
* Get the device's Universally Unique Identifier (UUID).
*
* @return
*/
public String getUuid() {
String uuid = Settings.Secure.getString(this.cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
return uuid;
}
public String getModel() {
String model = android.os.Build.MODEL;
return model;
}
public String getProductName() {
String productname = android.os.Build.PRODUCT;
return productname;
}
public String getManufacturer() {
String manufacturer = android.os.Build.MANUFACTURER;
return manufacturer;
}
/**
* Get the OS version.
*
* @return
*/
public String getOSVersion() {
String osversion = android.os.Build.VERSION.RELEASE;
return osversion;
}
public String getSDKVersion() {
@SuppressWarnings("deprecation")
String sdkversion = android.os.Build.VERSION.SDK;
return sdkversion;
}
public String getTimeZoneID() {
TimeZone tz = TimeZone.getDefault();
return (tz.getID());
}
/**
* Function to check if the device is manufactured by Amazon
*
* @return
*/
public boolean isAmazonDevice() {
if (android.os.Build.MANUFACTURER.equals(AMAZON_DEVICE)) {
return true;
}
return false;
}
}

View File

@ -0,0 +1,306 @@
/*
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.
*/
package org.apache.cordova.devicemotion;
import java.util.List;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Looper;
/**
* This class listens to the accelerometer sensor and stores the latest
* acceleration values x,y,z.
*/
public class AccelListener extends CordovaPlugin implements SensorEventListener {
public static int STOPPED = 0;
public static int STARTING = 1;
public static int RUNNING = 2;
public static int ERROR_FAILED_TO_START = 3;
private float x,y,z; // most recent acceleration values
private long timestamp; // time of most recent value
private int status; // status of listener
private int accuracy = SensorManager.SENSOR_STATUS_UNRELIABLE;
private SensorManager sensorManager; // Sensor manager
private Sensor mSensor; // Acceleration sensor returned by sensor manager
private CallbackContext callbackContext; // Keeps track of the JS callback context.
private Handler mainHandler=null;
private Runnable mainRunnable =new Runnable() {
public void run() {
AccelListener.this.timeout();
}
};
/**
* Create an accelerometer listener.
*/
public AccelListener() {
this.x = 0;
this.y = 0;
this.z = 0;
this.timestamp = 0;
this.setStatus(AccelListener.STOPPED);
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param webView The associated CordovaWebView.
*/
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE);
}
/**
* Executes the request.
*
* @param action The action to execute.
* @param args The exec() arguments.
* @param callbackId The callback id used when calling back into JavaScript.
* @return Whether the action was valid.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
if (action.equals("start")) {
this.callbackContext = callbackContext;
if (this.status != AccelListener.RUNNING) {
// If not running, then this is an async call, so don't worry about waiting
// We drop the callback onto our stack, call start, and let start and the sensor callback fire off the callback down the road
this.start();
}
}
else if (action.equals("stop")) {
if (this.status == AccelListener.RUNNING) {
this.stop();
}
} else {
// Unsupported action
return false;
}
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT, "");
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
return true;
}
/**
* Called by AccelBroker when listener is to be shut down.
* Stop listener.
*/
public void onDestroy() {
this.stop();
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
//
/**
* Start listening for acceleration sensor.
*
* @return status of listener
*/
private int start() {
// If already starting or running, then restart timeout and return
if ((this.status == AccelListener.RUNNING) || (this.status == AccelListener.STARTING)) {
startTimeout();
return this.status;
}
this.setStatus(AccelListener.STARTING);
// Get accelerometer from sensor manager
List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
// If found, then register as listener
if ((list != null) && (list.size() > 0)) {
this.mSensor = list.get(0);
if (this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_UI)) {
this.setStatus(AccelListener.STARTING);
} else {
this.setStatus(AccelListener.ERROR_FAILED_TO_START);
this.fail(AccelListener.ERROR_FAILED_TO_START, "Device sensor returned an error.");
return this.status;
};
} else {
this.setStatus(AccelListener.ERROR_FAILED_TO_START);
this.fail(AccelListener.ERROR_FAILED_TO_START, "No sensors found to register accelerometer listening to.");
return this.status;
}
startTimeout();
return this.status;
}
private void startTimeout() {
// Set a timeout callback on the main thread.
stopTimeout();
mainHandler = new Handler(Looper.getMainLooper());
mainHandler.postDelayed(mainRunnable, 2000);
}
private void stopTimeout() {
if(mainHandler!=null){
mainHandler.removeCallbacks(mainRunnable);
}
}
/**
* Stop listening to acceleration sensor.
*/
private void stop() {
stopTimeout();
if (this.status != AccelListener.STOPPED) {
this.sensorManager.unregisterListener(this);
}
this.setStatus(AccelListener.STOPPED);
this.accuracy = SensorManager.SENSOR_STATUS_UNRELIABLE;
}
/**
* Returns latest cached position if the sensor hasn't returned newer value.
*
* Called two seconds after starting the listener.
*/
private void timeout() {
if (this.status == AccelListener.STARTING) {
// call win with latest cached position
this.timestamp = System.currentTimeMillis();
this.win();
}
}
/**
* Called when the accuracy of the sensor has changed.
*
* @param sensor
* @param accuracy
*/
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Only look at accelerometer events
if (sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return;
}
// If not running, then just return
if (this.status == AccelListener.STOPPED) {
return;
}
this.accuracy = accuracy;
}
/**
* Sensor listener event.
*
* @param SensorEvent event
*/
public void onSensorChanged(SensorEvent event) {
// Only look at accelerometer events
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return;
}
// If not running, then just return
if (this.status == AccelListener.STOPPED) {
return;
}
this.setStatus(AccelListener.RUNNING);
if (this.accuracy >= SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM) {
// Save time that event was received
this.timestamp = System.currentTimeMillis();
this.x = event.values[0];
this.y = event.values[1];
this.z = event.values[2];
this.win();
}
}
/**
* Called when the view navigates.
*/
@Override
public void onReset() {
if (this.status == AccelListener.RUNNING) {
this.stop();
}
}
// Sends an error back to JS
private void fail(int code, String message) {
// Error object
JSONObject errorObj = new JSONObject();
try {
errorObj.put("code", code);
errorObj.put("message", message);
} catch (JSONException e) {
e.printStackTrace();
}
PluginResult err = new PluginResult(PluginResult.Status.ERROR, errorObj);
err.setKeepCallback(true);
callbackContext.sendPluginResult(err);
}
private void win() {
// Success return object
PluginResult result = new PluginResult(PluginResult.Status.OK, this.getAccelerationJSON());
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
}
private void setStatus(int status) {
this.status = status;
}
private JSONObject getAccelerationJSON() {
JSONObject r = new JSONObject();
try {
r.put("x", this.x);
r.put("y", this.y);
r.put("z", this.z);
r.put("timestamp", this.timestamp);
} catch (JSONException e) {
e.printStackTrace();
}
return r;
}
}

View File

@ -0,0 +1,296 @@
/*
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.
*/
package org.apache.cordova.deviceorientation;
import java.util.List;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
/**
* This class listens to the compass sensor and stores the latest heading value.
*/
public class CompassListener extends CordovaPlugin implements SensorEventListener {
public static int STOPPED = 0;
public static int STARTING = 1;
public static int RUNNING = 2;
public static int ERROR_FAILED_TO_START = 3;
public long TIMEOUT = 30000; // Timeout in msec to shut off listener
int status; // status of listener
float heading; // most recent heading value
long timeStamp; // time of most recent value
long lastAccessTime; // time the value was last retrieved
int accuracy; // accuracy of the sensor
private SensorManager sensorManager;// Sensor manager
Sensor mSensor; // Compass sensor returned by sensor manager
private CallbackContext callbackContext;
/**
* Constructor.
*/
public CompassListener() {
this.heading = 0;
this.timeStamp = 0;
this.setStatus(CompassListener.STOPPED);
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE);
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackS=Context The callback id used when calling back into JavaScript.
* @return True if the action was valid.
* @throws JSONException
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("start")) {
this.start();
}
else if (action.equals("stop")) {
this.stop();
}
else if (action.equals("getStatus")) {
int i = this.getStatus();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, i));
}
else if (action.equals("getHeading")) {
// If not running, then this is an async call, so don't worry about waiting
if (this.status != CompassListener.RUNNING) {
int r = this.start();
if (r == CompassListener.ERROR_FAILED_TO_START) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, CompassListener.ERROR_FAILED_TO_START));
return true;
}
// Set a timeout callback on the main thread.
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
CompassListener.this.timeout();
}
}, 2000);
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, getCompassHeading()));
}
else if (action.equals("setTimeout")) {
this.setTimeout(args.getLong(0));
}
else if (action.equals("getTimeout")) {
long l = this.getTimeout();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l));
} else {
// Unsupported action
return false;
}
return true;
}
/**
* Called when listener is to be shut down and object is being destroyed.
*/
public void onDestroy() {
this.stop();
}
/**
* Called when app has navigated and JS listeners have been destroyed.
*/
public void onReset() {
this.stop();
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Start listening for compass sensor.
*
* @return status of listener
*/
public int start() {
// If already starting or running, then just return
if ((this.status == CompassListener.RUNNING) || (this.status == CompassListener.STARTING)) {
return this.status;
}
// Get compass sensor from sensor manager
@SuppressWarnings("deprecation")
List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
// If found, then register as listener
if (list != null && list.size() > 0) {
this.mSensor = list.get(0);
this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_NORMAL);
this.lastAccessTime = System.currentTimeMillis();
this.setStatus(CompassListener.STARTING);
}
// If error, then set status to error
else {
this.setStatus(CompassListener.ERROR_FAILED_TO_START);
}
return this.status;
}
/**
* Stop listening to compass sensor.
*/
public void stop() {
if (this.status != CompassListener.STOPPED) {
this.sensorManager.unregisterListener(this);
}
this.setStatus(CompassListener.STOPPED);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
/**
* Called after a delay to time out if the listener has not attached fast enough.
*/
private void timeout() {
if (this.status == CompassListener.STARTING) {
this.setStatus(CompassListener.ERROR_FAILED_TO_START);
if (this.callbackContext != null) {
this.callbackContext.error("Compass listener failed to start.");
}
}
}
/**
* Sensor listener event.
*
* @param SensorEvent event
*/
public void onSensorChanged(SensorEvent event) {
// We only care about the orientation as far as it refers to Magnetic North
float heading = event.values[0];
// Save heading
this.timeStamp = System.currentTimeMillis();
this.heading = heading;
this.setStatus(CompassListener.RUNNING);
// If heading hasn't been read for TIMEOUT time, then turn off compass sensor to save power
if ((this.timeStamp - this.lastAccessTime) > this.TIMEOUT) {
this.stop();
}
}
/**
* Get status of compass sensor.
*
* @return status
*/
public int getStatus() {
return this.status;
}
/**
* Get the most recent compass heading.
*
* @return heading
*/
public float getHeading() {
this.lastAccessTime = System.currentTimeMillis();
return this.heading;
}
/**
* Set the timeout to turn off compass sensor if getHeading() hasn't been called.
*
* @param timeout Timeout in msec.
*/
public void setTimeout(long timeout) {
this.TIMEOUT = timeout;
}
/**
* Get the timeout to turn off compass sensor if getHeading() hasn't been called.
*
* @return timeout in msec
*/
public long getTimeout() {
return this.TIMEOUT;
}
/**
* Set the status and send it to JavaScript.
* @param status
*/
private void setStatus(int status) {
this.status = status;
}
/**
* Create the CompassHeading JSON object to be returned to JavaScript
*
* @return a compass heading
*/
private JSONObject getCompassHeading() throws JSONException {
JSONObject obj = new JSONObject();
obj.put("magneticHeading", this.getHeading());
obj.put("trueHeading", this.getHeading());
// Since the magnetic and true heading are always the same our and accuracy
// is defined as the difference between true and magnetic always return zero
obj.put("headingAccuracy", 0);
obj.put("timestamp", this.timeStamp);
return obj;
}
}

View File

@ -0,0 +1,483 @@
/*
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.
*/
package org.apache.cordova.dialogs;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.EditText;
import android.widget.TextView;
/**
* This class provides access to notifications on the device.
*
* Be aware that this implementation gets called on
* navigator.notification.{alert|confirm|prompt}, and that there is a separate
* implementation in org.apache.cordova.CordovaChromeClient that gets
* called on a simple window.{alert|confirm|prompt}.
*/
public class Notification extends CordovaPlugin {
public int confirmResult = -1;
public ProgressDialog spinnerDialog = null;
public ProgressDialog progressDialog = null;
/**
* Constructor.
*/
public Notification() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArray of arguments for the plugin.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return True when the action was valid, false otherwise.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
/*
* Don't run any of these if the current activity is finishing
* in order to avoid android.view.WindowManager$BadTokenException
* crashing the app. Just return true here since false should only
* be returned in the event of an invalid action.
*/
if(this.cordova.getActivity().isFinishing()) return true;
if (action.equals("beep")) {
this.beep(args.getLong(0));
}
else if (action.equals("alert")) {
this.alert(args.getString(0), args.getString(1), args.getString(2), callbackContext);
return true;
}
else if (action.equals("confirm")) {
this.confirm(args.getString(0), args.getString(1), args.getJSONArray(2), callbackContext);
return true;
}
else if (action.equals("prompt")) {
this.prompt(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), callbackContext);
return true;
}
else if (action.equals("activityStart")) {
this.activityStart(args.getString(0), args.getString(1));
}
else if (action.equals("activityStop")) {
this.activityStop();
}
else if (action.equals("progressStart")) {
this.progressStart(args.getString(0), args.getString(1));
}
else if (action.equals("progressValue")) {
this.progressValue(args.getInt(0));
}
else if (action.equals("progressStop")) {
this.progressStop();
}
else {
return false;
}
// Only alert and confirm are async.
callbackContext.success();
return true;
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Beep plays the default notification ringtone.
*
* @param count Number of times to play notification
*/
public void beep(final long count) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone notification = RingtoneManager.getRingtone(cordova.getActivity().getBaseContext(), ringtone);
// If phone is not set to silent mode
if (notification != null) {
for (long i = 0; i < count; ++i) {
notification.play();
long timeout = 5000;
while (notification.isPlaying() && (timeout > 0)) {
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
}
}
});
}
/**
* Builds and shows a native Android alert with given Strings
* @param message The message the alert should display
* @param title The title of the alert
* @param buttonLabel The label of the button
* @param callbackContext The callback context
*/
public synchronized void alert(final String message, final String title, final String buttonLabel, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
dlg.setPositiveButton(buttonLabel,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
changeTextDirection(dlg);
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Builds and shows a native Android confirm dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The index of the button pressed will be returned to the JavaScript callback identified by callbackId.
*
* @param message The message the dialog should display
* @param title The title of the dialog
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackContext The callback context.
*/
public synchronized void confirm(final String message, final String title, final JSONArray buttonLabels, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
// First button
if (buttonLabels.length() > 0) {
try {
dlg.setNegativeButton(buttonLabels.getString(0),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1));
}
});
} catch (JSONException e) { }
}
// Second button
if (buttonLabels.length() > 1) {
try {
dlg.setNeutralButton(buttonLabels.getString(1),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2));
}
});
} catch (JSONException e) { }
}
// Third button
if (buttonLabels.length() > 2) {
try {
dlg.setPositiveButton(buttonLabels.getString(2),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3));
}
});
} catch (JSONException e) { }
}
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
changeTextDirection(dlg);
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Builds and shows a native Android prompt dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The following results are returned to the JavaScript callback identified by callbackId:
* buttonIndex Index number of the button selected
* input1 The text entered in the prompt dialog box
*
* @param message The message the dialog should display
* @param title The title of the dialog
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackContext The callback context.
*/
public synchronized void prompt(final String message, final String title, final JSONArray buttonLabels, final String defaultText, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
final EditText promptInput = new EditText(cordova.getActivity());
promptInput.setHint(defaultText);
AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
dlg.setView(promptInput);
final JSONObject result = new JSONObject();
// First button
if (buttonLabels.length() > 0) {
try {
dlg.setNegativeButton(buttonLabels.getString(0),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",1);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) { e.printStackTrace(); }
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) { }
}
// Second button
if (buttonLabels.length() > 1) {
try {
dlg.setNeutralButton(buttonLabels.getString(1),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",2);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) { e.printStackTrace(); }
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) { }
}
// Third button
if (buttonLabels.length() > 2) {
try {
dlg.setPositiveButton(buttonLabels.getString(2),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",3);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) { e.printStackTrace(); }
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) { }
}
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog){
dialog.dismiss();
try {
result.put("buttonIndex",0);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) { e.printStackTrace(); }
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
changeTextDirection(dlg);
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Show the spinner.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void activityStart(final String title, final String message) {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
final Notification notification = this;
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
notification.spinnerDialog = createProgressDialog(cordova); // new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
notification.spinnerDialog.setTitle(title);
notification.spinnerDialog.setMessage(message);
notification.spinnerDialog.setCancelable(true);
notification.spinnerDialog.setIndeterminate(true);
notification.spinnerDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.spinnerDialog = null;
}
});
notification.spinnerDialog.show();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Stop spinner.
*/
public synchronized void activityStop() {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
}
/**
* Show the progress dialog.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void progressStart(final String title, final String message) {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
final Notification notification = this;
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
notification.progressDialog = createProgressDialog(cordova); // new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
notification.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
notification.progressDialog.setTitle(title);
notification.progressDialog.setMessage(message);
notification.progressDialog.setCancelable(true);
notification.progressDialog.setMax(100);
notification.progressDialog.setProgress(0);
notification.progressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.progressDialog = null;
}
});
notification.progressDialog.show();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Set value of progress bar.
*
* @param value 0-100
*/
public synchronized void progressValue(int value) {
if (this.progressDialog != null) {
this.progressDialog.setProgress(value);
}
}
/**
* Stop progress dialog.
*/
public synchronized void progressStop() {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
}
@SuppressLint("NewApi")
private AlertDialog.Builder createDialog(CordovaInterface cordova) {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) {
return new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
} else {
return new AlertDialog.Builder(cordova.getActivity());
}
}
@SuppressLint("InlinedApi")
private ProgressDialog createProgressDialog(CordovaInterface cordova) {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
} else {
return new ProgressDialog(cordova.getActivity());
}
}
@SuppressLint("NewApi")
private void changeTextDirection(Builder dlg){
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
dlg.create();
AlertDialog dialog = dlg.show();
if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
TextView messageview = (TextView)dialog.findViewById(android.R.id.message);
messageview.setTextDirection(android.view.View.TEXT_DIRECTION_LOCALE);
}
}
}

View File

@ -0,0 +1,267 @@
/*
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.
*/
package org.apache.cordova.networkinformation;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class NetworkManager extends CordovaPlugin {
public static int NOT_REACHABLE = 0;
public static int REACHABLE_VIA_CARRIER_DATA_NETWORK = 1;
public static int REACHABLE_VIA_WIFI_NETWORK = 2;
public static final String WIFI = "wifi";
public static final String WIMAX = "wimax";
// mobile
public static final String MOBILE = "mobile";
// Android L calls this Cellular, because I have no idea!
public static final String CELLULAR = "cellular";
// 2G network types
public static final String GSM = "gsm";
public static final String GPRS = "gprs";
public static final String EDGE = "edge";
// 3G network types
public static final String CDMA = "cdma";
public static final String UMTS = "umts";
public static final String HSPA = "hspa";
public static final String HSUPA = "hsupa";
public static final String HSDPA = "hsdpa";
public static final String ONEXRTT = "1xrtt";
public static final String EHRPD = "ehrpd";
// 4G network types
public static final String LTE = "lte";
public static final String UMB = "umb";
public static final String HSPA_PLUS = "hspa+";
// return type
public static final String TYPE_UNKNOWN = "unknown";
public static final String TYPE_ETHERNET = "ethernet";
public static final String TYPE_WIFI = "wifi";
public static final String TYPE_2G = "2g";
public static final String TYPE_3G = "3g";
public static final String TYPE_4G = "4g";
public static final String TYPE_NONE = "none";
private static final String LOG_TAG = "NetworkManager";
private CallbackContext connectionCallbackContext;
ConnectivityManager sockMan;
BroadcastReceiver receiver;
private JSONObject lastInfo = null;
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.sockMan = (ConnectivityManager) cordova.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
this.connectionCallbackContext = null;
// We need to listen to connectivity events to update navigator.connection
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
if (this.receiver == null) {
this.receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// (The null check is for the ARM Emulator, please use Intel Emulator for better results)
if(NetworkManager.this.webView != null)
updateConnectionInfo(sockMan.getActiveNetworkInfo());
}
};
webView.getContext().registerReceiver(this.receiver, intentFilter);
}
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback id used when calling back into JavaScript.
* @return True if the action was valid, false otherwise.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
if (action.equals("getConnectionInfo")) {
this.connectionCallbackContext = callbackContext;
NetworkInfo info = sockMan.getActiveNetworkInfo();
String connectionType = "";
try {
connectionType = this.getConnectionInfo(info).get("type").toString();
} catch (JSONException e) { }
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, connectionType);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
}
return false;
}
/**
* Stop network receiver.
*/
public void onDestroy() {
if (this.receiver != null) {
try {
webView.getContext().unregisterReceiver(this.receiver);
} catch (Exception e) {
Log.e(LOG_TAG, "Error unregistering network receiver: " + e.getMessage(), e);
} finally {
receiver = null;
}
}
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Updates the JavaScript side whenever the connection changes
*
* @param info the current active network info
* @return
*/
private void updateConnectionInfo(NetworkInfo info) {
// send update to javascript "navigator.network.connection"
// Jellybean sends its own info
JSONObject thisInfo = this.getConnectionInfo(info);
if(!thisInfo.equals(lastInfo))
{
String connectionType = "";
try {
connectionType = thisInfo.get("type").toString();
} catch (JSONException e) { }
sendUpdate(connectionType);
lastInfo = thisInfo;
}
}
/**
* Get the latest network connection information
*
* @param info the current active network info
* @return a JSONObject that represents the network info
*/
private JSONObject getConnectionInfo(NetworkInfo info) {
String type = TYPE_NONE;
String extraInfo = "";
if (info != null) {
// If we are not connected to any network set type to none
if (!info.isConnected()) {
type = TYPE_NONE;
}
else {
type = getType(info);
}
extraInfo = info.getExtraInfo();
}
Log.d("CordovaNetworkManager", "Connection Type: " + type);
Log.d("CordovaNetworkManager", "Connection Extra Info: " + extraInfo);
JSONObject connectionInfo = new JSONObject();
try {
connectionInfo.put("type", type);
connectionInfo.put("extraInfo", extraInfo);
} catch (JSONException e) { }
return connectionInfo;
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param connection the network info to set as navigator.connection
*/
private void sendUpdate(String type) {
if (connectionCallbackContext != null) {
PluginResult result = new PluginResult(PluginResult.Status.OK, type);
result.setKeepCallback(true);
connectionCallbackContext.sendPluginResult(result);
}
webView.postMessage("networkconnection", type);
}
/**
* Determine the type of connection
*
* @param info the network info so we can determine connection type.
* @return the type of mobile network we are on
*/
private String getType(NetworkInfo info) {
if (info != null) {
String type = info.getTypeName();
if (type.toLowerCase().equals(WIFI)) {
return TYPE_WIFI;
}
else if (type.toLowerCase().equals(MOBILE) || type.toLowerCase().equals(CELLULAR)) {
type = info.getSubtypeName();
if (type.toLowerCase().equals(GSM) ||
type.toLowerCase().equals(GPRS) ||
type.toLowerCase().equals(EDGE)) {
return TYPE_2G;
}
else if (type.toLowerCase().startsWith(CDMA) ||
type.toLowerCase().equals(UMTS) ||
type.toLowerCase().equals(ONEXRTT) ||
type.toLowerCase().equals(EHRPD) ||
type.toLowerCase().equals(HSUPA) ||
type.toLowerCase().equals(HSDPA) ||
type.toLowerCase().equals(HSPA)) {
return TYPE_3G;
}
else if (type.toLowerCase().equals(LTE) ||
type.toLowerCase().equals(UMB) ||
type.toLowerCase().equals(HSPA_PLUS)) {
return TYPE_4G;
}
}
}
else {
return TYPE_NONE;
}
return TYPE_UNKNOWN;
}
}

View File

@ -0,0 +1,133 @@
/*
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.
*/
package org.apache.cordova.vibration;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.os.Vibrator;
import android.media.AudioManager;
/**
* This class provides access to vibration on the device.
*/
public class Vibration extends CordovaPlugin {
/**
* Constructor.
*/
public Vibration() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArray of arguments for the plugin.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return True when the action was valid, false otherwise.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("vibrate")) {
this.vibrate(args.getLong(0));
}
else if (action.equals("vibrateWithPattern")) {
JSONArray pattern = args.getJSONArray(0);
int repeat = args.getInt(1);
//add a 0 at the beginning of pattern to align with w3c
long[] patternArray = new long[pattern.length()+1];
patternArray[0] = 0;
for (int i = 0; i < pattern.length(); i++) {
patternArray[i+1] = pattern.getLong(i);
}
this.vibrateWithPattern(patternArray, repeat);
}
else if (action.equals("cancelVibration")) {
this.cancelVibration();
}
else {
return false;
}
// Only alert and confirm are async.
callbackContext.success();
return true;
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Vibrates the device for a given amount of time.
*
* @param time Time to vibrate in ms.
*/
public void vibrate(long time) {
// Start the vibration, 0 defaults to half a second.
if (time == 0) {
time = 500;
}
AudioManager manager = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);
if (manager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) {
Vibrator vibrator = (Vibrator) this.cordova.getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(time);
}
}
/**
* Vibrates the device with a given pattern.
*
* @param pattern Pattern with which to vibrate the device.
* Pass in an array of longs that
* are the durations for which to
* turn on or off the vibrator in
* milliseconds. The first value
* indicates the number of milliseconds
* to wait before turning the vibrator
* on. The next value indicates the
* number of milliseconds for which
* to keep the vibrator on before
* turning it off. Subsequent values
* alternate between durations in
* milliseconds to turn the vibrator
* off or to turn the vibrator on.
*
* @param repeat Optional index into the pattern array at which
* to start repeating, or -1 for no repetition (default).
*/
public void vibrateWithPattern(long[] pattern, int repeat) {
AudioManager manager = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);
if (manager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) {
Vibrator vibrator = (Vibrator) this.cordova.getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern, repeat);
}
}
/**
* Immediately cancels any currently running vibration.
*/
public void cancelVibration() {
Vibrator vibrator = (Vibrator) this.cordova.getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.cancel();
}
}

View File

@ -0,0 +1,161 @@
/*
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.
*/
package org.apache.cordova.whitelist;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.Whitelist;
import org.xmlpull.v1.XmlPullParser;
import android.content.Context;
import android.util.Log;
public class WhitelistPlugin extends CordovaPlugin {
private static final String LOG_TAG = "WhitelistPlugin";
private Whitelist allowedNavigations;
private Whitelist allowedIntents;
private Whitelist allowedRequests;
// Used when instantiated via reflection by PluginManager
public WhitelistPlugin() {
}
// These can be used by embedders to allow Java-configuration of whitelists.
public WhitelistPlugin(Context context) {
this(new Whitelist(), new Whitelist(), null);
new CustomConfigXmlParser().parse(context);
}
public WhitelistPlugin(XmlPullParser xmlParser) {
this(new Whitelist(), new Whitelist(), null);
new CustomConfigXmlParser().parse(xmlParser);
}
public WhitelistPlugin(Whitelist allowedNavigations, Whitelist allowedIntents, Whitelist allowedRequests) {
if (allowedRequests == null) {
allowedRequests = new Whitelist();
allowedRequests.addWhiteListEntry("file:///*", false);
allowedRequests.addWhiteListEntry("data:*", false);
}
this.allowedNavigations = allowedNavigations;
this.allowedIntents = allowedIntents;
this.allowedRequests = allowedRequests;
}
@Override
public void pluginInitialize() {
if (allowedNavigations == null) {
allowedNavigations = new Whitelist();
allowedIntents = new Whitelist();
allowedRequests = new Whitelist();
new CustomConfigXmlParser().parse(webView.getContext());
}
}
private class CustomConfigXmlParser extends ConfigXmlParser {
@Override
public void handleStartTag(XmlPullParser xml) {
String strNode = xml.getName();
if (strNode.equals("content")) {
String startPage = xml.getAttributeValue(null, "src");
allowedNavigations.addWhiteListEntry(startPage, false);
} else if (strNode.equals("allow-navigation")) {
String origin = xml.getAttributeValue(null, "href");
if ("*".equals(origin)) {
allowedNavigations.addWhiteListEntry("http://*/*", false);
allowedNavigations.addWhiteListEntry("https://*/*", false);
allowedNavigations.addWhiteListEntry("data:*", false);
} else {
allowedNavigations.addWhiteListEntry(origin, false);
}
} else if (strNode.equals("allow-intent")) {
String origin = xml.getAttributeValue(null, "href");
allowedIntents.addWhiteListEntry(origin, false);
} else if (strNode.equals("access")) {
String origin = xml.getAttributeValue(null, "origin");
String subdomains = xml.getAttributeValue(null, "subdomains");
boolean external = (xml.getAttributeValue(null, "launch-external") != null);
if (origin != null) {
if (external) {
Log.w(LOG_TAG, "Found <access launch-external> within config.xml. Please use <allow-intent> instead.");
allowedIntents.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0));
} else {
if ("*".equals(origin)) {
allowedRequests.addWhiteListEntry("http://*/*", false);
allowedRequests.addWhiteListEntry("https://*/*", false);
} else {
allowedRequests.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0));
}
}
}
}
}
@Override
public void handleEndTag(XmlPullParser xml) {
}
}
@Override
public Boolean shouldAllowNavigation(String url) {
if (allowedNavigations.isUrlWhiteListed(url)) {
return true;
}
return null; // Default policy
}
@Override
public Boolean shouldAllowRequest(String url) {
if (Boolean.TRUE == shouldAllowNavigation(url)) {
return true;
}
if (allowedRequests.isUrlWhiteListed(url)) {
return true;
}
return null; // Default policy
}
@Override
public Boolean shouldOpenExternalUrl(String url) {
if (allowedIntents.isUrlWhiteListed(url)) {
return true;
}
return null; // Default policy
}
public Whitelist getAllowedNavigations() {
return allowedNavigations;
}
public void setAllowedNavigations(Whitelist allowedNavigations) {
this.allowedNavigations = allowedNavigations;
}
public Whitelist getAllowedIntents() {
return allowedIntents;
}
public void setAllowedIntents(Whitelist allowedIntents) {
this.allowedIntents = allowedIntents;
}
public Whitelist getAllowedRequests() {
return allowedRequests;
}
public void setAllowedRequests(Whitelist allowedRequests) {
this.allowedRequests = allowedRequests;
}
}

View File

@ -14,7 +14,9 @@
<content src="index.html" />
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
@ -24,12 +26,48 @@
<allow-intent href="market:*" />
<allow-navigation href="*" />
<feature name="Battery" >
<param name="android-package" value="org.apache.cordova.batterystatus.BatteryListener"/>
</feature>
<feature name="Camera">
<param name="android-package" value="org.apache.cordova.camera.CameraLauncher"/>
</feature>
<feature name="Device" >
<param name="android-package" value="org.apache.cordova.device.Device"/>
</feature>
<feature name="Accelerometer">
<param name="android-package" value="org.apache.cordova.devicemotion.AccelListener"/>
</feature>
<feature name="Compass">
<param name="android-package" value="org.apache.cordova.deviceorientation.CompassListener"/>
</feature>
<feature name="Notification">
<param name="android-package" value="org.apache.cordova.dialogs.Notification"/>
</feature>
<feature name="NetworkStatus">
<param name="android-package" value="org.apache.cordova.networkinformation.NetworkManager"/>
</feature>
<feature name="Vibration">
<param name="android-package" value="org.apache.cordova.vibration.Vibration"/>
</feature>
<!--
<feature name="Whitelist">
<param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" />
After enable it block and freez requests to our JSON-RPC
<feature name="Whitelist" >
<param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin"/>
<param name="onload" value="true" />
</feature>
-->
<preference name="loglevel" value="DEBUG" />
<!--
<preference name="splashscreen" value="splash" />