Initial commit

This commit is contained in:
2018-09-22 10:44:38 +08:00
commit eacb95c18a
723 changed files with 100993 additions and 0 deletions

64
plugins/android.json Normal file
View File

@@ -0,0 +1,64 @@
{
"prepare_queue": {
"installed": [],
"uninstalled": []
},
"config_munge": {
"files": {}
},
"installed_plugins": {
"com.jiliac.systemvolume": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"com.phonegap.plugins.OrientationLock": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"cordova-plugin-tts": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"cordova.custom.plugins.exitapp": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"cordova-plugin-geolocation": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"cordova-plugin-battery-status": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"cordova-plugin-x-toast": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"cordova-plugin-app-version": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"phonegap-plugin-speech-recognition": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"cordova-plugin-network-information": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"cordova-plugin-insomnia": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"cordova-plugin-whitelist": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"cordova-plugin-fullscreen": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"cordova-plugin-file": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"com.pylonproducts.wifiwizard": {
"PACKAGE_NAME": "net.yunkong2.vis"
},
"cordova-plugin-certificates": {
"PACKAGE_NAME": "net.yunkong2.vis"
}
},
"dependent_plugins": {
"cordova-plugin-compat": {
"PACKAGE_NAME": "net.yunkong2.vis"
}
}
}

View File

@@ -0,0 +1,21 @@
## Description
Plugin to set volume of the music stream.
## Supported Platforms
Android
## Installation
Adding the Plugin to your project:
```bash
phonegap local plugin add https://github.com/Jiliac/phonegap-plugin-systemvolume.git
```
## Example
```bash
//set the sound to maximum
window.system.setSystemVolume(1.0);
```

View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
id="com.jiliac.systemvolume"
version="0.1.0">
<name>System Volume</name>
<description>PhoneGap System Volume Plugin</description>
<license>MIT</license>
<keywords>phonegap,volume</keywords>
<repo>https://github.com/Jiliac/phonegap-plugin-systemvolume.git</repo>
<js-module src="www/systemvolume.js" name="SystemVolume">
<clobbers target="window.system" />
</js-module>
<!-- android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="SystemVolume">
<param name="android-package" value="com.jiliac.systemvolume.SystemVolume"/>
</feature>
</config-file>
<source-file src="src/android/SystemVolume.java" target-dir="src/com/jiliac/systemvolume" />
<config-file target="AndroidManifest.xml" parent="/manifest">
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
</config-file>
</platform>
<config-file target="AndroidManifest.xml" parent="/manifest">
<uses-permission android:name="android.permission.VIBRATE"/>
</config-file>
</plugin>

View File

@@ -0,0 +1,41 @@
package com.jiliac.systemvolume;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.media.AudioManager;
import android.os.Vibrator;
public class SystemVolume extends CordovaPlugin {
public SystemVolume(){
}
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if(action.equals("setSystemVolume")) {
this.setSystemVolume(args.getDouble(0));
} else {
return false;
}
callbackContext.success();
return true;
}
public void setSystemVolume(double volume) {
AudioManager am = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);
am.setStreamVolume(
AudioManager.STREAM_MUSIC,
(int) (am.getStreamMaxVolume(AudioManager.STREAM_MUSIC) * volume),
0);
/*am.setStreamVolume(
AudioManager.STREAM_SYSTEM,
(int) (am.getStreamMaxVolume(AudioManager.STREAM_SYSTEM) * volume),
0);
*/
}
}

View File

@@ -0,0 +1,8 @@
var exec = require('cordova/exec');
module.exports = {
setSystemVolume: function(volume) {
exec(null, null, "SystemVolume", "setSystemVolume", [volume]);
},
};

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2012-2014 Emil Varga <emil.varga@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,29 @@
# OrientationLock #
Android Cordova plugin for locking/unlocking the screen orientation from Javascript
## Calling the plugin ##
From your JavaScript code call
`window.plugins.orientationLock.unlock()` to unlock orientation,
`window.plugins.orientationLock.lock("portrait")` or `window.plugins.orientationLock.lock("landscape")`
to lock your screen to the specified orientation.
To start your Cordova application pre-locked place
`setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);` or
`setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);`
in the `onCreate()` of your Cordova activity.
Once unlocked, you can track orientation changes with the regular `orientationchange` event:
window.addEventListener("orientationchange", function() {
alert(window.orientation);
});
## Adding the Plugin to your project ##
Using this plugin requires [Apache Cordova for Android](https://github.com/apache/cordova-android).
Within your project, run the following command:
cordova plugin add https://github.com/cogitor/PhoneGap-OrientationLock.git

View File

@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
id="com.phonegap.plugins.OrientationLock"
version="0.1">
<name>OrientationLock</name>
<author>Emil Varga</author>
<description>
Android Cordova plugin for locking/unlocking the screen orientation from Javascript.
</description>
<license>MIT</license>
<js-module src="www/orientationLock.js" name="OrientationLock">
<clobbers target="OrientationLock" />
</js-module>
<engines>
<engine name="cordova" version=">=3.0.0" />
</engines>
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="OrientationLock" >
<param name="android-package" value="com.plugin.phonegap.OrientationLock"/>
</feature>
</config-file>
<source-file src="src/com/plugin/phonegap/OrientationLock.java" target-dir="src/com/plugin/phonegap/" />
</platform>
</plugin>

View File

@@ -0,0 +1,65 @@
package com.plugin.phonegap;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.pm.ActivityInfo;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
/**
*
* Android Phonegap Plugin for locking/unlocking the orientation from JS code
*
*/
public class OrientationLock extends CordovaPlugin {
private static final String LANSCAPE = "landscape";
private static final String PORTRAIT = "portrait";
public OrientationLock() {
}
public void unlock() {
this.cordova.getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
public void lock(String orientation) {
if (orientation.equals(PORTRAIT))
this.cordova.getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
this.cordova.getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
@Override
public boolean execute(String action, JSONArray arguments, CallbackContext callbackContext) {
if (action.equals("lock")) {
try {
String orientation = arguments.getString(0);
if (orientation!=null && (orientation.equals(LANSCAPE) || orientation.equals(PORTRAIT))) {
this.lock(orientation);
callbackContext.success();
return true;
} else {
return false;
}
} catch (JSONException e) {
callbackContext.error("JSON_EXCEPTION");
return true;
}
} else if (action.equals("unlock")) {
this.unlock();
callbackContext.success();
return true;
} else {
return false;
}
}
}

View File

@@ -0,0 +1,18 @@
var OrientationLock = function() {}
OrientationLock.prototype.lock = function(orientation, success, fail) {
return cordova.exec(success, fail, "OrientationLock", "lock", [orientation])
}
OrientationLock.prototype.unlock = function(success, fail) {
return cordova.exec(success, fail, "OrientationLock", "unlock", [])
}
if ( ! window.plugins ) {
window.plugins = {}
}
if ( ! window.plugins.orientationLock ) {
window.plugins.orientationLock = new OrientationLock()
}
module.exports = OrientationLock

View File

@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@@ -0,0 +1,153 @@
# WifiWizard
Version 0.2.10
`getCurrentBSSID` now available on IOS.
Fixed callback issue with `connectNetwork`. It now checks to make sure you are connected to the specific network before returning.
Updated permissions for Android Marshmallow.
Version 0.2.9
This Phonegap plugin enables WiFi management from within Phonegap applications.
iOS has limited functionality, as Apple's WifiManager equivalent is only available as a private API. Any app that used these features would not be allowed on the app store. The only function availabe for iOS is `getCurrentSSID`.
### Installation
#### Master
Run `phonegap plugin install https://github.com/parsonsmatt/WifiWizard.git`. Please note that the plugin is in active development, and this will pull the most recent commits.
#### Releases
Run `cordova plugin add com.pylonproducts.wifiwizard`. This will get the latest release of the plugin.
### Usage from within Cordova/Phonegap:
#### `WifiWizard.formatWifiConfig(SSID, password, algorithm);`
Formats the wifi configuration information into a JSON for use with the addNetwork function. Currently, only WPA is supported for the `algorithm` value.
#### `WifiWizard.formatWPAConfig(SSID, password);`
Is a helper method. It returns an object which can be used to add a WPA wifi network.
#### `WifiWizard.addNetwork(wifi, win, fail);`
Adds the network to the list of available networks that the user can log into. `wifi` needs to be an object as formatted by formatWifiConfig. `win` and `fail` are callback functions to be executed based on the result of the call.
#### `WifiWizard.removeNetwork(SSID, win, fail);`
Removes the network with the given SSID. As above, `win` and `fail` are callback functions.
#### `WifiWizard.connectNetwork(SSID, win, fail);`
Connects the phone to the given Wifi network.
#### `WifiWizard.disconnectNetwork(SSID, win, fail);`
Disconnects the phone to the given Wifi network.
#### `WifiWizard.listNetworks(listHandler, fail);`
Retrieves a list of the configured networks as an array of strings and passes them to the function listHandler.
#### `WifiWizard.startScan(success, fail);`
Start WiFi scanning. `success` is a function that is called when the scan is started.
#### `WifiWizard.getScanResults([options], listHandler, fail);`
Retrieves a list of the available networks as an array of objects and passes them to the function listHandler. The format of the array is:
networks = [
{ "level": signal_level, // raw RSSI value
"SSID": ssid, // SSID as string, with escaped double quotes: "\"ssid name\""
"BSSID": bssid // MAC address of WiFi router as string
"frequency": frequency of the access point channel in MHz
"capabilities": capabilities // Describes the authentication, key management, and encryption schemes supported by the access point.
"timestamp": timestamp in microseconds (since boot) when this result was last seen.
}
]
An options object may be passed. Currently, the only supported option is `numLevels`, and it has the following behavior:
- if `(n == true || n < 2)`, `*.getScanResults({numLevels: n})` will return data as before, split in 5 levels;
- if `(n > 1)`, `*.getScanResults({numLevels: n})` will calculate the signal level, split in n levels;
- if `(n == false)`, `*.getScanResults({numLevels: n})` will use the raw signal level;
#### `WifiWizard.getCurrentSSID(ssidHandler, fail);`
Retrieves the current SSID and passes it to ssidHandler.
#### `WifiWizard.isWifiEnabled(win, fail);`
Retrieves the current wifi status and passes `true` or `false` to the handler.
#### `WifiWizard.setWifiEnabled(enabled, win, fail);`
Set wifi status. `enabled` is a Boolean type, so to disable the Wifi, you'd execute `WifiWizard.setWifiEnabled(false, win, fail);`
### Changelog:
#### v0.2.9
`isWifiEnabled` bug fixed. `level` in `getScanResults` object now refers to raw RSSI value. The function now accepts an options object, and by specifiying `{ numLevels: value }` you can get the old behavior.
#### v0.2.8
`getScanResults` now returns the BSSID along with the SSID and strength of the network.
#### v0.2.7
- Clobber WifiWizard.js automatically via Cordova plugin architecture
#### v0.2.6
- Added `isWifiEnabled`, `setWifiEnabled`
#### v0.2.5
- Fixes `getConnectedSSID` error handlers
#### v0.2.4
- Added `getConnectedSSID` method
#### v0.2.3
- Added `disconnect` that does disconnection on current WiFi
#### v0.2.2
- Added `startScan` and `getScanResults`
#### v0.2.1
- Fixed reference problem in `formatWPAConfig`
#### v0.2.0
- Changed format of wifiConfiguration object to allow more extensibility.
#### v0.1.1
- `addNetwork` will now update the network if the SSID already exists.
#### v0.1.0
- All functions now work!
#### v0.0.3
- Fixed errors in native implementation. Currently, Add and Remove networks aren't working, but others are working as expected.
#### v0.0.2
- Changed plugin.xml and WifiWizard.js to attach WifiWizard directly to the HTML.
#### v0.0.1
- Initial commit

View File

@@ -0,0 +1,100 @@
{
"_args": [
[
{
"raw": "wifiwizard",
"scope": null,
"escapedName": "wifiwizard",
"name": "wifiwizard",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"D:\\pWork\\yunkong2.vis.cordova\\node_modules"
]
],
"_from": "wifiwizard@latest",
"_id": "wifiwizard@0.2.11",
"_inCache": true,
"_location": "/wifiwizard",
"_nodeVersion": "0.12.7",
"_npmUser": {
"name": "hoerresb",
"email": "brandonhoerres@gmail.com"
},
"_npmVersion": "2.11.3",
"_phantomChildren": {},
"_requested": {
"raw": "wifiwizard",
"scope": null,
"escapedName": "wifiwizard",
"name": "wifiwizard",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/wifiwizard/-/wifiwizard-0.2.11.tgz",
"_shasum": "ed2db47bc4ac621c12de1d6ef5948822e964df14",
"_shrinkwrap": null,
"_spec": "wifiwizard",
"_where": "D:\\pWork\\yunkong2.vis.cordova\\node_modules",
"author": {
"name": "Matt Parsons"
},
"bugs": {
"url": "https://github.com/parsonsmatt/wifiwizard/issues"
},
"cordova": {
"id": "com.pylonproducts.wifiwizard",
"platforms": [
"android",
"ios"
]
},
"dependencies": {},
"description": "This plugin allows Phonegap applications to manage Wifi connections.",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "ed2db47bc4ac621c12de1d6ef5948822e964df14",
"tarball": "https://registry.npmjs.org/wifiwizard/-/wifiwizard-0.2.11.tgz"
},
"gitHead": "6a7701ebe2ec7e7bb176c63375d0c67a3de87972",
"homepage": "https://github.com/parsonsmatt/wifiwizard#readme",
"keywords": [
"phonegap",
"network",
"wifi",
"ecosystem:cordova",
"cordova-android",
"cordova-ios"
],
"license": "Apache 2.0",
"maintainers": [
{
"name": "asmund1",
"email": "asmund@herikstad.net"
},
{
"name": "hoerresb",
"email": "brandonhoerres@gmail.com"
},
{
"name": "parsonsmatt",
"email": "parsonsmatt@gmail.com"
}
],
"name": "wifiwizard",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/parsonsmatt/wifiwizard.git"
},
"scripts": {},
"version": "0.2.11"
}

View File

@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
id="com.pylonproducts.wifiwizard"
version="0.2.11">
<name>WifiWizard</name>
<description>This plugin allows Phonegap applications to manage Wifi connections.</description>
<author>Matt Parsons</author>
<keywords>phonegap,network,wifi</keywords>
<license>Apache 2.0</license>
<repo>https://github.com/parsonsmatt/WifiWizard/</repo>
<js-module src="www/WifiWizard.js" name="WifiWizard">
<clobbers target="window.WifiWizard"/>
</js-module>
<platform name="android">
<config-file target="AndroidManifest.xml" parent="/manifest">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</config-file>
<config-file target="res/xml/config.xml" parent="/*">
<feature name="WifiWizard">
<param name="android-package" value="com.pylonproducts.wifiwizard.WifiWizard" />
<param name="onload" value="true" />
</feature>
</config-file>
<source-file src="src/android/src/com/pylonproducts/wifiwizard/WifiWizard.java" target-dir="src/com/pylonproducts/wifiwizard" />
</platform>
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="WifiWizard">
<param name="ios-package" value="NXWWifiWizard"/>
</feature>
</config-file>
<header-file src="src/ios/NXWWifiWizard.h"/>
<source-file src="src/ios/NXWWifiWizard.m"/>
<framework src="SystemConfiguration.framework" />
</platform>
</plugin>

View File

@@ -0,0 +1,570 @@
/*
* Copyright 2015 Matt Parsons
*
* Licensed 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 com.pylonproducts.wifiwizard;
import org.apache.cordova.*;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiEnterpriseConfig;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.SupplicantState;
import android.content.Context;
import android.util.Log;
public class WifiWizard extends CordovaPlugin {
private static final String ADD_NETWORK = "addNetwork";
private static final String REMOVE_NETWORK = "removeNetwork";
private static final String CONNECT_NETWORK = "connectNetwork";
private static final String DISCONNECT_NETWORK = "disconnectNetwork";
private static final String DISCONNECT = "disconnect";
private static final String LIST_NETWORKS = "listNetworks";
private static final String START_SCAN = "startScan";
private static final String GET_SCAN_RESULTS = "getScanResults";
private static final String GET_CONNECTED_SSID = "getConnectedSSID";
private static final String IS_WIFI_ENABLED = "isWifiEnabled";
private static final String SET_WIFI_ENABLED = "setWifiEnabled";
private static final String TAG = "WifiWizard";
private WifiManager wifiManager;
private CallbackContext callbackContext;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.wifiManager = (WifiManager) cordova.getActivity().getSystemService(Context.WIFI_SERVICE);
}
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext)
throws JSONException {
this.callbackContext = callbackContext;
if(action.equals(IS_WIFI_ENABLED)) {
return this.isWifiEnabled(callbackContext);
}
else if(action.equals(SET_WIFI_ENABLED)) {
return this.setWifiEnabled(callbackContext, data);
}
else if (!wifiManager.isWifiEnabled()) {
callbackContext.error("Wifi is not enabled.");
return false;
}
else if(action.equals(ADD_NETWORK)) {
return this.addNetwork(callbackContext, data);
}
else if(action.equals(REMOVE_NETWORK)) {
return this.removeNetwork(callbackContext, data);
}
else if(action.equals(CONNECT_NETWORK)) {
return this.connectNetwork(callbackContext, data);
}
else if(action.equals(DISCONNECT_NETWORK)) {
return this.disconnectNetwork(callbackContext, data);
}
else if(action.equals(LIST_NETWORKS)) {
return this.listNetworks(callbackContext);
}
else if(action.equals(START_SCAN)) {
return this.startScan(callbackContext);
}
else if(action.equals(GET_SCAN_RESULTS)) {
return this.getScanResults(callbackContext, data);
}
else if(action.equals(DISCONNECT)) {
return this.disconnect(callbackContext);
}
else if(action.equals(GET_CONNECTED_SSID)) {
return this.getConnectedSSID(callbackContext);
}
else {
callbackContext.error("Incorrect action parameter: " + action);
}
return false;
}
/**
* This methods adds a network to the list of available WiFi networks.
* If the network already exists, then it updates it.
*
* @params callbackContext A Cordova callback context.
* @params data JSON Array with [0] == SSID, [1] == password
* @return true if add successful, false if add fails
*/
private boolean addNetwork(CallbackContext callbackContext, JSONArray data) {
// Initialize the WifiConfiguration object
WifiConfiguration wifi = new WifiConfiguration();
Log.d(TAG, "WifiWizard: addNetwork entered.");
try {
// data's order for ANY object is 0: ssid, 1: authentication algorithm,
// 2+: authentication information.
String authType = data.getString(1);
if (authType.equals("WPA")) {
// WPA Data format:
// 0: ssid
// 1: auth
// 2: password
String newSSID = data.getString(0);
wifi.SSID = newSSID;
String newPass = data.getString(2);
wifi.preSharedKey = newPass;
wifi.status = WifiConfiguration.Status.ENABLED;
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifi.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifi.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifi.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifi.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifi.networkId = ssidToNetworkId(newSSID);
if ( wifi.networkId == -1 ) {
wifiManager.addNetwork(wifi);
callbackContext.success(newSSID + " successfully added.");
}
else {
wifiManager.updateNetwork(wifi);
callbackContext.success(newSSID + " successfully updated.");
}
wifiManager.saveConfiguration();
return true;
}
else if (authType.equals("WEP")) {
// TODO: connect/configure for WEP
Log.d(TAG, "WEP unsupported.");
callbackContext.error("WEP unsupported");
return false;
}
else if (authType.equals("NONE")) {
String newSSID = data.getString(0);
wifi.SSID = newSSID;
wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifi.networkId = ssidToNetworkId(newSSID);
if ( wifi.networkId == -1 ) {
wifiManager.addNetwork(wifi);
callbackContext.success(newSSID + " successfully added.");
}
else {
wifiManager.updateNetwork(wifi);
callbackContext.success(newSSID + " successfully updated.");
}
wifiManager.saveConfiguration();
return true;
}
// TODO: Add more authentications as necessary
else {
Log.d(TAG, "Wifi Authentication Type Not Supported.");
callbackContext.error("Wifi Authentication Type Not Supported: " + authType);
return false;
}
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG,e.getMessage());
return false;
}
}
/**
* This method removes a network from the list of configured networks.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to remove
* @return true if network removed, false if failed
*/
private boolean removeNetwork(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard: removeNetwork entered.");
if(!validateData(data)) {
callbackContext.error("WifiWizard: removeNetwork data invalid");
Log.d(TAG, "WifiWizard: removeNetwork data invalid");
return false;
}
// TODO: Verify the type of data!
try {
String ssidToDisconnect = data.getString(0);
int networkIdToRemove = ssidToNetworkId(ssidToDisconnect);
if (networkIdToRemove >= 0) {
wifiManager.removeNetwork(networkIdToRemove);
wifiManager.saveConfiguration();
callbackContext.success("Network removed.");
return true;
}
else {
callbackContext.error("Network not found.");
Log.d(TAG, "WifiWizard: Network not found, can't remove.");
return false;
}
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
}
/**
* This method connects a network.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
* @return true if network connected, false if failed
*/
private boolean connectNetwork(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard: connectNetwork entered.");
if(!validateData(data)) {
callbackContext.error("WifiWizard: connectNetwork invalid data");
Log.d(TAG, "WifiWizard: connectNetwork invalid data.");
return false;
}
String ssidToConnect = "";
try {
ssidToConnect = data.getString(0);
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
int networkIdToConnect = ssidToNetworkId(ssidToConnect);
if (networkIdToConnect >= 0) {
// We disable the network before connecting, because if this was the last connection before
// a disconnect(), this will not reconnect.
wifiManager.disableNetwork(networkIdToConnect);
wifiManager.enableNetwork(networkIdToConnect, true);
SupplicantState supState;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
supState = wifiInfo.getSupplicantState();
callbackContext.success(supState.toString());
return true;
}else{
callbackContext.error("WifiWizard: cannot connect to network");
return false;
}
}
/**
* This method disconnects a network.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
* @return true if network disconnected, false if failed
*/
private boolean disconnectNetwork(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard: disconnectNetwork entered.");
if(!validateData(data)) {
callbackContext.error("WifiWizard: disconnectNetwork invalid data");
Log.d(TAG, "WifiWizard: disconnectNetwork invalid data");
return false;
}
String ssidToDisconnect = "";
// TODO: Verify type of data here!
try {
ssidToDisconnect = data.getString(0);
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
int networkIdToDisconnect = ssidToNetworkId(ssidToDisconnect);
if (networkIdToDisconnect > 0) {
wifiManager.disableNetwork(networkIdToDisconnect);
callbackContext.success("Network " + ssidToDisconnect + " disconnected!");
return true;
}
else {
callbackContext.error("Network " + ssidToDisconnect + " not found!");
Log.d(TAG, "WifiWizard: Network not found to disconnect.");
return false;
}
}
/**
* This method disconnects current network.
*
* @param callbackContext A Cordova callback context
* @return true if network disconnected, false if failed
*/
private boolean disconnect(CallbackContext callbackContext) {
Log.d(TAG, "WifiWizard: disconnect entered.");
if (wifiManager.disconnect()) {
callbackContext.success("Disconnected from current network");
return true;
} else {
callbackContext.error("Unable to disconnect from the current network");
return false;
}
}
/**
* This method uses the callbackContext.success method to send a JSONArray
* of the currently configured networks.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
* @return true if network disconnected, false if failed
*/
private boolean listNetworks(CallbackContext callbackContext) {
Log.d(TAG, "WifiWizard: listNetworks entered.");
List<WifiConfiguration> wifiList = wifiManager.getConfiguredNetworks();
JSONArray returnList = new JSONArray();
for (WifiConfiguration wifi : wifiList) {
returnList.put(wifi.SSID);
}
callbackContext.success(returnList);
return true;
}
/**
* This method uses the callbackContext.success method to send a JSONArray
* of the scanned networks.
*
* @param callbackContext A Cordova callback context
* @param data JSONArray with [0] == JSONObject
* @return true
*/
private boolean getScanResults(CallbackContext callbackContext, JSONArray data) {
List<ScanResult> scanResults = wifiManager.getScanResults();
JSONArray returnList = new JSONArray();
Integer numLevels = null;
if(!validateData(data)) {
callbackContext.error("WifiWizard: disconnectNetwork invalid data");
Log.d(TAG, "WifiWizard: disconnectNetwork invalid data");
return false;
}else if (!data.isNull(0)) {
try {
JSONObject options = data.getJSONObject(0);
if (options.has("numLevels")) {
Integer levels = options.optInt("numLevels");
if (levels > 0) {
numLevels = levels;
} else if (options.optBoolean("numLevels", false)) {
// use previous default for {numLevels: true}
numLevels = 5;
}
}
} catch (JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
return false;
}
}
for (ScanResult scan : scanResults) {
/*
* @todo - breaking change, remove this notice when tidying new release and explain changes, e.g.:
* 0.y.z includes a breaking change to WifiWizard.getScanResults().
* Earlier versions set scans' level attributes to a number derived from wifiManager.calculateSignalLevel.
* This update returns scans' raw RSSI value as the level, per Android spec / APIs.
* If your application depends on the previous behaviour, we have added an options object that will modify behaviour:
* - if `(n == true || n < 2)`, `*.getScanResults({numLevels: n})` will return data as before, split in 5 levels;
* - if `(n > 1)`, `*.getScanResults({numLevels: n})` will calculate the signal level, split in n levels;
* - if `(n == false)`, `*.getScanResults({numLevels: n})` will use the raw signal level;
*/
int level;
if (numLevels == null) {
level = scan.level;
} else {
level = wifiManager.calculateSignalLevel(scan.level, numLevels);
}
JSONObject lvl = new JSONObject();
try {
lvl.put("level", level);
lvl.put("SSID", scan.SSID);
lvl.put("BSSID", scan.BSSID);
lvl.put("frequency", scan.frequency);
lvl.put("capabilities", scan.capabilities);
// lvl.put("timestamp", scan.timestamp);
returnList.put(lvl);
} catch (JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
return false;
}
}
callbackContext.success(returnList);
return true;
}
/**
* This method uses the callbackContext.success method. It starts a wifi scanning
*
* @param callbackContext A Cordova callback context
* @return true if started was successful
*/
private boolean startScan(CallbackContext callbackContext) {
if (wifiManager.startScan()) {
callbackContext.success();
return true;
}
else {
callbackContext.error("Scan failed");
return false;
}
}
/**
* This method retrieves the SSID for the currently connected network
*
* @param callbackContext A Cordova callback context
* @return true if SSID found, false if not.
*/
private boolean getConnectedSSID(CallbackContext callbackContext){
if(!wifiManager.isWifiEnabled()){
callbackContext.error("Wifi is disabled");
return false;
}
WifiInfo info = wifiManager.getConnectionInfo();
if(info == null){
callbackContext.error("Unable to read wifi info");
return false;
}
String ssid = info.getSSID();
if(ssid.isEmpty()) {
ssid = info.getBSSID();
}
if(ssid.isEmpty()){
callbackContext.error("SSID is empty");
return false;
}
callbackContext.success(ssid);
return true;
}
/**
* This method retrieves the current WiFi status
*
* @param callbackContext A Cordova callback context
* @return true if WiFi is enabled, fail will be called if not.
*/
private boolean isWifiEnabled(CallbackContext callbackContext) {
boolean isEnabled = wifiManager.isWifiEnabled();
callbackContext.success(isEnabled ? "1" : "0");
return isEnabled;
}
/**
* This method takes a given String, searches the current list of configured WiFi
* networks, and returns the networkId for the network if the SSID matches. If not,
* it returns -1.
*/
private int ssidToNetworkId(String ssid) {
List<WifiConfiguration> currentNetworks = wifiManager.getConfiguredNetworks();
int networkId = -1;
// For each network in the list, compare the SSID with the given one
for (WifiConfiguration test : currentNetworks) {
if ( test.SSID.equals(ssid) ) {
networkId = test.networkId;
}
}
return networkId;
}
/**
* This method enables or disables the wifi
*/
private boolean setWifiEnabled(CallbackContext callbackContext, JSONArray data) {
if(!validateData(data)) {
callbackContext.error("WifiWizard: disconnectNetwork invalid data");
Log.d(TAG, "WifiWizard: disconnectNetwork invalid data");
return false;
}
String status = "";
try {
status = data.getString(0);
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
if (wifiManager.setWifiEnabled(status.equals("true"))) {
callbackContext.success();
return true;
}
else {
callbackContext.error("Cannot enable wifi");
return false;
}
}
private boolean validateData(JSONArray data) {
try {
if (data == null || data.get(0) == null) {
callbackContext.error("Data is null.");
return false;
}
return true;
}
catch (Exception e) {
callbackContext.error(e.getMessage());
}
return false;
}
}

View File

@@ -0,0 +1,18 @@
#import <Cordova/CDV.h>
@interface NXWWifiWizard : CDVPlugin
- (void)addNetwork:(CDVInvokedUrlCommand*)command;
- (void)removeNetwork:(CDVInvokedUrlCommand*)command;
- (void)connectNetwork:(CDVInvokedUrlCommand*)command;
- (void)disconnectNetwork:(CDVInvokedUrlCommand*)command;
- (void)listNetworks:(CDVInvokedUrlCommand*)command;
- (void)getScanResults:(CDVInvokedUrlCommand*)command;
- (void)startScan:(CDVInvokedUrlCommand*)command;
- (void)disconnect:(CDVInvokedUrlCommand*)command;
- (void)getConnectedSSID:(CDVInvokedUrlCommand*)command;
- (void)getConnectedBSSID:(CDVInvokedUrlCommand*)command;
- (void)isWifiEnabled:(CDVInvokedUrlCommand*)command;
- (void)setWifiEnabled:(CDVInvokedUrlCommand*)command;
@end

View File

@@ -0,0 +1,135 @@
#import "NXWWifiWizard.h"
#import <SystemConfiguration/CaptiveNetwork.h>
@implementation NXWWifiWizard
- (id)fetchSSIDInfo {
// see http://stackoverflow.com/a/5198968/907720
NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
NSLog(@"Supported interfaces: %@", ifs);
NSDictionary *info;
for (NSString *ifnam in ifs) {
info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
NSLog(@"%@ => %@", ifnam, info);
if (info && [info count]) { break; }
}
return info;
}
- (void)addNetwork:(CDVInvokedUrlCommand*)command {
CDVPluginResult *pluginResult = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not supported"];
[self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId];
}
- (void)removeNetwork:(CDVInvokedUrlCommand*)command {
CDVPluginResult *pluginResult = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not supported"];
[self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId];
}
- (void)connectNetwork:(CDVInvokedUrlCommand*)command {
CDVPluginResult *pluginResult = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not supported"];
[self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId];
}
- (void)disconnectNetwork:(CDVInvokedUrlCommand*)command {
CDVPluginResult *pluginResult = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not supported"];
[self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId];
}
- (void)listNetworks:(CDVInvokedUrlCommand*)command {
CDVPluginResult *pluginResult = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not supported"];
[self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId];
}
- (void)getScanResults:(CDVInvokedUrlCommand*)command {
CDVPluginResult *pluginResult = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not supported"];
[self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId];
}
- (void)startScan:(CDVInvokedUrlCommand*)command {
CDVPluginResult *pluginResult = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not supported"];
[self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId];
}
- (void)disconnect:(CDVInvokedUrlCommand*)command {
CDVPluginResult *pluginResult = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not supported"];
[self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId];
}
- (void)getConnectedSSID:(CDVInvokedUrlCommand*)command {
CDVPluginResult *pluginResult = nil;
NSDictionary *r = [self fetchSSIDInfo];
NSString *ssid = [r objectForKey:(id)kCNNetworkInfoKeySSID]; //@"SSID"
if (ssid && [ssid length]) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:ssid];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not available"];
}
[self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId];
}
- (void)getConnectedBSSID:(CDVInvokedUrlCommand*)command {
CDVPluginResult *pluginResult = nil;
NSDictionary *r = [self fetchSSIDInfo];
NSString *bssid = [r objectForKey:(id)kCNNetworkInfoKeyBSSID]; //@"SSID"
if (bssid && [bssid length]) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:bssid];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not available"];
}
[self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId];
}
- (void)isWifiEnabled:(CDVInvokedUrlCommand*)command {
}
- (void)setWifiEnabled:(CDVInvokedUrlCommand*)command {
CDVPluginResult *pluginResult = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Not supported"];
[self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId];
}
@end

View File

@@ -0,0 +1,295 @@
/*
* Copyright 2015 Matt Parsons
*
* Licensed 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 is the interface for the WifiWizard Phonegap plugin.
*/
var WifiWizard = {
/**
* This method formats wifi information into an object for use with the
* addNetwork function. Currently only supports
* @param SSID the SSID of the network enclosed in double quotes
* @param password the password for the network enclosed in double quotes
* @param algorithm the authentication algorithm
* @return wifiConfig a JSON object properly formatted for the plugin.
*/
formatWifiConfig: function(SSID, password, algorithm) {
var wifiConfig = {
SSID: WifiWizard.formatWifiString(SSID)
};
if (!algorithm && !password) {
// open network
wifiConfig.auth = {
algorithm: 'NONE'
};
} else if (algorithm === 'WPA') {
wifiConfig.auth = {
algorithm : algorithm,
password : WifiWizard.formatWifiString(password)
// Other parameters can be added depending on algorithm.
};
}
else if (algorithm === 'New network type') {
wifiConfig.auth = {
algorithm : algorithm
// Etc...
};
}
else {
console.log("Algorithm incorrect")
return false;
}
return wifiConfig;
},
/**
* This method is a helper method that returns a wifi object with WPA.
*/
formatWPAConfig: function(SSID, password) {
return WifiWizard.formatWifiConfig(SSID, password, 'WPA');
},
/**
* This method formats a given SSID and ensures that it is appropriate.
* If the SSID is not wrapped in double quotes, it wraps it in double quotes.
* Despite the name, this also needs to be done to WPA PSK.
* @param ssid the SSID to format
*/
formatWifiString: function(ssid) {
if (ssid === undefined || ssid === null) {
ssid = "";
}
ssid = ssid.trim()
if (ssid.charAt(0) != '"' ) {
ssid = '"' + ssid;
}
if (ssid.charAt(ssid.length-1) != '"' ) {
ssid = ssid + '"';
}
return ssid;
},
/**
* This methods adds a network to the list of available networks.
* Currently, only WPA authentication method is supported.
*
* @param wifi is JSON formatted information necessary for adding the Wifi
* network, as is done in formatWifiConfig.
* @param win is a callback function that gets called if the plugin is
* successful.
* @param fail is a callback function that gets called if the plugin gets
* an error
*/
addNetwork: function(wifi, win, fail) {
//console.log("WifiWizard add method entered.");
if (wifi !== null && typeof wifi === 'object') {
// Ok to proceed!
}
else {
console.log('WifiWizard: Invalid parameter. wifi not an object.');
}
var networkInformation = [];
if (wifi.SSID !== undefined && wifi.SSID !== '') {
networkInformation.push(wifi.SSID);
}
else {
// i dunno, like, reject the call or something? what are you even doing?
console.log('WifiWizard: No SSID given.');
return false;
}
if (typeof wifi.auth == 'object') {
switch (wifi.auth.algorithm) {
case 'WPA':
networkInformation.push('WPA');
networkInformation.push(wifi.auth.password);
break;
case 'NONE':
networkInformation.push('NONE');
break;
case 'Newly supported type':
// Push values in specific order, and implement new type in the Java code.
break;
default:
console.log("WifiWizard: authentication invalid.");
}
}
else {
console.log('WifiWizard: No authentication algorithm given.');
return false;
}
cordova.exec(win, fail, 'WifiWizard', 'addNetwork', networkInformation);
},
/**
* This method removes a given network from the list of configured networks.
* @param SSID of the network to remove
* @param win function to handle successful callback
* @param fail function to handle error callback
*/
removeNetwork: function(SSID, win, fail) {
cordova.exec(win, fail, 'WifiWizard', 'removeNetwork', [WifiWizard.formatWifiString(SSID)]);
},
/**
* This method connects a network if it is configured.
* @param SSID the network to connect
* @param win function that is called if successful
* @param fail function that is called to handle errors
*/
connectNetwork: function(SSID, win, fail) {
cordova.exec(win, fail, 'WifiWizard', 'connectNetwork', [WifiWizard.formatWifiString(SSID)]);
},
/**
* This method disconnects a network if it is configured.
* @param SSID the network to disconnect
* @param win function that is called if successful
* @param fail function that is called to handle errors
*/
disconnectNetwork: function(SSID, win, fail) {
cordova.exec(win, fail, 'WifiWizard', 'disconnectNetwork', [WifiWizard.formatWifiString(SSID)]);
},
/**
* Hands the list of previously used and configured networks to the `win` success callback function.
* @param win callback function that receives list of networks
* @param fail callback function if error
* @return a list of networks
*/
listNetworks: function(win, fail) {
if (typeof win != "function") {
console.log("listNetworks first parameter must be a function to handle list.");
return;
}
cordova.exec(win, fail, 'WifiWizard', 'listNetworks', []);
},
/**
* Hands the list of scanned networks to the `win` success callback function.
* @param opts optional json object of options
* @param win callback function that receives list of networks
* @param fail callback function if error
* @return a list of networks
*/
getScanResults: function(options, win, fail) {
if (typeof options === 'function') {
fail = win;
win = options;
options = {};
}
if (typeof win != "function") {
console.log("getScanResults first parameter must be a function to handle list.");
return;
}
cordova.exec(win, fail, 'WifiWizard', 'getScanResults', [options]);
},
/**
* Start scanning wifi.
* @param win callback function
* @param fail callback function if error
*/
startScan: function(win, fail) {
if (typeof win != "function") {
console.log("startScan first parameter must be a function to handle list.");
return;
}
cordova.exec(win, fail, 'WifiWizard', 'startScan', []);
},
/**
* Disconnect current wifi.
* @param win callback function
* @param fail callback function if error
*/
disconnect: function(win, fail) {
if (typeof win != "function") {
console.log("disconnect first parameter must be a function to handle list.");
return;
}
cordova.exec(win, fail, 'WifiWizard', 'disconnect', []);
},
/**
* Gets the currently connected wifi SSID
* @param win callback function
* @param fail callback function if error
*/
getCurrentSSID: function(win, fail) {
if (typeof win != "function") {
console.log("getCurrentSSID first parameter must be a function to handle SSID.");
return;
}
cordova.exec(win, fail, 'WifiWizard', 'getConnectedSSID', []);
},
getCurrentBSSID: function(win, fail) {
if (typeof win != "function") {
console.log("getCurrentSSID first parameter must be a function to handle SSID.");
return;
}
cordova.exec(win, fail, 'WifiWizard', 'getConnectedBSSID', []);
},
/**
* Gets 'true' or 'false' if WiFi is enabled or disabled
* @param win callback function
* @param fail
*/
isWifiEnabled: function(win, fail) {
if (typeof win != "function") {
console.log("isWifiEnabled first parameter must be a function to handle wifi status.");
return;
}
cordova.exec(
// Cordova can only return strings to JS, and the underlying plugin
// sends a "1" for true and "0" for false.
function(result) {
win(result == "1");
},
fail, 'WifiWizard', 'isWifiEnabled', []
);
},
/**
* Gets '1' if WiFi is enabled
* @param enabled callback function
* @param win callback function
* @param fail callback function if wifi is disabled
*/
setWifiEnabled: function(enabled, win, fail) {
if (typeof win != "function") {
console.log("setWifiEnabled second parameter must be a function to handle enable result.");
return;
}
cordova.exec(win, fail, 'WifiWizard', 'setWifiEnabled', [enabled]);
}
};
module.exports = WifiWizard;

View File

@@ -0,0 +1,42 @@
### 0.1.9
* Renamed Windows8 platform to Windows
### 0.1.7
* Add getPackageName feature (thanks to @gprasanth)
* Add getAppName feature (thanks to @mirko77)
* Fix for windows 8 (thanks to @deliriousrhino)
* Fix version number in plugin.xml file
### 0.1.6
* Split into two functions getAppVersion.getVersionNumber() and getAppVersion.getVersionCode() to return build number
* Fix a deprecation warning in iOS version
### 0.1.5
* iOS: Return version number but log and fall back to build number if it is nil (thanks to [Eddy Verbruggen](https://github.com/EddyVerbruggen))
### 0.1.4
* Return version number, not build number on iOS (thanks to http://www.humancopy.net)
* Support for Windows phone 8 (thanks to Cristi Badila / Gediminas Šaltenis)
* Support for AngularJS as well as jQuery (thanks to Matias Singers, [Red Ape Solutions](http://www.redapesolutions.com/))
### 0.1.3
* Fixes to Android for Corova 3 and above (thanks to AxoInsanit)
### 0.1.2
* Updated for Cordova 3 and above (thanks to Russell Keith-Magee [freakboy3742](https://github.com/freakboy3742)
### 0.1.1
* Improved README
* Bug fix for non-jQuery use
* Tidy plugin.xml
### 0.1.0
* First release

View File

@@ -0,0 +1,20 @@
Copyright (c) 2013 White October
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,71 @@
# Cordova AppVersion plugin
Reads the version of your app from the target build settings.
## Installation
### With cordova-cli
If you are using [cordova-cli](https://github.com/apache/cordova-cli), install
with:
cordova plugin add cordova-plugin-app-version
### With plugman
With a plain [plugman](https://github.com/apache/cordova-plugman), you should be
able to install with something like:
plugman --platform <ios|android> --project <directory> --plugin https://github.com/whiteoctober/cordova-plugin-app-version.git
### Manually in iOS
TODO: Write these instructions
### Manually in Android
TODO: Write these instructions
## Use from Javascript
If you are using jQuery, AngularJS, WinJS or any Promise/A library (Bluebird), promise style is supported. Use something like:
cordova.getAppVersion.getVersionNumber().then(function (version) {
$('.version').text(version);
});
If not, pass a callback function:
cordova.getAppVersion.getVersionNumber(function (version) {
alert(version);
});
In addition to the version number you can also retrieve other details about your application:
### getAppName
Returns the name of the app. E.g. "My Awesome App"
### getPackageName
Returns the package name of the app - the reversed domain name app identifier like com.example.myawesomeapp
### getVersionCode
Returns the build identifier of the app
### getVersionNumber
Returns the version number of the app
## Credits
Written by [Robert (Jamie) Munro](http://twitter.com/rjmunro) at
[White October](http://whiteoctober.co.uk/)
Various others have contributed fixes and new features. See the CHANGELOG.md for details.
Original code based on the following Stack Overflow posts:
* [iOS](http://stackoverflow.com/a/14713364/3408)
* [Android](http://stackoverflow.com/a/3637686/3408)

View File

@@ -0,0 +1 @@
0.1.9

View File

@@ -0,0 +1,94 @@
{
"_args": [
[
{
"raw": "cordova-plugin-app-version",
"scope": null,
"escapedName": "cordova-plugin-app-version",
"name": "cordova-plugin-app-version",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"D:\\pWork\\yunkong2.vis.cordova\\node_modules"
]
],
"_from": "cordova-plugin-app-version@latest",
"_id": "cordova-plugin-app-version@0.1.9",
"_inCache": true,
"_location": "/cordova-plugin-app-version",
"_nodeVersion": "5.8.0",
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/cordova-plugin-app-version-0.1.9.tgz_1472026299040_0.8699118127115071"
},
"_npmUser": {
"name": "whiteoctober",
"email": "info@whiteoctober.co.uk"
},
"_npmVersion": "3.7.3",
"_phantomChildren": {},
"_requested": {
"raw": "cordova-plugin-app-version",
"scope": null,
"escapedName": "cordova-plugin-app-version",
"name": "cordova-plugin-app-version",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"#USER"
],
"_resolved": "https://registry.npmjs.org/cordova-plugin-app-version/-/cordova-plugin-app-version-0.1.9.tgz",
"_shasum": "9db0607863337a710489302e5f50a904f1449bdb",
"_shrinkwrap": null,
"_spec": "cordova-plugin-app-version",
"_where": "D:\\pWork\\yunkong2.vis.cordova\\node_modules",
"author": {
"name": "whiteoctober"
},
"bugs": {
"url": "https://github.com/whiteoctober/cordova-plugin-app-version/issues"
},
"dependencies": {},
"description": "Cordova plugin to return the version number of the current app",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "9db0607863337a710489302e5f50a904f1449bdb",
"tarball": "https://registry.npmjs.org/cordova-plugin-app-version/-/cordova-plugin-app-version-0.1.9.tgz"
},
"gitHead": "bcfecaf9e4d20135a487de5502f7d1e3b251e062",
"homepage": "https://github.com/whiteoctober/cordova-plugin-app-version#readme",
"keywords": [
"cordova",
"ecosystem:cordova",
"app",
"version",
"appversion",
"plugin"
],
"license": "MIT",
"maintainers": [
{
"name": "maistho",
"email": "maistho@gmail.com"
},
{
"name": "whiteoctober",
"email": "info@whiteoctober.co.uk"
}
],
"name": "cordova-plugin-app-version",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/whiteoctober/cordova-plugin-app-version.git"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"version": "0.1.9"
}

View File

@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
id="cordova-plugin-app-version"
version="0.1.9">
<name>AppVersion</name>
<description>
This plugin will return the version of your App that you have set in
packaging it. I.e. it will always match the version in the app store.
</description>
<license>MIT</license>
<engines>
<!--
Cordova 2.8.0 is all I have tested on - it should work fine with earlier versions.
Please modify the below line, test, and submit a PR if it works for you.
-->
<engine name="cordova" version=">=3.0.0" />
</engines>
<js-module src="www/AppVersionPlugin.js">
<clobbers target="cordova.getAppVersion" />
</js-module>
<!-- android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="AppVersion">
<param name="android-package" value="uk.co.whiteoctober.cordova.AppVersion"/>
</feature>
</config-file>
<source-file src="src/android/AppVersion.java" target-dir="src/uk/co/whiteoctober/cordova" />
</platform>
<!-- blackberry10 -->
<platform name="blackberry10">
<dependency id="cordova-plugin-bb-app" />
<config-file target="www/config.xml" parent="/widget">
<feature name="AppVersion" value="AppVersion" />
</config-file>
<js-module src="www/blackberry10/AppVersionProxy.js" name="AppVersionProxy.js" >
<runs />
</js-module>
</platform>
<!-- ios -->
<platform name="ios">
<plugins-plist key="AppVersion" string="AppVersion" />
<config-file target="config.xml" parent="/*">
<feature name="AppVersion">
<param name="ios-package" value="AppVersion" />
</feature>
</config-file>
<header-file src="src/ios/AppVersion.h" />
<source-file src="src/ios/AppVersion.m" />
</platform>
<!-- windows8 -->
<platform name="windows">
<js-module src="src/windows/AppVersionProxy.js" name="AppVersionProxy">
<merges target=""/>
</js-module>
</platform>
<!-- wp8 -->
<platform name="wp8">
<config-file target="config.xml" parent="/*">
<feature name="AppVersion">
<param name="wp-package" value="AppVersion"/>
</feature>
</config-file>
<source-file src="src/wp8/AppVersion.cs" />
</platform>
</plugin>

View File

@@ -0,0 +1,45 @@
package uk.co.whiteoctober.cordova;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PackageManager;
public class AppVersion extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
if (action.equals("getAppName")) {
PackageManager packageManager = this.cordova.getActivity().getPackageManager();
ApplicationInfo app = packageManager.getApplicationInfo(this.cordova.getActivity().getPackageName(), 0);
callbackContext.success((String)packageManager.getApplicationLabel(app));
return true;
}
if (action.equals("getPackageName")) {
callbackContext.success(this.cordova.getActivity().getPackageName());
return true;
}
if (action.equals("getVersionNumber")) {
PackageManager packageManager = this.cordova.getActivity().getPackageManager();
callbackContext.success(packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionName);
return true;
}
if (action.equals("getVersionCode")) {
PackageManager packageManager = this.cordova.getActivity().getPackageManager();
callbackContext.success(packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionCode);
return true;
}
return false;
} catch (NameNotFoundException e) {
callbackContext.success("N/A");
return true;
}
}
}

View File

@@ -0,0 +1,13 @@
#import <Cordova/CDVPlugin.h>
@interface AppVersion : CDVPlugin
- (void)getAppName:(CDVInvokedUrlCommand*)command;
- (void)getPackageName:(CDVInvokedUrlCommand*)command;
- (void)getVersionNumber:(CDVInvokedUrlCommand*)command;
- (void)getVersionCode:(CDVInvokedUrlCommand*)command;
@end

View File

@@ -0,0 +1,47 @@
#import "AppVersion.h"
#import <Cordova/CDVPluginResult.h>
@implementation AppVersion
- (void)getAppName : (CDVInvokedUrlCommand *)command
{
NSString * callbackId = command.callbackId;
NSString * version =[[[NSBundle mainBundle]infoDictionary]objectForKey :@"CFBundleDisplayName"];
CDVPluginResult * pluginResult =[CDVPluginResult resultWithStatus : CDVCommandStatus_OK messageAsString : version];
[self.commandDelegate sendPluginResult : pluginResult callbackId : callbackId];
}
- (void)getPackageName:(CDVInvokedUrlCommand*)command
{
NSString* callbackId = command.callbackId;
NSString* packageName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:packageName];
[self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
}
- (void)getVersionNumber:(CDVInvokedUrlCommand*)command
{
NSString* callbackId = command.callbackId;
NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
if (version == nil) {
NSLog(@"CFBundleShortVersionString was nil, attempting CFBundleVersion");
version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
if (version == nil) {
NSLog(@"CFBundleVersion was also nil, giving up");
// not calling error callback here to maintain backward compatibility
}
}
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:version];
[self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
}
- (void)getVersionCode:(CDVInvokedUrlCommand*)command
{
NSString* callbackId = command.callbackId;
NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:version];
[self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
}
@end

View File

@@ -0,0 +1,33 @@
AppVersionProxy = {
getVersionNumber: function (successCallback, failCallback, args) {
var version = Windows.ApplicationModel.Package.current.id.version;
successCallback([version.major, version.minor, version.build, version.revision].join('.'));
},
getAppName: function (successCallback, failCallback, args) {
if(Windows.ApplicationModel.Package.current && Windows.ApplicationModel.Package.current.displayName){
var name = Windows.ApplicationModel.Package.current.displayName;
successCallback(name);
} else {
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync("AppxManifest.xml").then(function (file) {
Windows.Data.Xml.Dom.XmlDocument.loadFromFileAsync(file).then(function (xdoc) {
var displayName = xdoc.getElementsByTagName("DisplayName");
if (displayName && displayName.length === 1) {
var name = displayName[0].innerText;
successCallback(name);
} else {
(failCallback || function(){})({ code: -1, message: "ERR_DISPLAY_NAME_NOT_FOUND" });
}
}, (failCallback || function(){}));
}, (failCallback || function(){}));
}
},
getPackageName: function (successCallback, failCallback, args) {
var name = Windows.ApplicationModel.Package.current.id.name;
successCallback(name);
},
getVersionCode: function (successCallback, failCallback, args) {
var build = Windows.ApplicationModel.Package.current.id.version.build;
successCallback(build);
}
};
cordova.commandProxy.add("AppVersion", AppVersionProxy);

View File

@@ -0,0 +1,53 @@
using System;
using System.Reflection;
using System.Xml.Linq;
using Windows.ApplicationModel;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
namespace Cordova.Extension.Commands
{
public class AppVersion : BaseCommand
{
public void getVersionNumber(string empty)
{
string version;
if (Environment.OSVersion.Version.Major <= 8)
{
// Package.Current.Id is NOT working in Windows Phone 8
// Workaround based on http://stackoverflow.com/questions/14371275/how-can-i-get-my-windows-store-apps-title-and-version-info
version = XDocument.Load("WMAppManifest.xml").Root.Element("App").Attribute("Version").Value;
}
else
{
version = Package.Current.Id.Version.ToString();
}
this.DispatchCommandResult(new PluginResult(PluginResult.Status.OK, version));
}
public void getAppName(string empty)
{
string name;
if (Environment.OSVersion.Version.Major <= 8)
{
//Windows.ApplicationModel.Package.Current.Id is NOT working in Windows Phone 8
//Workaround based on http://stackoverflow.com/questions/14371275/how-can-i-get-my-windows-store-apps-title-and-version-info
name = XDocument.Load("WMAppManifest.xml").Root.Element("App").Attribute("Title").Value;
}
else
{
name = Package.Current.Id.Name;
}
this.DispatchCommandResult(new PluginResult(PluginResult.Status.OK, name));
}
public void getPackageName(string empty)
{
string package = Assembly.GetExecutingAssembly().GetName().Name;
this.DispatchCommandResult(new PluginResult(PluginResult.Status.OK, package));
}
}
}

View File

@@ -0,0 +1,65 @@
/*jslint indent: 2 */
/*global window, jQuery, angular, cordova */
"use strict";
// Returns a jQuery or AngularJS deferred object, or pass a success and fail callbacks if you don't want to use jQuery or AngularJS
var getPromisedCordovaExec = function (command, success, fail) {
var toReturn, deferred, injector, $q;
if (success === undefined) {
if (window.jQuery) {
deferred = jQuery.Deferred();
success = deferred.resolve;
fail = deferred.reject;
toReturn = deferred;
} else if (window.angular) {
injector = angular.injector(["ng"]);
$q = injector.get("$q");
deferred = $q.defer();
success = deferred.resolve;
fail = deferred.reject;
toReturn = deferred.promise;
} else if (window.when && window.when.promise) {
deferred = when.defer();
success = deferred.resolve;
fail = deferred.reject;
toReturn = deferred.promise;
} else if (window.Promise) {
toReturn = new Promise(function(c, e) {
success = c;
fail = e;
});
} else if (window.WinJS && window.WinJS.Promise) {
toReturn = new WinJS.Promise(function(c, e) {
success = c;
fail = e;
});
} else {
return console.error('AppVersion either needs a success callback, or jQuery/AngularJS/Promise/WinJS.Promise defined for using promises');
}
}
// 5th param is NOT optional. must be at least empty array
cordova.exec(success, fail, "AppVersion", command, []);
return toReturn;
};
var getAppVersion = function (success, fail) {
return getPromisedCordovaExec('getVersionNumber', success, fail);
};
getAppVersion.getAppName = function (success, fail) {
return getPromisedCordovaExec('getAppName', success, fail);
};
getAppVersion.getPackageName = function (success, fail) {
return getPromisedCordovaExec('getPackageName', success, fail);
};
getAppVersion.getVersionNumber = function (success, fail) {
return getPromisedCordovaExec('getVersionNumber', success, fail);
};
getAppVersion.getVersionCode = function (success, fail) {
return getPromisedCordovaExec('getVersionCode', success, fail);
};
module.exports = getAppVersion;

View File

@@ -0,0 +1,18 @@
module.exports = {
getVersionNumber: function( success, fail ) {
if( !blackberry || !blackberry.app || !blackberry.app.version ) {
if( fail ) {
return fail();
} else {
return "";
}
}
if( success ) {
return success( blackberry.app.version );
}
return blackberry.app.version;
}
};
require("cordova/exec/proxy").add("AppVersion", module.exports);

View File

@@ -0,0 +1,37 @@
<!--
#
# 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.
#
-->
# Contributing to Apache Cordova
Anyone can contribute to Cordova. And we need your contributions.
There are multiple ways to contribute: report bugs, improve the docs, and
contribute code.
For instructions on this, start with the
[contribution overview](http://cordova.apache.org/contribute/).
The details are explained there, but the important items are:
- Sign and submit an Apache ICLA (Contributor License Agreement).
- Have a Jira issue open that corresponds to your contribution.
- Run the tests so your patch doesn't break existing functionality.
We look forward to your contributions!

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed 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.

View File

@@ -0,0 +1,5 @@
Apache Cordova
Copyright 2012 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).

View File

@@ -0,0 +1,137 @@
---
title: Battery Status
description: Get events for device battery level.
---
<!--
# license: 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.
-->
|Android 4.4|Android 5.1|Android 6.0|iOS 9.3|iOS 10.0|Windows 10 Store|Travis CI|
|:-:|:-:|:-:|:-:|:-:|:-:|:-:|
|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-battery-status)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-battery-status/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-battery-status)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-battery-status/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-battery-status)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-battery-status/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-battery-status)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-battery-status/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-battery-status)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-battery-status/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-battery-status)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-battery-status/)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-battery-status.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-battery-status)|
# cordova-plugin-battery-status
This plugin provides an implementation of an old version of the [Battery Status Events API][w3c_spec]. It adds the following three events to the `window` object:
* batterystatus
* batterycritical
* batterylow
Applications may use `window.addEventListener` to attach an event listener for any of the above events after the `deviceready` event fires.
## Installation
cordova plugin add cordova-plugin-battery-status
## Status object
All events in this plugin return an object with the following properties:
- __level__: The battery charge percentage (0-100). _(Number)_
- __isPlugged__: A boolean that indicates whether the device is plugged in. _(Boolean)_
## batterystatus event
Fires when the battery charge percentage changes by at least 1 percent, or when the device is plugged in or unplugged. Returns an [object][status_object] containing battery status.
### Example
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(status) {
console.log("Level: " + status.level + " isPlugged: " + status.isPlugged);
}
### Supported Platforms
- Amazon Fire OS
- iOS
- Android
- BlackBerry 10
- Windows Phone 7 and 8
- Windows (Windows Phone 8.1 and Windows 10)
- Firefox OS
- Browser (Chrome, Firefox, Opera)
### Quirks: Android &amp; Amazon Fire OS
**Warning**: the Android and Fire OS implementations are greedy and prolonged use will drain the device's battery.
### Quirks: Windows Phone 7 &amp; Windows Phone 8
The `level` property is _not_ supported on Windows Phone 7 because the OS does not provide native APIs to determine battery level. The `isPlugged` parameter _is_ supported.
### Quirks: Windows Phone 8.1
The `isPlugged` parameter is _not_ supported on Windows Phone 8.1. The `level` parameter _is_ supported.
## batterylow event
Fires when the battery charge percentage reaches the low charge threshold. This threshold value is device-specific. Returns an [object][status_object] containing battery status.
### Example
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(status) {
alert("Battery Level Low " + status.level + "%");
}
### Supported Platforms
- Amazon Fire OS
- iOS
- Android
- BlackBerry 10
- Firefox OS
- Windows (Windows Phone 8.1 and Windows 10)
- Browser (Chrome, Firefox, Opera)
### Quirks: Windows Phone 8.1
The `batterylow` event fires on Windows Phone 8.1 irrespective of whether the device is plugged in or not. This happens because the OS does not provide an API to detect whether the device is plugged in.
## batterycritical event
Fires when the battery charge percentage reaches the critical charge threshold. This threshold value is device-specific. Returns an [object][status_object] containing battery status.
### Example
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(status) {
alert("Battery Level Critical " + status.level + "%\nRecharge Soon!");
}
### Supported Platforms
- Amazon Fire OS
- iOS
- Android
- BlackBerry 10
- Firefox OS
- Windows (Windows Phone 8.1 and Windows 10)
- Browser (Chrome, Firefox, Opera)
### Quirks: Windows Phone 8.1
The `batterycritical` event fires on Windows Phone 8.1 irrespective of whether the device is plugged in or not. This happens because the OS does not provide an API to detect whether the device is plugged in.
[w3c_spec]: http://www.w3.org/TR/2011/WD-battery-status-20110915/
[status_object]: #status-object

View File

@@ -0,0 +1,131 @@
<!--
#
# 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.
#
-->
# Release Notes
### 1.2.4 (Apr 27, 2017)
* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) (Android) Added **Android 6.0** build badge
* [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder
* [CB-12639](https://issues.apache.org/jira/browse/CB-12639) (all) Tests: console.err() -> console.error()
### 1.2.3 (Feb 28, 2017)
* [CB-12369](https://issues.apache.org/jira/browse/CB-12369) Add plugin typings from `DefinitelyTyped`
* [CB-12363](https://issues.apache.org/jira/browse/CB-12363) Added build badges for **iOS 9.3** and **iOS 10.0**
### 1.2.2 (Dec 12, 2016)
* [CB-12227](https://issues.apache.org/jira/browse/CB-12227) (windows) Fixed Browserify error
* [CB-12236](https://issues.apache.org/jira/browse/CB-12236) - Fix RELEASENOTES.md for cordova-plugin-battery-status
* [CB-12230](https://issues.apache.org/jira/browse/CB-12230) Removed Windows 8.1 build badges
* [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Incremented plugin version.
### 1.2.1 (Dec 07, 2016)
* [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Updated version and RELEASENOTES.md for release 1.2.1
* [CB-8929](https://issues.apache.org/jira/browse/CB-8929) Fix failing tests on iOS
* [CB-8929](https://issues.apache.org/jira/browse/CB-8929) Use PowerManager to get battery state on Win 10
* [CB-11917](https://issues.apache.org/jira/browse/CB-11917) - Remove pull request template checklist item: "iCLA has been submitted…"
* [CB-11832](https://issues.apache.org/jira/browse/CB-11832) Incremented plugin version.
### 1.2.0 (Sep 08, 2016)
* [CB-11795](https://issues.apache.org/jira/browse/CB-11795) Add 'protective' entry to cordovaDependencies
* Plugin uses Android Log class and not Cordova LOG class
* Add badges for paramedic builds on Jenkins
* Add pull request template.
* [CB-10996](https://issues.apache.org/jira/browse/CB-10996) Adding front matter to README.md
### 1.1.2 (Apr 15, 2016)
* [CB-10720](https://issues.apache.org/jira/browse/CB-10720) Reorganizing and rewording docs.
* [CB-10636](https://issues.apache.org/jira/browse/CB-10636) Add JSHint for plugins
### 1.1.1 (Nov 18, 2015)
* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest
* Fixing contribute link.
### 1.1.0 (Jun 17, 2015)
* added missing license headers
* [CB-7953](https://issues.apache.org/jira/browse/CB-7953) Add cordova-plugin-battery-status support for browser platform
* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-battery-status documentation translation: cordova-plugin-battery-status
* attempt to fix npm issue
### 1.0.0 (Apr 15, 2015)
* [CB-8746](https://issues.apache.org/jira/browse/CB-8746) gave plugin major version bump
* [CB-8808](https://issues.apache.org/jira/browse/CB-8808) Fixed tests to pass on Windows Phone 8.1
* [CB-8831](https://issues.apache.org/jira/browse/CB-8831) Adds extra check for available API on Windows
* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) properly updated translated docs to use new id
* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) changed plugin-id to pacakge-name
* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) updated translated docs to use new id
* Use TRAVIS_BUILD_DIR, install paramedic by npm
* Doc correction, Use the apostrophe to show possession
* Fix travis+paramedic pathing issue
* add Android+FireOS warning to tell devs that prolonged use will drain the battery.
* [CB-7971](https://issues.apache.org/jira/browse/CB-7971) Add cordova-plugin-battery-status support for Windows Phone 8.1
* [CB-8659](https://issues.apache.org/jira/browse/CB-8659): ios: 4.0.x Compatibility: Remove use of initWithWebView method
* added apache/travis badge - will not show until INFRA updates the github integration
* add travis.yml for CI with paramedic
* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file
### 0.2.12 (Dec 02, 2014)
* [CB-7976](https://issues.apache.org/jira/browse/CB-7976) Android: Use webView's context rather than Activity's context for intent receiver
* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-battery-status documentation translation: cordova-plugin-battery-status
* [CB-7571](https://issues.apache.org/jira/browse/CB-7571) Bump version of nested plugin to match parent plugin
### 0.2.11 (Sep 17, 2014)
* [CB-7249](https://issues.apache.org/jira/browse/CB-7249) cordova-plugin-battery-status documentation translation: cordova-plugin-battery-status
* [CB-6724](https://issues.apache.org/jira/browse/CB-6724) re-add accidental removed of var keyword
* [CB-6957](https://issues.apache.org/jira/browse/CB-6957) renamed folder to tests + added nested plugin.xml
* added documentation for manual tests
* [CB-6957](https://issues.apache.org/jira/browse/CB-6957) Style improvements on Manual tests
### 0.2.10 (Aug 06, 2014)
* [CB-6957](https://issues.apache.org/jira/browse/CB-6957) Ported Battery-status manual & automated
* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs
### 0.2.9 (Jun 05, 2014)
* [CB-6721](https://issues.apache.org/jira/browse/CB-6721) Test for batterycritical change before batterylow change
* [CB-5611](https://issues.apache.org/jira/browse/CB-5611) firefoxos: battery-status plugin support added
* [CB-4519](https://issues.apache.org/jira/browse/CB-4519), [CB-4520](https://issues.apache.org/jira/browse/CB-4520) low+critical weren't firing when level went from 21->19, and were when level went 19->20
* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md
### 0.2.8 (Apr 17, 2014)
* [CB-6465](https://issues.apache.org/jira/browse/CB-6465): Add license headers to Tizen code
* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers
* Add NOTICE file
### 0.2.7 (Feb 05, 2014)
* Add Tizen plugin.
### 0.2.6 (Jan 02, 2014)
* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Add doc/index.md for Battery Status.
### 0.2.5 (Dec 4, 2013)
* Merged WP8 support for level, but #def'd it out so the same code runs on wp7. Updated docs to reflect WP8 support for battery level, and low+critical events
* wp8 add support in level
* add ubuntu platform
* 1. Updated platform name amazon->amazon-fireos. Deleted src files. 2. Change to use amazon-fireos as the platform if user agent string contains 'cordova-amazon-fireos'
### 0.2.4 (Oct 25, 2013)
* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): added repo + issue tag to plugin.xml for battery status plugin
* [CB-4915](https://issues.apache.org/jira/browse/CB-4915) Incremented plugin version on dev branch.
### 0.2.3 (Sept 25, 2013)
* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) bumping&resetting version
* [CB-4752](https://issues.apache.org/jira/browse/CB-4752) Incremented plugin version on dev branch.
* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.battery-status to org.apache.cordova.battery-status

View File

@@ -0,0 +1,151 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-battery-status
[![Build Status](https://travis-ci.org/apache/cordova-plugin-battery-status.svg)](https://travis-ci.org/apache/cordova-plugin-battery-status)
Dieses Plugin stellt eine Implementierung einer alten Version der [Batterie-Status-API](http://www.w3.org/TR/2011/WD-battery-status-20110915/) dar..
Es fügt die folgenden drei `window` Events hinzu:
* batterystatus
* batterycritical
* batterylow
## Installation
cordova plugin add cordova-plugin-battery-status
## batterystatus
Dieses Ereignis wird ausgelöst, wenn sich der Prozentsatz der Akkuladung um mindestens 1 Prozent ändert, oder wenn das Gerät aufgeladen oder vom Netz getrennt wird.
Dem Batterie-Status-Event-Handler wird ein Objekt übergeben, das zwei Eigenschaften enthält:
* **Ebene**: der Prozentsatz der Batterieladung (0-100). *(Anzahl)*
* **IsPlugged**: ein boolescher Wert, der angibt, ob das Gerät eingesteckt ist *(boolesch)*
Anwendungen sollten in der Regel `window.addEventListener` verwenden, um einen Event-Listener hinzuzufügen, nachdem das `deviceready` -Event ausgelöst wurde.
### Unterstützte Plattformen
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Windows Phone 7 und 8
* Windows (nur Windows Phone 8.1)
* Tizen
* Firefox OS
### Android und Amazon Fire OS Macken
* Warnung: die Android + Fire OS Implementierungen sind gierig und längerem Gebrauch lässt den Benutzer Batterie.
### Windows Phone 7 und 8 Eigenarten
Windows Phone 7 bietet keine systemeigenen APIs um das Batterie-Niveau zu bestimmen, so dass die `level` -Eigenschaft ist nicht verfügbar. Der `isPlugged` -Parameter wird unterstützt.
### Windows-Eigenheiten
Windows Phone 8.1 unterstützt keine `IsPlugged` Parameter. `Der Parameter <em>wird</em> unterstützt.`
### Beispiel
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
Das Ereignis wird ausgelöst, wenn der Prozentsatz der Batterieladung den kritischen Akku-Schwellenwert erreicht hat. Der Wert ist gerätespezifisch.
Der `batterycritical` Handler übergibt ein Objekt mit zwei Eigenschaften:
* **Ebene**: der Prozentsatz der Batterieladung (0-100). *(Anzahl)*
* **IsPlugged**: ein boolescher Wert, der angibt, ob das Gerät eingesteckt ist *(boolesch)*
Anwendungen sollten in der Regel `window.addEventListener` verwenden, um einen Event-Listener hinzuzufügen, nachdem das `deviceready` -Event ausgelöst wurde.
### Unterstützte Plattformen
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
* Windows (nur Windows Phone 8.1)
### Windows-Eigenheiten
Windows Phone 8.1 wird `batterycritical` Ereignis unabhängig angeschlossen Zustand ausgelöst, da es nicht unterstützt wird.
### Beispiel
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
Das Ereignis wird ausgelöst, wenn der Prozentsatz der Batterieladung den kritischen Akku-Schwellenwert erreicht hat. Der Wert ist gerätespezifisch.
Der `batterylow` Handler übergibt ein Objekt mit zwei Eigenschaften:
* **Ebene**: der Prozentsatz der Batterieladung (0-100). *(Anzahl)*
* **IsPlugged**: ein boolescher Wert, der angibt, ob das Gerät eingesteckt ist *(boolesch)*
Anwendungen sollten in der Regel `window.addEventListener` verwenden, um einen Event-Listener hinzuzufügen, nachdem das `deviceready` -Event ausgelöst wurde.
### Unterstützte Plattformen
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
* Windows (nur Windows Phone 8.1)
### Windows-Eigenheiten
Windows Phone 8.1 wird `batterylow` Ereignis unabhängig angeschlossen Zustand ausgelöst, da es nicht unterstützt wird.
### Beispiel
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,132 @@
<!---
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.
-->
# org.Apache.Cordova.Battery-status
Dieses Plugin stellt eine Implementierung einer alten Version der [Batterie-Status-API][1] dar..
[1]: http://www.w3.org/TR/2011/WD-battery-status-20110915/
Es fügt die folgenden drei `window` Events hinzu:
* batterystatus
* batterycritical
* batterylow
## Installation
cordova plugin add cordova-plugin-battery-status
## batterystatus
Dieses Ereignis wird ausgelöst, wenn sich der Prozentsatz der Akkuladung um mindestens 1 Prozent ändert, oder wenn das Gerät aufgeladen oder vom Netz getrennt wird.
Dem Batterie-Status-Event-Handler wird ein Objekt übergeben, das zwei Eigenschaften enthält:
* **Ebene**: der Prozentsatz der Batterieladung (0-100). *(Anzahl)*
* **IsPlugged**: ein boolescher Wert, der angibt, ob das Gerät eingesteckt ist *(boolesch)*
Anwendungen sollten in der Regel `window.addEventListener` verwenden, um einen Event-Listener hinzuzufügen, nachdem das `deviceready` -Event ausgelöst wurde.
### Unterstützte Plattformen
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Windows Phone 7 und 8
* Tizen
* Firefox OS
### Windows Phone 7 und 8 Eigenarten
Windows Phone 7 bietet keine systemeigenen APIs um das Batterie-Niveau zu bestimmen, so dass die `level` -Eigenschaft ist nicht verfügbar. Der `isPlugged` -Parameter wird unterstützt.
### Beispiel
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
Das Ereignis wird ausgelöst, wenn der Prozentsatz der Batterieladung den kritischen Akku-Schwellenwert erreicht hat. Der Wert ist gerätespezifisch.
Der `batterycritical` Handler übergibt ein Objekt mit zwei Eigenschaften:
* **Ebene**: der Prozentsatz der Batterieladung (0-100). *(Anzahl)*
* **IsPlugged**: ein boolescher Wert, der angibt, ob das Gerät eingesteckt ist *(boolesch)*
Anwendungen sollten in der Regel `window.addEventListener` verwenden, um einen Event-Listener hinzuzufügen, nachdem das `deviceready` -Event ausgelöst wurde.
### Unterstützte Plattformen
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
### Beispiel
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
Das Ereignis wird ausgelöst, wenn der Prozentsatz der Batterieladung den kritischen Akku-Schwellenwert erreicht hat. Der Wert ist gerätespezifisch.
Der `batterylow` Handler übergibt ein Objekt mit zwei Eigenschaften:
* **Ebene**: der Prozentsatz der Batterieladung (0-100). *(Anzahl)*
* **IsPlugged**: ein boolescher Wert, der angibt, ob das Gerät eingesteckt ist *(boolesch)*
Anwendungen sollten in der Regel `window.addEventListener` verwenden, um einen Event-Listener hinzuzufügen, nachdem das `deviceready` -Event ausgelöst wurde.
### Unterstützte Plattformen
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
### Beispiel
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,151 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-battery-status
[![Build Status](https://travis-ci.org/apache/cordova-plugin-battery-status.svg)](https://travis-ci.org/apache/cordova-plugin-battery-status)
Este plugin proporciona una implementación de una versión antigua de la [Batería estado eventos API](http://www.w3.org/TR/2011/WD-battery-status-20110915/).
Agrega los siguientes tres `window` eventos:
* batterystatus
* batterycritical
* batterylow
## Instalación
cordova plugin add cordova-plugin-battery-status
## batterystatus
Este evento se desencadena cuando cambia el porcentaje de carga de la batería en menos de 1 por ciento, o si el aparato está enchufado o desenchufado.
El controlador del estado de batería se pasa un objeto que contiene dos propiedades:
* **level**: el porcentaje de carga de la batería (0-100). *(Número)*
* **isPlugged**: un valor booleano que indica si el dispositivo está conectado pulg *(Boolean)*
Las aplicaciones normalmente deben utilizar `window.addEventListener` para conectar un detector de eventos después de la `deviceready` evento incendios.
### Plataformas soportadas
* Amazon fire OS
* iOS
* Android
* BlackBerry 10
* Windows Phone 7 y 8
* Windows (sólo Windows Phone 8.1)
* Tizen
* Firefox OS
### Android y Amazon fuego OS caprichos
* ADVERTENCIA: el Android + fuego OS implementaciones son codiciosas y uso prolongado agotará la batería del usuario.
### Windows Phone 7 y 8 rarezas
Windows Phone 7 no proporciona una API nativa para determinar el nivel de batería, lo que `level` no está disponible. El `isPlugged` parámetro *es* apoyado.
### Windows rarezas
8.1 de Windows Phone no permite `isPlugged` parámetro. El parámetro `level` *es* apoyado.
### Ejemplo
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
El evento se desencadena cuando el porcentaje de carga de la batería ha alcanzado el umbral crítico de batería. El valor es específica del dispositivo.
El controlador `batterycritical` se pasa un objeto que contiene dos propiedades:
* **level**: el porcentaje de carga de la batería (0-100). *(Número)*
* **isPlugged**: un valor booleano que indica si el dispositivo está conectado pulg *(Boolean)*
Las aplicaciones normalmente deben utilizar `window.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`.
### Plataformas soportadas
* Amazon fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
* Windows (sólo Windows Phone 8.1)
### Windows rarezas
8.1 de Windows Phone se disparará `batterycritical` evento independientemente del estado tapado porque no es compatible.
### Ejemplo
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
El evento se desencadena cuando el porcentaje de carga de la batería ha alcanzado el umbral de batería baja, el valor específico del dispositivo.
El controlador de `batterylow` se pasa un objeto que contiene dos propiedades:
* **level**: el porcentaje de carga de la batería (0-100). *(Número)*
* **isPlugged**: un valor booleano que indica si el dispositivo está conectado pulg *(Boolean)*
Las aplicaciones normalmente deben utilizar `window.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`.
### Plataformas soportadas
* Amazon fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
* Windows (sólo Windows Phone 8.1)
### Windows rarezas
8.1 de Windows Phone se disparará `batterylow` evento independientemente del estado tapado porque no es compatible.
### Ejemplo
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,132 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-battery-status
Este plugin proporciona una implementación de una versión antigua de la [Batería estado eventos API][1].
[1]: http://www.w3.org/TR/2011/WD-battery-status-20110915/
Agrega los siguientes tres `window` eventos:
* batterystatus
* batterycritical
* batterylow
## Instalación
cordova plugin add cordova-plugin-battery-status
## batterystatus
Este evento se desencadena cuando cambia el porcentaje de carga de la batería en menos de 1 por ciento, o si el aparato está enchufado o desenchufado.
El controlador del estado de batería se pasa un objeto que contiene dos propiedades:
* **level**: el porcentaje de carga de la batería (0-100). *(Número)*
* **isPlugged**: un valor booleano que indica si el dispositivo está conectado pulg *(Boolean)*
Las aplicaciones normalmente deben utilizar `window.addEventListener` para conectar un detector de eventos después de la `deviceready` evento incendios.
### Plataformas soportadas
* Amazon fire OS
* iOS
* Android
* BlackBerry 10
* Windows Phone 7 y 8
* Tizen
* Firefox OS
### Windows Phone 7 y 8 rarezas
Windows Phone 7 no proporciona una API nativa para determinar el nivel de batería, lo que `level` no está disponible. El `isPlugged` parámetro *es* apoyado.
### Ejemplo
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
El evento se desencadena cuando el porcentaje de carga de la batería ha alcanzado el umbral crítico de batería. El valor es específica del dispositivo.
El controlador `batterycritical` se pasa un objeto que contiene dos propiedades:
* **level**: el porcentaje de carga de la batería (0-100). *(Número)*
* **isPlugged**: un valor booleano que indica si el dispositivo está conectado pulg *(Boolean)*
Las aplicaciones normalmente deben utilizar `window.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`.
### Plataformas soportadas
* Amazon fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
### Ejemplo
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
El evento se desencadena cuando el porcentaje de carga de la batería ha alcanzado el umbral de batería baja, el valor específico del dispositivo.
El controlador de `batterylow` se pasa un objeto que contiene dos propiedades:
* **level**: el porcentaje de carga de la batería (0-100). *(Número)*
* **isPlugged**: un valor booleano que indica si el dispositivo está conectado pulg *(Boolean)*
Las aplicaciones normalmente deben utilizar `window.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`.
### Plataformas soportadas
* Amazon fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
### Ejemplo
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,151 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# Cordova-plugin-batterie-statut
[![Build Status](https://travis-ci.org/apache/cordova-plugin-battery-status.svg)](https://travis-ci.org/apache/cordova-plugin-battery-status)
Ce plugin fournit une implémentation d'une ancienne version de [Batterie Status événements API](http://www.w3.org/TR/2011/WD-battery-status-20110915/).
Il ajoute les trois `window` des événements :
* batterystatus
* batterycritical
* batterylow
## Installation
cordova plugin add cordova-plugin-battery-status
## batterystatus
L'évènement se déclenche lorsque le taux de charge de la batterie gagne ou perd au moins un pourcent, ou quand l'appareil est branché ou débranché.
Le gestionnaire est appelé avec un objet contenant deux propriétés :
* **level** : le taux de charge de la batterie (0-100). *(Number)*
* **isPlugged** : un booléen indiquant si l'appareil est en cours de chargement ou non. *(Boolean)*
Les applications doivent généralement utiliser `window.addEventListener` pour attacher un écouteur d'événements après le `deviceready` événement se déclenche.
### Plates-formes supportées
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Windows Phone 7 et 8
* Windows (Windows Phone 8.1 uniquement)
* Paciarelli
* Firefox OS
### Android et Amazon Fire OS bizarreries
* AVERTISSEMENT : l'Android + feu OS implémentations sont avides et utilisation prolongée s'évacuera pile de l'utilisateur.
### Notes au sujet de Windows Phone 7 et 8
Windows Phone 7 ne fournit pas d'API native pour déterminer le niveau de la batterie, de ce fait la propriété `level` n'est pas disponible. La propriété `isPlugged` *est* quant à elle prise en charge.
### Bizarreries de Windows
8.1 de Windows Phone ne prend pas de paramètre `isPlugged` . Le `level` paramètre *is* pris en charge.
### Exemple
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
L'évènement se déclenche lorsque le pourcentage de charge de la batterie a atteint un seuil critique. Cette valeur est spécifique à l'appareil.
Le gestionnaire `batterycritical` est appelé avec un objet contenant deux propriétés :
* **level** : le taux de charge de la batterie (0-100). *(Number)*
* **isPlugged** : un booléen indiquant si l'appareil est en cours de chargement ou non. *(Boolean)*
Les applications devraient en général utiliser `window.addEventListener` pour attacher un écouteur d'évènements, une fois l'évènement `deviceready` déclenché.
### Plates-formes supportées
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Paciarelli
* Firefox OS
* Windows (Windows Phone 8.1 uniquement)
### Bizarreries de Windows
Windows Phone 8.1 tirera `batterycritical` épreuve que l'État branché car il n'est pas supportée.
### Exemple
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
L'évènement se déclenche lorsque le pourcentage de charge de la batterie a atteint un niveau faible, cette valeur est spécifique à l'appareil.
Le gestionnaire `batterylow` est appelé avec un objet contenant deux propriétés :
* **level** : le taux de charge de la batterie (0-100). *(Number)*
* **isPlugged** : un booléen indiquant si l'appareil est en cours de chargement ou non. *(Boolean)*
Les applications devraient en général utiliser `window.addEventListener` pour attacher un écouteur d'évènements, une fois l'évènement `deviceready` déclenché.
### Plates-formes supportées
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Paciarelli
* Firefox OS
* Windows (Windows Phone 8.1 uniquement)
### Bizarreries de Windows
Windows Phone 8.1 tirera `batterylow` épreuve que l'État branché car il n'est pas supportée.
### Exemple
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,132 @@
<!---
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.
-->
# org.Apache.Cordova.Battery inscrits
Ce plugin fournit une implémentation d'une ancienne version de [Batterie Status événements API][1].
[1]: http://www.w3.org/TR/2011/WD-battery-status-20110915/
Il ajoute les trois `window` des événements :
* batterystatus
* batterycritical
* batterylow
## Installation
cordova plugin add cordova-plugin-battery-status
## batterystatus
L'évènement se déclenche lorsque le taux de charge de la batterie gagne ou perd au moins un pourcent, ou quand l'appareil est branché ou débranché.
Le gestionnaire est appelé avec un objet contenant deux propriétés :
* **level** : le taux de charge de la batterie (0-100). *(Number)*
* **isPlugged** : un booléen indiquant si l'appareil est en cours de chargement ou non. *(Boolean)*
Les applications doivent généralement utiliser `window.addEventListener` pour attacher un écouteur d'événements après le `deviceready` événement se déclenche.
### Plates-formes prises en charge
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Windows Phone 7 et 8
* Paciarelli
* Firefox OS
### Notes au sujet de Windows Phone 7 et 8
Windows Phone 7 ne fournit pas d'API native pour déterminer le niveau de la batterie, de ce fait la propriété `level` n'est pas disponible. La propriété `isPlugged` *est* quant à elle prise en charge.
### Exemple
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
L'évènement se déclenche lorsque le pourcentage de charge de la batterie a atteint un seuil critique. Cette valeur est spécifique à l'appareil.
Le gestionnaire `batterycritical` est appelé avec un objet contenant deux propriétés :
* **niveau**: le pourcentage de charge de la batterie (0-100). *(Nombre)*
* **isPlugged**: valeur booléenne qui indique si l'appareil n'est branché *(Boolean)*
Les applications devraient en général utiliser `window.addEventListener` pour attacher un écouteur d'évènements, une fois l'évènement `deviceready` déclenché.
### Plates-formes prises en charge
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Paciarelli
* Firefox OS
### Exemple
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
L'évènement se déclenche lorsque le pourcentage de charge de la batterie a atteint un niveau faible, cette valeur est spécifique à l'appareil.
Le gestionnaire `batterylow` est appelé avec un objet contenant deux propriétés :
* **niveau**: le pourcentage de charge de la batterie (0-100). *(Nombre)*
* **isPlugged**: valeur booléenne qui indique si l'appareil n'est branché *(Boolean)*
Les applications devraient en général utiliser `window.addEventListener` pour attacher un écouteur d'évènements, une fois l'évènement `deviceready` déclenché.
### Plates-formes prises en charge
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Paciarelli
* Firefox OS
### Exemple
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,151 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-battery-status
[![Build Status](https://travis-ci.org/apache/cordova-plugin-battery-status.svg)](https://travis-ci.org/apache/cordova-plugin-battery-status)
Questo plugin fornisce un'implementazione di una vecchia versione dell' [API di eventi lo stato della batteria](http://www.w3.org/TR/2011/WD-battery-status-20110915/).
Aggiunge i seguenti tre `window` eventi:
* batterystatus
* batterycritical
* batterylow
## Installazione
cordova plugin add cordova-plugin-battery-status
## batterystatus
Questo evento viene generato quando la percentuale di carica della batteria cambia almeno l'1 per cento, o se il dispositivo è collegato o scollegato.
Il gestore di stato della batteria viene passato un oggetto che contiene due proprietà:
* **livello**: la percentuale di carica della batteria (0-100). *(Numero)*
* **isPlugged**: un valore booleano che indica se il dispositivo è collegato poll *(Boolean)*
Applicazioni in genere è necessario utilizzare `window.addEventListener` per fissare un listener di eventi dopo il `deviceready` evento incendi.
### Piattaforme supportate
* Amazon fuoco OS
* iOS
* Android
* BlackBerry 10
* Windows Phone 7 e 8
* Windows (solo Windows Phone 8.1)
* Tizen
* Firefox OS
### Android e Amazon fuoco OS stranezze
* Avviso: il Android + fuoco OS implementazioni sono avide e uso prolungato si scaricherà la batteria dell'utente.
### Windows Phone 7 e 8 stranezze
Windows Phone 7 non fornisce le API native per determinare il livello della batteria, così la `level` proprietà non è disponibile. Il `isPlugged` parametro *è* supportato.
### Stranezze di Windows
8.1 di Windows Phone non supporta il parametro `isPlugged` . Il `level` parametro *is* supportata.
### Esempio
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
L'evento viene generato quando la percentuale di carica della batteria ha raggiunto la soglia critica di batteria. Il valore è specifico del dispositivo.
Il `batterycritical` gestore viene passato un oggetto che contiene due proprietà:
* **livello**: la percentuale di carica della batteria (0-100). *(Numero)*
* **isPlugged**: un valore booleano che indica se il dispositivo è collegato poll *(Boolean)*
Applicazioni in genere è necessario utilizzare `window.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi.
### Piattaforme supportate
* Amazon fuoco OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
* Windows (solo Windows Phone 8.1)
### Stranezze di Windows
Windows Phone 8.1 vengano attivati `batterycritical` evento indipendentemente dallo stato tappato, come non è supportato.
### Esempio
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
L'evento viene generato quando la percentuale di carica della batteria ha raggiunto la soglia di batteria scarica, il valore specifico del dispositivo.
Il `batterylow` gestore viene passato un oggetto che contiene due proprietà:
* **livello**: la percentuale di carica della batteria (0-100). *(Numero)*
* **isPlugged**: un valore booleano che indica se il dispositivo è collegato poll *(Boolean)*
Applicazioni in genere è necessario utilizzare `window.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi.
### Piattaforme supportate
* Amazon fuoco OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
* Windows (solo Windows Phone 8.1)
### Stranezze di Windows
Windows Phone 8.1 vengano attivati `batterylow` evento indipendentemente dallo stato tappato, come non è supportato.
### Esempio
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,132 @@
<!---
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.
-->
# org.apache.Cordova.Battery-status
Questo plugin fornisce un'implementazione di una vecchia versione dell' [API di eventi lo stato della batteria][1].
[1]: http://www.w3.org/TR/2011/WD-battery-status-20110915/
Aggiunge i seguenti tre `window` eventi:
* batterystatus
* batterycritical
* batterylow
## Installazione
cordova plugin add cordova-plugin-battery-status
## batterystatus
Questo evento viene generato quando la percentuale di carica della batteria cambia almeno l'1 per cento, o se il dispositivo è collegato o scollegato.
Il gestore di stato della batteria viene passato un oggetto che contiene due proprietà:
* **livello**: la percentuale di carica della batteria (0-100). *(Numero)*
* **isPlugged**: un valore booleano che indica se il dispositivo è collegato poll *(Boolean)*
Applicazioni in genere è necessario utilizzare `window.addEventListener` per fissare un listener di eventi dopo il `deviceready` evento incendi.
### Piattaforme supportate
* Amazon fuoco OS
* iOS
* Android
* BlackBerry 10
* Windows Phone 7 e 8
* Tizen
* Firefox OS
### Windows Phone 7 e 8 stranezze
Windows Phone 7 non fornisce le API native per determinare il livello della batteria, così la `level` proprietà non è disponibile. Il `isPlugged` parametro *è* supportato.
### Esempio
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
L'evento viene generato quando la percentuale di carica della batteria ha raggiunto la soglia critica di batteria. Il valore è specifico del dispositivo.
Il `batterycritical` gestore viene passato un oggetto che contiene due proprietà:
* **livello**: la percentuale di carica della batteria (0-100). *(Numero)*
* **isPlugged**: un valore booleano che indica se il dispositivo è collegato poll *(Boolean)*
Applicazioni in genere è necessario utilizzare `window.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi.
### Piattaforme supportate
* Amazon fuoco OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
### Esempio
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
L'evento viene generato quando la percentuale di carica della batteria ha raggiunto la soglia di batteria scarica, il valore specifico del dispositivo.
Il `batterylow` gestore viene passato un oggetto che contiene due proprietà:
* **livello**: la percentuale di carica della batteria (0-100). *(Numero)*
* **isPlugged**: un valore booleano che indica se il dispositivo è collegato poll *(Boolean)*
Applicazioni in genere è necessario utilizzare `window.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi.
### Piattaforme supportate
* Amazon fuoco OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
### Esempio
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,151 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-battery-status
[![Build Status](https://travis-ci.org/apache/cordova-plugin-battery-status.svg)](https://travis-ci.org/apache/cordova-plugin-battery-status)
このプラグインは、[バッテリ ステータス イベント API](http://www.w3.org/TR/2011/WD-battery-status-20110915/)の旧バージョンの実装を提供します.
次の 3 つを追加します `window` イベント。
* batterystatus
* batterycritical
* batterylow
## インストール
cordova plugin add cordova-plugin-battery-status
## batterystatus
バッテリーの充電の割合 1% 以上によって変更されたとき、またはデバイス接続している場合に発生します。
バッテリ状態ハンドラーは 2 つのプロパティを格納しているオブジェクトに渡されます。
* **レベル** バッテリーの充電量 0-100) の割合。*(数)*
* **起こしたり** デバイスが接続されてインチ*(ブール値)*かどうかを示すブール値
通常アプリケーションに使用する必要があります `window.addEventListener` 後のイベント リスナーをアタッチする、 `deviceready` イベントが発生します。
### サポートされているプラットフォーム
* アマゾン火 OS
* iOS
* アンドロイド
* ブラックベリー 10
* Windows Phone 7 と 8
* Windows (Windows Phone 8.1 のみ)
* Tizen
* Firefox の OS
### アンドロイドとアマゾン火 OS 癖
* 警告: Android + 火 OS 実装は欲張りな長期使用ユーザーのバッテリーを排出するでしょう。
### Windows Phone 7 と 8 癖
Windows Phone 7 は、バッテリーのレベルを決定するネイティブ Api を提供しませんので、 `level` プロパティは使用できません。`isPlugged`パラメーター*が*サポートされています。
### Windows の癖
Windows Phone 8.1`isPlugged`パラメーターをサポートしていません。 `level`のパラメーター*is*サポートされています。
### 例
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
バッテリーの充電の割合がバッテリ切れのしきい値に達したときに発生します。値は、デバイス固有です。
`batterycritical`ハンドラーは 2 つのプロパティを格納しているオブジェクトに渡されます。
* **レベル** バッテリーの充電量 0-100) の割合。*(数)*
* **起こしたり** デバイスが接続されてインチ*(ブール値)*かどうかを示すブール値
通常アプリケーションに使用する必要があります `window.addEventListener` 一度のイベント リスナーをアタッチし、 `deviceready` イベントが発生します。
### サポートされているプラットフォーム
* アマゾン火 OS
* iOS
* アンドロイド
* ブラックベリー 10
* Tizen
* Firefox の OS
* Windows (Windows Phone 8.1 のみ)
### Windows の癖
それはサポートされていないために、Windows Phone 8.1 は接続状態に関係なく`batterycritical`イベントを発生します。
### 例
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
バッテリーの充電の割合がバッテリ低下しきい値、デバイス固有の値に達したときに発生します。
`batterylow`ハンドラーは 2 つのプロパティを格納しているオブジェクトに渡されます。
* **レベル** バッテリーの充電量 0-100) の割合。*(数)*
* **起こしたり** デバイスが接続されてインチ*(ブール値)*かどうかを示すブール値
通常アプリケーションに使用する必要があります `window.addEventListener` 一度のイベント リスナーをアタッチし、 `deviceready` イベントが発生します。
### サポートされているプラットフォーム
* アマゾン火 OS
* iOS
* アンドロイド
* ブラックベリー 10
* Tizen
* Firefox の OS
* Windows (Windows Phone 8.1 のみ)
### Windows の癖
それはサポートされていないために、Windows Phone 8.1 は接続状態に関係なく`batterylow`イベントを発生します。
### 例
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,132 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-battery ステータス
このプラグインは、[バッテリ ステータス イベント API][1]の旧バージョンの実装を提供します.
[1]: http://www.w3.org/TR/2011/WD-battery-status-20110915/
次の 3 つを追加します `window` イベント。
* batterystatus
* batterycritical
* batterylow
## インストール
cordova plugin add cordova-plugin-battery-status
## batterystatus
バッテリーの充電の割合 1% 以上によって変更されたとき、またはデバイス接続している場合に発生します。
バッテリ状態ハンドラーは 2 つのプロパティを格納しているオブジェクトに渡されます。
* **レベル** バッテリーの充電量 0-100) の割合。*(数)*
* **起こしたり** デバイスが接続されてインチ*(ブール値)*かどうかを示すブール値
通常アプリケーションに使用する必要があります `window.addEventListener` 後のイベント リスナーをアタッチする、 `deviceready` イベントが発生します。
### サポートされているプラットフォーム
* アマゾン火 OS
* iOS
* アンドロイド
* ブラックベリー 10
* Windows Phone 7 と 8
* Tizen
* Firefox の OS
### Windows Phone 7 と 8 癖
Windows Phone 7 は、バッテリーのレベルを決定するネイティブ Api を提供しませんので、 `level` プロパティは使用できません。`isPlugged`パラメーター*が*サポートされています。
### 例
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
バッテリーの充電の割合がバッテリ切れのしきい値に達したときに発生します。値は、デバイス固有です。
`batterycritical`ハンドラーは 2 つのプロパティを格納しているオブジェクトに渡されます。
* **レベル** バッテリーの充電量 0-100) の割合。*(数)*
* **起こしたり** デバイスが接続されてインチ*(ブール値)*かどうかを示すブール値
通常アプリケーションに使用する必要があります `window.addEventListener` 一度のイベント リスナーをアタッチし、 `deviceready` イベントが発生します。
### サポートされているプラットフォーム
* アマゾン火 OS
* iOS
* アンドロイド
* ブラックベリー 10
* Tizen
* Firefox の OS
### 例
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
バッテリーの充電の割合がバッテリ低下しきい値、デバイス固有の値に達したときに発生します。
`batterylow`ハンドラーは 2 つのプロパティを格納しているオブジェクトに渡されます。
* **レベル** バッテリーの充電量 0-100) の割合。*(数)*
* **起こしたり** デバイスが接続されてインチ*(ブール値)*かどうかを示すブール値
通常アプリケーションに使用する必要があります `window.addEventListener` 一度のイベント リスナーをアタッチし、 `deviceready` イベントが発生します。
### サポートされているプラットフォーム
* アマゾン火 OS
* iOS
* アンドロイド
* ブラックベリー 10
* Tizen
* Firefox の OS
### 例
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,151 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-battery-status
[![Build Status](https://travis-ci.org/apache/cordova-plugin-battery-status.svg)](https://travis-ci.org/apache/cordova-plugin-battery-status)
이 플러그인에서는 [배터리 상태 이벤트 API](http://www.w3.org/TR/2011/WD-battery-status-20110915/) 의 이전 버전의 구현을.
그것은 다음과 같은 세 가지 추가 `window` 이벤트:
* batterystatus
* batterycritical
* batterylow
## 설치
cordova plugin add cordova-plugin-battery-status
## batterystatus
이 이벤트는 배터리 충전 비율 1% 이상에 의해 변경 될 때 또는 장치를 연결 하거나 분리 하는 경우 발생 합니다.
배터리 상태 처리기는 두 개의 속성이 포함 된 개체에 전달 됩니다.
* **수준**: 배터리 충전 (0-100)의 비율. *(수)*
* **isPlugged**: 장치 연결된 인치 *(부울)* 인지 여부를 나타내는 부울 값
일반적으로 응용 프로그램을 사용 해야 합니다 `window.addEventListener` 후 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* iOS
* 안 드 로이드
* 블랙베리 10
* Windows Phone 7과 8
* 윈도 (Windows Phone 8.1만)
* Tizen
* Firefox 운영 체제
### 안 드 로이드와 아마존 화재 OS 단점이
* 경고: 안 드 로이드 + 화재 OS 구현 욕심이 있으며 장기간된 사용 사용자의 배터리를 배출 합니다.
### Windows Phone 7, 8 특수
Windows Phone 7 배터리 수준을 확인 하려면 네이티브 Api를 제공 하지 않습니다 때문에 `level` 속성은 사용할 수 없습니다. `isPlugged`매개 변수는 *는* 지원.
### 윈도우 특수
Windows Phone 8.1 `isPlugged` 매개 변수를 지원 하지 않습니다. `level` 매개 변수는 *는* 지원.
### 예를 들어
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
이벤트 발생 때 배터리 충전 비율 배터리 위험 임계값에 도달 했습니다. 값은 장치 마다 다릅니다.
`batterycritical`처리기는 두 개의 속성이 포함 된 개체에 전달 됩니다:
* **수준**: 배터리 충전 (0-100)의 비율. *(수)*
* **isPlugged**: 장치 연결된 인치 *(부울)* 인지 여부를 나타내는 부울 값
일반적으로 응용 프로그램을 사용 해야 합니다 `window.addEventListener` 한번 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* iOS
* 안 드 로이드
* 블랙베리 10
* Tizen
* Firefox 운영 체제
* 윈도 (Windows Phone 8.1만)
### 윈도우 특수
으로 지원 되지 않습니다 Windows Phone 8.1 연결된 상태 `batterycritical` 이벤트를 발생 합니다.
### 예를 들어
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
이벤트 발생 때 배터리 충전 비율 낮은 배터리 임계값, 특정 값에 도달 했습니다.
`batterylow`처리기는 두 개의 속성이 포함 된 개체에 전달 됩니다:
* **수준**: 배터리 충전 (0-100)의 비율. *(수)*
* **isPlugged**: 장치 연결된 인치 *(부울)* 인지 여부를 나타내는 부울 값
일반적으로 응용 프로그램을 사용 해야 합니다 `window.addEventListener` 한번 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* iOS
* 안 드 로이드
* 블랙베리 10
* Tizen
* Firefox 운영 체제
* 윈도 (Windows Phone 8.1만)
### 윈도우 특수
으로 지원 되지 않습니다 Windows Phone 8.1 연결된 상태 `batterylow` 이벤트를 발생 합니다.
### 예를 들어
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,132 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-battery 상태
이 플러그인에서는 [배터리 상태 이벤트 API][1] 의 이전 버전의 구현을.
[1]: http://www.w3.org/TR/2011/WD-battery-status-20110915/
그것은 다음과 같은 세 가지 추가 `window` 이벤트:
* batterystatus
* batterycritical
* batterylow
## 설치
cordova plugin add cordova-plugin-battery-status
## batterystatus
이 이벤트는 배터리 충전 비율 1% 이상에 의해 변경 될 때 또는 장치를 연결 하거나 분리 하는 경우 발생 합니다.
배터리 상태 처리기는 두 개의 속성이 포함 된 개체에 전달 됩니다.
* **수준**: 배터리 충전 (0-100)의 비율. *(수)*
* **isPlugged**: 장치 연결된 인치 *(부울)* 인지 여부를 나타내는 부울 값
일반적으로 응용 프로그램을 사용 해야 합니다 `window.addEventListener` 후 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* iOS
* 안 드 로이드
* 블랙베리 10
* Windows Phone 7과 8
* Tizen
* Firefox 운영 체제
### Windows Phone 7, 8 특수
Windows Phone 7 배터리 수준을 확인 하려면 네이티브 Api를 제공 하지 않습니다 때문에 `level` 속성은 사용할 수 없습니다. `isPlugged`매개 변수는 *는* 지원.
### 예를 들어
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
이벤트 발생 때 배터리 충전 비율 배터리 위험 임계값에 도달 했습니다. 값은 장치 마다 다릅니다.
`batterycritical`처리기는 두 개의 속성이 포함 된 개체에 전달 됩니다:
* **수준**: 배터리 충전 (0-100)의 비율. *(수)*
* **isPlugged**: 장치 연결된 인치 *(부울)* 인지 여부를 나타내는 부울 값
일반적으로 응용 프로그램을 사용 해야 합니다 `window.addEventListener` 한번 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* iOS
* 안 드 로이드
* 블랙베리 10
* Tizen
* Firefox 운영 체제
### 예를 들어
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
이벤트 발생 때 배터리 충전 비율 낮은 배터리 임계값, 특정 값에 도달 했습니다.
`batterylow`처리기는 두 개의 속성이 포함 된 개체에 전달 됩니다:
* **수준**: 배터리 충전 (0-100)의 비율. *(수)*
* **isPlugged**: 장치 연결된 인치 *(부울)* 인지 여부를 나타내는 부울 값
일반적으로 응용 프로그램을 사용 해야 합니다 `window.addEventListener` 한번 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* iOS
* 안 드 로이드
* 블랙베리 10
* Tizen
* Firefox 운영 체제
### 예를 들어
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,151 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-battery-status
[![Build Status](https://travis-ci.org/apache/cordova-plugin-battery-status.svg)](https://travis-ci.org/apache/cordova-plugin-battery-status)
Wtyczka stanowi implementację starą wersję [API zdarzeń stanu baterii](http://www.w3.org/TR/2011/WD-battery-status-20110915/).
To dodaje następujące trzy `window` zdarzenia:
* batterystatus
* batterycritical
* batterylow
## Instalacja
cordova plugin add cordova-plugin-battery-status
## batterystatus
To zdarzenie fires po zmianie procent naładowania baterii, przez co najmniej 1 procent, lub jeśli urządzenie jest podłączone lub odłączony.
Obsługi stan baterii jest przekazywany obiekt, który zawiera dwie właściwości:
* **poziom**: procent naładowania baterii (0-100). *(Liczba)*
* **isPlugged**: boolean, która wskazuje, czy urządzenie jest podłączony *(Boolean)*
Aplikacje zwykle należy użyć `window.addEventListener` Aby dołączyć słuchacza po `deviceready` pożary zdarzenia.
### Obsługiwane platformy
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Windows Phone 7 i 8
* Windows (tylko Windows Phone 8.1)
* Tizen
* Firefox OS
### Android i Amazon ogień OS dziwactwa
* Ostrzeżenie: Android + ogień OS implementacje są chciwi i długotrwałe stosowanie drenażu użytkownika baterii.
### Windows Phone 7 i 8 dziwactwa
Windows Phone 7 nie zapewniają native API do określenia poziomu baterii, więc `level` Właściwość jest niedostępny. `isPlugged`Parametr *jest* obsługiwany.
### Windows dziwactwa
Windows Phone 8.1 obsługuje parametr `isPlugged` . `Parametr <em>jest</em> obsługiwany.`
### Przykład
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
Zdarzenie odpala gdy procent naładowania baterii osiągnie próg rozładowanej baterii. Wartość jest specyficzne dla urządzenia.
`batterycritical`Obsługi jest przekazywany obiekt, który zawiera dwie właściwości:
* **poziom**: procent naładowania baterii (0-100). *(Liczba)*
* **isPlugged**: boolean, która wskazuje, czy urządzenie jest podłączony *(Boolean)*
Aplikacje zwykle należy użyć `window.addEventListener` Aby dołączyć słuchacza raz `deviceready` pożary zdarzenia.
### Obsługiwane platformy
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
* Windows (tylko Windows Phone 8.1)
### Windows dziwactwa
Windows Phone 8.1 będzie ogień `batterycritical` imprezy niezależnie od stanu podłączony, jak nie jest obsługiwany.
### Przykład
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
Zdarzenie odpala gdy procent naładowania baterii osiągnie próg niskiego poziomu baterii, wartości specyficzne dla urządzenia.
`batterylow`Obsługi jest przekazywany obiekt, który zawiera dwie właściwości:
* **poziom**: procent naładowania baterii (0-100). *(Liczba)*
* **isPlugged**: boolean, która wskazuje, czy urządzenie jest podłączony *(Boolean)*
Aplikacje zwykle należy użyć `window.addEventListener` Aby dołączyć słuchacza raz `deviceready` pożary zdarzenia.
### Obsługiwane platformy
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
* Windows (tylko Windows Phone 8.1)
### Windows dziwactwa
Windows Phone 8.1 będzie ogień `batterylow` imprezy niezależnie od stanu podłączony, jak nie jest obsługiwany.
### Przykład
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,132 @@
<!---
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.
-->
# org.Apache.Cordova.Battery stan
Wtyczka stanowi implementację starą wersję [API zdarzeń stanu baterii][1].
[1]: http://www.w3.org/TR/2011/WD-battery-status-20110915/
To dodaje następujące trzy `window` zdarzenia:
* batterystatus
* batterycritical
* batterylow
## Instalacja
cordova plugin add cordova-plugin-battery-status
## batterystatus
To zdarzenie fires po zmianie procent naładowania baterii, przez co najmniej 1 procent, lub jeśli urządzenie jest podłączone lub odłączony.
Obsługi stan baterii jest przekazywany obiekt, który zawiera dwie właściwości:
* **poziom**: procent naładowania baterii (0-100). *(Liczba)*
* **isPlugged**: boolean, która wskazuje, czy urządzenie jest podłączony *(Boolean)*
Aplikacje zwykle należy użyć `window.addEventListener` Aby dołączyć słuchacza po `deviceready` pożary zdarzenia.
### Obsługiwane platformy
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Windows Phone 7 i 8
* Tizen
* Firefox OS
### Windows Phone 7 i 8 dziwactwa
Windows Phone 7 nie zapewniają native API do określenia poziomu baterii, więc `level` Właściwość jest niedostępny. `isPlugged`Parametr *jest* obsługiwany.
### Przykład
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
Zdarzenie odpala gdy procent naładowania baterii osiągnie próg rozładowanej baterii. Wartość jest specyficzne dla urządzenia.
`batterycritical`Obsługi jest przekazywany obiekt, który zawiera dwie właściwości:
* **poziom**: procent naładowania baterii (0-100). *(Liczba)*
* **isPlugged**: boolean, która wskazuje, czy urządzenie jest podłączony *(logiczna)*
Aplikacje zwykle należy użyć `window.addEventListener` Aby dołączyć słuchacza raz `deviceready` pożary zdarzenia.
### Obsługiwane platformy
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
### Przykład
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
Zdarzenie odpala gdy procent naładowania baterii osiągnie próg niskiego poziomu baterii, wartości specyficzne dla urządzenia.
`batterylow`Obsługi jest przekazywany obiekt, który zawiera dwie właściwości:
* **poziom**: procent naładowania baterii (0-100). *(Liczba)*
* **isPlugged**: boolean, która wskazuje, czy urządzenie jest podłączony *(logiczna)*
Aplikacje zwykle należy użyć `window.addEventListener` Aby dołączyć słuchacza raz `deviceready` pożary zdarzenia.
### Obsługiwane platformy
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
### Przykład
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,132 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-battery-status
Этот плагин предоставляет реализацию старой версии [API Событий Статуса Батареи][1].
[1]: http://www.w3.org/TR/2011/WD-battery-status-20110915/
API добавляет следующие три события для объекта `window`:
* batterystatus
* batterycritical
* batterylow
## Установка
cordova plugin add cordova-plugin-battery-status
## batterystatus
Это событие возникает при изменении процент заряда батареи по крайней мере на 1%, или если устройство подключается или отключается от заряжающего устройства.
Обработчику события batterystatus передается объект, содержащий два свойства:
* **level**: процент заряда батареи (0-100). *(Число)*
* **isPlugged**: логическое значение, указывающее, подключено ли устройство к заряжающему устройству *(Boolean)*
Приложения обычно должны использовать `window.addEventListener` прикрепить прослушиватель событий после `deviceready` пожаров события.
### Поддерживаемые платформы
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Windows Phone 7 и 8
* Tizen
* Firefox OS
### Особенности Windows Phone 7 и 8
Windows Phone 7 не обеспечивает API, чтобы определить уровень заряда батареи, так что свойство `level` недоступно. Параметр `isPlugged` *поддерживается*.
### Пример
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
Событие возникает, когда процент заряда батареи почти достиг порога полной разрядки батареи. Значение этого порога зависит от конкретного устройства.
Обработчику события `batterycritical` передается объект, содержащий два свойства:
* **level**: процент заряда батареи (0-100). *(Число)*
* **isPlugged**: логическое значение, указывающее, подключено ли устройство к заряжающему устройству *(Boolean)*
Приложения обычно должны использовать `window.addEventListener` чтобы добавить обработчик события после того как произойдет событие `deviceready`.
### Поддерживаемые платформы
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
### Пример
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
Событие возникает, когда процент заряда батареи достигает порога низкого заряда батареи, это значение зависит от конкретного устройства.
Обработчику события `batterylow` передается объект, содержащий два свойства:
* **level**: процент заряда батареи (0-100). *(Число)*
* **isPlugged**: логическое значение, указывающее, подключено ли устройство к заряжающему устройству *(Boolean)*
Приложения обычно должны использовать `window.addEventListener` чтобы добавить обработчик события после того как произойдет событие `deviceready`.
### Поддерживаемые платформы
* Amazon Fire OS
* iOS
* Android
* BlackBerry 10
* Tizen
* Firefox OS
### Пример
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,151 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-battery-status
[![Build Status](https://travis-ci.org/apache/cordova-plugin-battery-status.svg)](https://travis-ci.org/apache/cordova-plugin-battery-status)
這個外掛程式提供的舊版本的[電池狀態事件 API](http://www.w3.org/TR/2011/WD-battery-status-20110915/)實現的.
它將添加以下三 `window` 事件:
* batterystatus
* batterycritical
* batterylow
## 安裝
cordova plugin add cordova-plugin-battery-status
## batterystatus
當電池計量的百分比改變了至少 1%,或如果在插入或拔出該設備會觸發此事件。
電池狀態處理常式傳遞一個物件,包含兩個屬性:
* **級別**: 電池充電 (0-100) 的百分比。*(人數)*
* **isPlugged** 一個布林值,該值指示設備是否插*(布林值)*
應用程式通常應使用 `window.addEventListener` 將附加一個事件攔截器後的 `deviceready` 事件觸發。
### 支援的平臺
* 亞馬遜火 OS
* iOS
* Android 系統
* 黑莓 10
* Windows Phone 7 和 8
* Windows (僅限於 Windows Phone 8.1)
* Tizen
* 火狐瀏覽器作業系統
### 安卓和亞馬遜火 OS 怪癖
* 警告: Android + 火 OS 實現都是貪婪和長時間的使用會流失使用者的電池。
### Windows Phone 7 和 8 怪癖
Windows Phone 7 並不提供本機 Api 來確定電池計量水準,所以 `level` 是不可用的屬性。`isPlugged`參數**支援的。
### Windows 的怪癖
Windows Phone 8.1 不支援`isPlugged`參數。 `水準`參數**支援。
### 示例
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
當電池計量的百分比已達到關鍵電池閾值時,將觸發該事件。值是特定于設備。
`batterycritical`處理常式傳遞一個物件,包含兩個屬性:
* **級別**: 電池充電 (0-100) 的百分比。*(人數)*
* **isPlugged** 一個布林值,該值指示設備是否插*(布林值)*
應用程式通常應使用 `window.addEventListener` 將一個事件攔截器附加一次 `deviceready` 事件火災。
### 支援的平臺
* 亞馬遜火 OS
* iOS
* Android 系統
* 黑莓 10
* Tizen
* 火狐瀏覽器作業系統
* Windows (僅限於 Windows Phone 8.1)
### Windows 的怪癖
Windows Phone 8.1 會觸發`batterycritical`事件任何堵塞狀態,因為它不支援。
### 示例
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
當電池計量的百分比已達到電池計量低門檻,設備特定值時,將觸發該事件。
`batterylow`處理常式傳遞一個物件,包含兩個屬性:
* **級別**: 電池充電 (0-100) 的百分比。*(人數)*
* **isPlugged** 一個布林值,該值指示設備是否插*(布林值)*
應用程式通常應使用 `window.addEventListener` 將一個事件攔截器附加一次 `deviceready` 事件火災。
### 支援的平臺
* 亞馬遜火 OS
* iOS
* Android 系統
* 黑莓 10
* Tizen
* 火狐瀏覽器作業系統
* Windows (僅限於 Windows Phone 8.1)
### Windows 的怪癖
Windows Phone 8.1 會觸發`batterylow`事件任何堵塞狀態,因為它不支援。
### 示例
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,132 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-battery-地位
這個外掛程式提供的舊版本的[電池狀態事件 API][1]實現的.
[1]: http://www.w3.org/TR/2011/WD-battery-status-20110915/
它將添加以下三 `window` 事件:
* batterystatus
* batterycritical
* batterylow
## 安裝
cordova plugin add cordova-plugin-battery-status
## batterystatus
當電池計量的百分比改變了至少 1%,或如果在插入或拔出該設備會觸發此事件。
電池狀態處理常式傳遞一個物件,包含兩個屬性:
* **級別**: 電池充電 (0-100) 的百分比。*(人數)*
* **isPlugged** 一個布林值,該值指示設備是否插*(布林值)*
應用程式通常應使用 `window.addEventListener` 將附加一個事件攔截器後的 `deviceready` 事件觸發。
### 支援的平臺
* 亞馬遜火 OS
* iOS
* Android 系統
* 黑莓 10
* Windows Phone 7 和 8
* Tizen
* 火狐瀏覽器作業系統
### Windows Phone 7 和 8 怪癖
Windows Phone 7 並不提供本機 Api 來確定電池計量水準,所以 `level` 是不可用的屬性。`isPlugged`參數**支援的。
### 示例
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
當電池計量的百分比已達到關鍵電池閾值時,將觸發該事件。值是特定于設備。
`batterycritical`處理常式傳遞一個物件,包含兩個屬性:
* **級別**: 電池充電 (0-100) 的百分比。*(人數)*
* **isPlugged** 一個布林值,該值指示設備是否插*(布林值)*
應用程式通常應使用 `window.addEventListener` 將一個事件攔截器附加一次 `deviceready` 事件火災。
### 支援的平臺
* 亞馬遜火 OS
* iOS
* Android 系統
* 黑莓 10
* Tizen
* 火狐瀏覽器作業系統
### 示例
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
## batterylow
當電池計量的百分比已達到電池計量低門檻,設備特定值時,將觸發該事件。
`batterylow`處理常式傳遞一個物件,包含兩個屬性:
* **級別**: 電池充電 (0-100) 的百分比。*(人數)*
* **isPlugged** 一個布林值,該值指示設備是否插*(布林值)*
應用程式通常應使用 `window.addEventListener` 將一個事件攔截器附加一次 `deviceready` 事件火災。
### 支援的平臺
* 亞馬遜火 OS
* iOS
* Android 系統
* 黑莓 10
* Tizen
* 火狐瀏覽器作業系統
### 示例
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}

View File

@@ -0,0 +1,140 @@
{
"_args": [
[
{
"raw": "cordova-plugin-battery-status",
"scope": null,
"escapedName": "cordova-plugin-battery-status",
"name": "cordova-plugin-battery-status",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"D:\\pWork\\yunkong2.vis.cordova\\node_modules"
]
],
"_from": "cordova-plugin-battery-status@latest",
"_id": "cordova-plugin-battery-status@1.2.4",
"_inCache": true,
"_location": "/cordova-plugin-battery-status",
"_nodeVersion": "6.10.1",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/cordova-plugin-battery-status-1.2.4.tgz_1493685627359_0.5040916141588241"
},
"_npmUser": {
"name": "filmaj",
"email": "maj.fil@gmail.com"
},
"_npmVersion": "3.10.10",
"_phantomChildren": {},
"_requested": {
"raw": "cordova-plugin-battery-status",
"scope": null,
"escapedName": "cordova-plugin-battery-status",
"name": "cordova-plugin-battery-status",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"#USER"
],
"_resolved": "https://registry.npmjs.org/cordova-plugin-battery-status/-/cordova-plugin-battery-status-1.2.4.tgz",
"_shasum": "73a576afc0a61a9dd29aff7765907ecac0c9f1f9",
"_shrinkwrap": null,
"_spec": "cordova-plugin-battery-status",
"_where": "D:\\pWork\\yunkong2.vis.cordova\\node_modules",
"author": {
"name": "Apache Software Foundation"
},
"bugs": {
"url": "https://github.com/apache/cordova-plugin-battery-status/issues"
},
"cordova": {
"id": "cordova-plugin-battery-status",
"platforms": [
"android",
"amazon-fireos",
"ubuntu",
"ios",
"blackberry10",
"wp7",
"wp8",
"tizen",
"firefoxos"
]
},
"dependencies": {},
"description": "Cordova Battery Plugin",
"devDependencies": {
"jshint": "^2.6.0"
},
"directories": {},
"dist": {
"shasum": "73a576afc0a61a9dd29aff7765907ecac0c9f1f9",
"tarball": "https://registry.npmjs.org/cordova-plugin-battery-status/-/cordova-plugin-battery-status-1.2.4.tgz"
},
"engines": {
"cordovaDependencies": {
"2.0.0": {
"cordova": ">100"
}
}
},
"homepage": "https://github.com/apache/cordova-plugin-battery-status#readme",
"keywords": [
"cordova",
"battery",
"ecosystem:cordova",
"cordova-android",
"cordova-amazon-fireos",
"cordova-ubuntu",
"cordova-ios",
"cordova-blackberry10",
"cordova-wp7",
"cordova-wp8",
"cordova-tizen",
"cordova-firefoxos"
],
"license": "Apache-2.0",
"maintainers": [
{
"name": "bowserj",
"email": "bowserj@apache.org"
},
{
"name": "csantanapr",
"email": "csantana23@gmail.com"
},
{
"name": "filmaj",
"email": "maj.fil@gmail.com"
},
{
"name": "purplecabbage",
"email": "purplecabbage@gmail.com"
},
{
"name": "shazron",
"email": "shazron@gmail.com"
},
{
"name": "stevegill",
"email": "stevengill97@gmail.com"
}
],
"name": "cordova-plugin-battery-status",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/apache/cordova-plugin-battery-status.git"
},
"scripts": {
"jshint": "node node_modules/jshint/bin/jshint www && node node_modules/jshint/bin/jshint src && node node_modules/jshint/bin/jshint tests",
"test": "npm run jshint"
},
"types": "./types/index.d.ts",
"version": "1.2.4"
}

View File

@@ -0,0 +1,133 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
id="cordova-plugin-battery-status"
version="1.2.4">
<name>Battery</name>
<description>Cordova Battery Plugin</description>
<license>Apache 2.0</license>
<keywords>cordova,battery</keywords>
<repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-battery-status.git</repo>
<issue>https://issues.apache.org/jira/browse/CB/component/12320643</issue>
<js-module src="www/battery.js" name="battery">
<clobbers target="navigator.battery" />
</js-module>
<!-- android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="Battery" >
<param name="android-package" value="org.apache.cordova.batterystatus.BatteryListener"/>
</feature>
</config-file>
<source-file src="src/android/BatteryListener.java" target-dir="src/org/apache/cordova/batterystatus" />
</platform>
<!-- amazon-fireos -->
<platform name="amazon-fireos">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="Battery" >
<param name="android-package" value="org.apache.cordova.batterystatus.BatteryListener"/>
</feature>
</config-file>
<source-file src="src/android/BatteryListener.java" target-dir="src/org/apache/cordova/batterystatus" />
</platform>
<!-- ubuntu -->
<platform name="ubuntu">
<header-file src="src/ubuntu/battery.h" />
<source-file src="src/ubuntu/battery.cpp" />
</platform>
<!-- ios -->
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="Battery">
<param name="ios-package" value="CDVBattery" />
</feature>
</config-file>
<header-file src="src/ios/CDVBattery.h" />
<source-file src="src/ios/CDVBattery.m" />
</platform>
<!-- blackberry10 -->
<platform name="blackberry10">
<source-file src="src/blackberry10/index.js" target-dir="Battery" />
<config-file target="www/config.xml" parent="/widget">
<feature name="Battery" value="Battery"/>
</config-file>
</platform>
<!-- wp7 -->
<platform name="wp7">
<config-file target="config.xml" parent="/*">
<feature name="Battery">
<param name="wp-package" value="Battery"/>
</feature>
</config-file>
<source-file src="src/wp/Battery.cs" />
</platform>
<!-- wp8 -->
<platform name="wp8">
<config-file target="config.xml" parent="/*">
<feature name="Battery">
<param name="wp-package" value="Battery"/>
</feature>
</config-file>
<source-file src="src/wp/Battery.cs" />
</platform>
<!-- windows -->
<platform name="windows">
<js-module src="src/windows/BatteryProxy.js" name="Battery">
<runs />
</js-module>
<framework src="src/windows/BatteryStatus.winmd" custom="true" target="phone"/>
</platform>
<!-- tizen -->
<platform name="tizen">
<js-module src="src/tizen/BatteryStatusProxy.js" name="BatteryStatusProxy">
<runs/>
</js-module>
</platform>
<!-- firefoxos -->
<platform name="firefoxos">
<js-module src="src/firefoxos/BatteryProxy.js" name="Battery">
<runs />
</js-module>
</platform>
<!-- browser -->
<platform name="browser">
<js-module src="src/browser/BatteryProxy.js" name="Battery">
<runs />
</js-module>
</platform>
</plugin>

View File

@@ -0,0 +1,163 @@
/*
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.batterystatus;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginResult;
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;
public class BatteryListener extends CordovaPlugin {
private static final String LOG_TAG = "BatteryManager";
BroadcastReceiver receiver;
private CallbackContext batteryCallbackContext = null;
/**
* Constructor.
*/
public BatteryListener() {
this.receiver = null;
}
/**
* Executes the request.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback context 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) {
if (action.equals("start")) {
if (this.batteryCallbackContext != null) {
callbackContext.error( "Battery listener already running.");
return true;
}
this.batteryCallbackContext = callbackContext;
// We need to listen to power events to update battery status
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
if (this.receiver == null) {
this.receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateBatteryInfo(intent);
}
};
webView.getContext().registerReceiver(this.receiver, intentFilter);
}
// Don't return any result now, since status results will be sent when events come in from broadcast receiver
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
}
else if (action.equals("stop")) {
removeBatteryListener();
this.sendUpdate(new JSONObject(), false); // release status callback in JS side
this.batteryCallbackContext = null;
callbackContext.success();
return true;
}
return false;
}
/**
* Stop battery receiver.
*/
public void onDestroy() {
removeBatteryListener();
}
/**
* Stop battery receiver.
*/
public void onReset() {
removeBatteryListener();
}
/**
* Stop the battery receiver and set it to null.
*/
private void removeBatteryListener() {
if (this.receiver != null) {
try {
webView.getContext().unregisterReceiver(this.receiver);
this.receiver = null;
} catch (Exception e) {
LOG.e(LOG_TAG, "Error unregistering battery receiver: " + e.getMessage(), e);
}
}
}
/**
* Creates a JSONObject with the current battery information
*
* @param batteryIntent the current battery information
* @return a JSONObject containing the battery status information
*/
private JSONObject getBatteryInfo(Intent batteryIntent) {
JSONObject obj = new JSONObject();
try {
obj.put("level", batteryIntent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, 0));
obj.put("isPlugged", batteryIntent.getIntExtra(android.os.BatteryManager.EXTRA_PLUGGED, -1) > 0 ? true : false);
} catch (JSONException e) {
LOG.e(LOG_TAG, e.getMessage(), e);
}
return obj;
}
/**
* Updates the JavaScript side whenever the battery changes
*
* @param batteryIntent the current battery information
* @return
*/
private void updateBatteryInfo(Intent batteryIntent) {
sendUpdate(this.getBatteryInfo(batteryIntent), true);
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param connection the network info to set as navigator.connection
*/
private void sendUpdate(JSONObject info, boolean keepCallback) {
if (this.batteryCallbackContext != null) {
PluginResult result = new PluginResult(PluginResult.Status.OK, info);
result.setKeepCallback(keepCallback);
this.batteryCallbackContext.sendPluginResult(result);
}
}
}

View File

@@ -0,0 +1,79 @@
/*
*
* 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.
*
*/
/* global PluginResult */
var _clientListeners = {},
_webkitBattery = navigator.webkitBattery || navigator.battery;
module.exports = {
start: function (success, fail, args, env) {
var result = new PluginResult(args, env),
listener = function (info) {
var resultInfo = {};
if (info) {
if (info.srcElement) {
//webkitBattery listeners store webkitBattery in srcElement object
info = info.srcElement;
}
//put data from webkitBattery into a format cordova expects
//webkitBattery seems to return level as a decimal pre 10.2
resultInfo.level = info.level <= 1 ? info.level * 100 : info.level;
resultInfo.isPlugged = info.charging;
}
result.callbackOk(resultInfo, true);
};
if (_clientListeners[env.webview.id]) {
//TODO: Change back to erroring out after reset is implemented
//result.error("Battery listener already running");
_webkitBattery.onchargingchange = null;
_webkitBattery.onlevelchange = null;
}
_clientListeners[env.webview.id] = listener;
_webkitBattery.onchargingchange = listener;
_webkitBattery.onlevelchange = listener;
setTimeout(function(){
//Call callback with webkitBattery data right away
listener(_webkitBattery);
});
result.noResult(true);
},
stop: function (success, fail, args, env) {
var result = new PluginResult(args, env),
listener = _clientListeners[env.webview.id];
if (!listener) {
result.error("Battery listener has not started");
} else {
_webkitBattery.onchargingchange = null;
_webkitBattery.onlevelchange = null;
delete _clientListeners[env.webview.id];
result.noResult(false);
}
}
};

View File

@@ -0,0 +1,80 @@
/*
*
* 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 w3cBattery;
var winCallBack;
function success() {
winCallBack({ level: w3cBattery.level * 100, isPlugged: w3cBattery.charging });
}
var Battery = {
start: function(win, fail, args, env) {
try {
var subscribe = function(battery) {
w3cBattery = battery;
winCallBack = win;
success();
if (typeof w3cBattery.addEventListener === 'function') {
w3cBattery.addEventListener('levelchange', success, false);
w3cBattery.addEventListener('chargingchange', success, false);
} else {
w3cBattery.onlevelchange = success;
w3cBattery.onchargingchange = success;
}
};
if (typeof navigator.getBattery === 'function') {
navigator.getBattery().then(function(battery) {
subscribe(battery);
});
} else {
var origBattery = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.battery');
if (origBattery) {
subscribe(origBattery);
} else {
fail('Not supported');
}
}
} catch(e) {
fail(e);
}
},
stop: function() {
try {
if (typeof w3cBattery.removeEventListener === 'function') {
w3cBattery.removeEventListener('levelchange', success, false);
w3cBattery.removeEventListener('chargingchange', success, false);
} else {
w3cBattery.onlevelchange = null;
w3cBattery.onchargingchange = null;
}
} catch(e) {
console.warn('Error occured while trying to stop battery: ' + JSON.stringify(e));
}
}
};
require("cordova/exec/proxy").add("Battery", Battery);

View File

@@ -0,0 +1,61 @@
/*
*
* 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 mozBattery = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.battery') || navigator.mozBattery;
var Battery = {
start: function(successCB, failCB, args, env) {
if (mozBattery) {
Battery.attachListeners(successCB);
} else {
failCB('Could not get window.navigator.battery');
}
},
stop: function() {
Battery.detachListeners();
},
attachListeners: function(_callBack) {
Battery.updateBatteryStatus(_callBack); // send a battery status event
mozBattery.addEventListener("chargingchange", function(){
_callBack({level: (mozBattery.level * 100), isPlugged: mozBattery.charging});
});
mozBattery.addEventListener("levelchange", function(){
_callBack({level: (mozBattery.level * 100), isPlugged: mozBattery.charging});
});
},
detachListeners: function() {
mozBattery.removeEventListener("chargingchange", null);
mozBattery.removeEventListener("levelchange", null);
},
updateBatteryStatus: function(_callBack) {
_callBack({level: (mozBattery.level * 100), isPlugged: mozBattery.charging});
}
};
require("cordova/exec/proxy").add("Battery", Battery);

View File

@@ -0,0 +1,40 @@
/*
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.
*/
#import <Foundation/Foundation.h>
#import <Cordova/CDVPlugin.h>
@interface CDVBattery : CDVPlugin {
UIDeviceBatteryState state;
float level;
bool isPlugged;
NSString* callbackId;
}
@property (nonatomic) UIDeviceBatteryState state;
@property (nonatomic) float level;
@property (nonatomic) bool isPlugged;
@property (strong) NSString* callbackId;
- (void)updateBatteryStatus:(NSNotification*)notification;
- (NSDictionary*)getBatteryStatus;
- (void)start:(CDVInvokedUrlCommand*)command;
- (void)stop:(CDVInvokedUrlCommand*)command;
- (void)dealloc;
@end

View File

@@ -0,0 +1,148 @@
/*
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.
*/
#import "CDVBattery.h"
@interface CDVBattery (PrivateMethods)
- (void)updateOnlineStatus;
@end
@implementation CDVBattery
@synthesize state, level, callbackId, isPlugged;
/* determining type of event occurs on JavaScript side
- (void) updateBatteryLevel:(NSNotification*)notification
{
// send batterylow event for less than 25% battery
// send batterycritical event for less than 10% battery
// W3c says to send batteryStatus event when batterylevel changes by more than 1% (iOS seems to notify each 5%)
// always update the navigator.device.battery info
float currentLevel = [[UIDevice currentDevice] batteryLevel];
NSString* type = @"";
// no check for level == -1 since this api is only called when monitoring is enabled so level should be valid
if (currentLevel < 0.10){
type = @"batterycritical";
} else if (currentLevel < 0.25) {
type = @"batterylow";
} else {
float onePercent = 0.1;
if (self.level >= 0 ){
onePercent = self.level * 0.01;
}
if (fabsf(currentLevel - self.level) > onePercent){
// issue batteryStatus event
type = @"batterystatus";
}
}
// update the battery info and fire event
NSString* jsString = [NSString stringWithFormat:@"navigator.device.battery._status(\"%@\", %@)", type,[[self getBatteryStatus] JSONRepresentation]];
[super writeJavascript:jsString];
}
*/
- (void)updateBatteryStatus:(NSNotification*)notification
{
NSDictionary* batteryData = [self getBatteryStatus];
if (self.callbackId) {
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:batteryData];
[result setKeepCallbackAsBool:YES];
[self.commandDelegate sendPluginResult:result callbackId:self.callbackId];
}
}
/* Get the current battery status and level. Status will be unknown and level will be -1.0 if
* monitoring is turned off.
*/
- (NSDictionary*)getBatteryStatus
{
UIDevice* currentDevice = [UIDevice currentDevice];
UIDeviceBatteryState currentState = [currentDevice batteryState];
isPlugged = FALSE; // UIDeviceBatteryStateUnknown or UIDeviceBatteryStateUnplugged
if ((currentState == UIDeviceBatteryStateCharging) || (currentState == UIDeviceBatteryStateFull)) {
isPlugged = TRUE;
}
float currentLevel = [currentDevice batteryLevel];
if ((currentLevel != self.level) || (currentState != self.state)) {
self.level = currentLevel;
self.state = currentState;
}
// W3C spec says level must be null if it is unknown
NSObject* w3cLevel = nil;
if ((currentState == UIDeviceBatteryStateUnknown) || (currentLevel == -1.0)) {
w3cLevel = [NSNull null];
} else {
w3cLevel = [NSNumber numberWithFloat:(currentLevel * 100)];
}
NSMutableDictionary* batteryData = [NSMutableDictionary dictionaryWithCapacity:2];
[batteryData setObject:[NSNumber numberWithBool:isPlugged] forKey:@"isPlugged"];
[batteryData setObject:w3cLevel forKey:@"level"];
return batteryData;
}
/* turn on battery monitoring*/
- (void)start:(CDVInvokedUrlCommand*)command
{
self.callbackId = command.callbackId;
if ([UIDevice currentDevice].batteryMonitoringEnabled == NO) {
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBatteryStatus:)
name:UIDeviceBatteryStateDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBatteryStatus:)
name:UIDeviceBatteryLevelDidChangeNotification object:nil];
}
}
/* turn off battery monitoring */
- (void)stop:(CDVInvokedUrlCommand*)command
{
// callback one last time to clear the callback function on JS side
if (self.callbackId) {
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self getBatteryStatus]];
[result setKeepCallbackAsBool:NO];
[self.commandDelegate sendPluginResult:result callbackId:self.callbackId];
}
self.callbackId = nil;
[[UIDevice currentDevice] setBatteryMonitoringEnabled:NO];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceBatteryStateDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceBatteryLevelDidChangeNotification object:nil];
}
- (void)pluginInitialize
{
self.state = UIDeviceBatteryStateUnknown;
self.level = -1.0;
}
- (void)dealloc
{
[self stop:nil];
}
- (void)onReset
{
[self stop:nil];
}
@end

View File

@@ -0,0 +1,47 @@
/*
*
* 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.
*
*/
/* global tizen */
var batteryListenerId = null;
module.exports = {
start: function(successCallback, errorCallback) {
var batterySuccessCallback = function(power) {
if (successCallback) {
successCallback({level: Math.round(power.level * 100), isPlugged: power.isCharging});
}
};
if (batteryListenerId === null) {
batteryListenerId = tizen.systeminfo.addPropertyValueChangeListener("BATTERY", batterySuccessCallback);
}
tizen.systeminfo.getPropertyValue("BATTERY", batterySuccessCallback, errorCallback);
},
stop: function(successCallback, errorCallback) {
tizen.systeminfo.removePropertyValueChangeListener(batteryListenerId);
batteryListenerId = null;
}
};
require("cordova/tizen/commandProxy").add("Battery", module.exports);

View File

@@ -0,0 +1,78 @@
/*
* 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.
*
*/
#include <QtCore>
#include "battery.h"
BatteryStatus::BatteryStatus(Cordova *cordova) : CPlugin(cordova) {
_scId = 0;
connect(&_batteryInfo, SIGNAL(remainingCapacityChanged(int,int)), this, SLOT(remainingCapacityChanged(int,int)));
connect(&_batteryInfo, SIGNAL(chargerTypeChanged(QBatteryInfo::ChargerType)), this, SLOT(chargerTypeChanged(QBatteryInfo::ChargerType)));
}
void BatteryStatus::remainingCapacityChanged(int battery, int capacity) {
Q_UNUSED(battery);
Q_UNUSED(capacity);
fireEvents();
}
void BatteryStatus::chargerTypeChanged(QBatteryInfo::ChargerType type) {
Q_UNUSED(type);
fireEvents();
}
void BatteryStatus::fireEvents() {
int fullCount = 0;
bool isPlugged = false;
int remaining = 0, total = 0;
for (int i = 0; i < _batteryInfo.batteryCount(); i++) {
isPlugged = (_batteryInfo.chargingState(i) == QBatteryInfo::Charging) || isPlugged;
fullCount += _batteryInfo.chargingState(i) == QBatteryInfo::Full;
remaining += _batteryInfo.remainingCapacity(i);
total += _batteryInfo.maximumCapacity(i);
}
isPlugged = isPlugged || (_batteryInfo.batteryCount() == fullCount);
if (_scId) {
QVariantMap obj;
obj.insert("isPlugged", (int)isPlugged);
if (total != 0)
obj.insert("level", remaining * 100 / total);
else
obj.insert("level", 100);
this->callbackWithoutRemove(_scId, CordovaInternal::format(obj));
}
}
void BatteryStatus::start(int scId, int) {
_scId = scId;
}
void BatteryStatus::stop(int, int) {
_scId = 0;
}

View File

@@ -0,0 +1,62 @@
/*
* 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.
*
*/
#ifndef BATTERY_H_AAAAAAAA
#define BATTERY_H_AAAAAAAA
#include <QBatteryInfo>
#include <cplugin.h>
class BatteryStatus: public CPlugin {
Q_OBJECT
public:
explicit BatteryStatus(Cordova *cordova);
virtual const QString fullName() override {
return BatteryStatus::fullID();
}
virtual const QString shortName() override {
return "Battery";
}
static const QString fullID() {
return "Battery";
}
public slots:
void start(int scId, int ecId);
void stop(int scId, int ecId);
private slots:
void remainingCapacityChanged(int battery, int capacity);
void chargerTypeChanged(QBatteryInfo::ChargerType type);
void onlineStatusChanged(bool isOnline);
private:
void fireEvents();
QBatteryInfo _batteryInfo;
int _scId;
};
#endif

View File

@@ -0,0 +1,125 @@
/*
*
* 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.
*
*/
/* global Windows, WinJS, BatteryStatus */
var PowerManager = Windows && Windows.System &&
Windows.System.Power && Windows.System.Power.PowerManager;
if (PowerManager) {
var pluginCallback;
var reportStatus = function () {
if (!pluginCallback) {
return;
}
pluginCallback({
level: PowerManager.remainingChargePercent,
isPlugged: PowerManager.powerSupplyStatus !== Windows.System.Power.PowerSupplyStatus.notPresent
}, { keepCallback: true });
};
var BatteryWin10 = {
start: function (win, fail) {
pluginCallback = win;
PowerManager.addEventListener('remainingchargepercentchanged', reportStatus);
PowerManager.addEventListener('powersupplystatuschanged', reportStatus);
reportStatus();
},
stop: function () {
if (pluginCallback) {
PowerManager.removeEventListener('remainingchargepercentchanged', reportStatus);
PowerManager.removeEventListener('powersupplystatuschanged', reportStatus);
}
pluginCallback = null;
}
};
require("cordova/exec/proxy").add("Battery", BatteryWin10);
} else {
var stopped;
var handleResponse = function(successCb, errorCb, jsonResponse) {
var info = JSON.parse(jsonResponse);
if (info.hasOwnProperty("exceptionMessage")) {
errorCb(info.exceptionMessage);
return;
}
successCb(info, { keepCallback: true });
};
var Battery = {
start: function (win, fail, args, env) {
function getBatteryStatus(success, error) {
handleResponse(success, error, BatteryStatus.BatteryStatus.start());
}
function getBatteryStatusLevelChangeEvent(success, error) {
return BatteryStatus.BatteryStatus.getBatteryStatusChangeEvent().done(function (result) {
if (stopped) {
return;
}
handleResponse(success, error, result);
setTimeout(function() { getBatteryStatusLevelChangeEvent(success, error); }, 0);
}, function(err) {
fail(err);
});
}
// Battery API supported on Phone devices only so in case of
// desktop/tablet the only one choice is to fail with appropriate message.
if (!WinJS.Utilities.isPhone) {
fail("The operation is not supported on Windows Desktop devices.");
return;
}
stopped = false;
try {
getBatteryStatus(win, fail);
getBatteryStatusLevelChangeEvent(win, fail);
} catch(e) {
fail(e);
}
},
stop: function () {
// Battery API supported on Phone devices only so in case of
// desktop/tablet device we don't need for any actions.
if (!WinJS.Utilities.isPhone) {
return;
}
stopped = true;
BatteryStatus.BatteryStatus.stop();
}
};
require("cordova/exec/proxy").add("Battery", Battery);
}

View File

@@ -0,0 +1,40 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30723.0
MinimumVisualStudioVersion = 10.0.40219.1
#
# 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.
#
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryStatus", "BatteryStatus\BatteryStatus.csproj", "{9749E0FB-CDCF-4D80-8953-AAB577B44234}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9749E0FB-CDCF-4D80-8953-AAB577B44234}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9749E0FB-CDCF-4D80-8953-AAB577B44234}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9749E0FB-CDCF-4D80-8953-AAB577B44234}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9749E0FB-CDCF-4D80-8953-AAB577B44234}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,3 @@
/bin/
/obj/
*.suo

View File

@@ -0,0 +1,104 @@
/*
Licensed 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.
*/
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Phone.Devices.Power;
namespace BatteryStatus
{
public sealed class BatteryStatus
{
private static Battery battery = Battery.GetDefault();
private static TaskCompletionSource<string> levelCompletionSource = new TaskCompletionSource<string>();
public static string start()
{
battery.RemainingChargePercentChanged += BatteryOnRemainingChargePercentChanged;
return getBatteryStatus();
}
public static void stop()
{
battery.RemainingChargePercentChanged -= BatteryOnRemainingChargePercentChanged;
}
public static string getBatteryStatus()
{
try
{
return Serialize(typeof(BatteryInfo), new BatteryInfo
{
Level = battery.RemainingChargePercent
});
}
catch (Exception ex)
{
return Serialize(typeof(ExceptionInfo), new ExceptionInfo { Message = ex.Message });
}
}
public static IAsyncOperation<string> getBatteryStatusChangeEvent()
{
return GetBatteryStatusChangeEvent().AsAsyncOperation();
}
private static async Task<string> GetBatteryStatusChangeEvent()
{
levelCompletionSource = new TaskCompletionSource<string>();
return await levelCompletionSource.Task;
}
private static void BatteryOnRemainingChargePercentChanged(object sender, object o)
{
levelCompletionSource.SetResult(getBatteryStatus());
}
private static string Serialize(Type type, object obj)
{
using (var stream = new MemoryStream())
{
var jsonSer = new DataContractJsonSerializer(type);
jsonSer.WriteObject(stream, obj);
stream.Position = 0;
return new StreamReader(stream).ReadToEnd();
}
}
[DataContract]
private class BatteryInfo
{
[DataMember(Name = "level")]
public int Level;
// Not supported by native API
[DataMember(Name = "isPlugged")]
public string IsPlugged;
};
[DataContract]
private class ExceptionInfo
{
[DataMember(Name = "exceptionMessage")]
public string Message = string.Empty;
};
}
}

View File

@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
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.
-->
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9749E0FB-CDCF-4D80-8953-AAB577B44234}</ProjectGuid>
<OutputType>winmdobj</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BatteryStatus</RootNamespace>
<AssemblyName>BatteryStatus</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{76F1466A-8B6D-4E39-A767-685A06062A39};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetPlatformIdentifier>WindowsPhoneApp</TargetPlatformIdentifier>
<TargetPlatformVersion>8.1</TargetPlatformVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_PHONE_APP</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_PHONE_APP</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<!-- A reference to the entire .NET Framework is automatically included -->
</ItemGroup>
<ItemGroup>
<Compile Include="BatteryStatus.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>xcopy /Y /Q "$(TargetPath)" "$(SolutionDir).."</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,44 @@
/*
Licensed 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.
*/
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BatteryStatus")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BatteryStatus")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,104 @@
/*
Licensed 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.
*/
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Info;
namespace WPCordovaClassLib.Cordova.Commands
{
/// <summary>
/// Listens for changes to the state of the battery on the device.
/// </summary>
public class Battery : BaseCommand
{
private bool isPlugged = false;
private EventHandler powerChanged;
#if WP8
private Windows.Phone.Devices.Power.Battery battery;
#endif
public Battery()
{
powerChanged = new EventHandler(DeviceStatus_PowerSourceChanged);
isPlugged = DeviceStatus.PowerSource.ToString().CompareTo("External") == 0;
#if WP8
battery = Windows.Phone.Devices.Power.Battery.GetDefault();
#endif
}
public void start(string options)
{
// Register power changed event handler
DeviceStatus.PowerSourceChanged += powerChanged;
#if WP8
battery.RemainingChargePercentChanged += Battery_RemainingChargePercentChanged;
#endif
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.KeepCallback = true;
DispatchCommandResult(result);
}
public void stop(string options)
{
// Unregister power changed event handler
DeviceStatus.PowerSourceChanged -= powerChanged;
#if WP8
battery.RemainingChargePercentChanged -= Battery_RemainingChargePercentChanged;
#endif
}
private void DeviceStatus_PowerSourceChanged(object sender, EventArgs e)
{
isPlugged = DeviceStatus.PowerSource.ToString().CompareTo("External") == 0;
PluginResult result = new PluginResult(PluginResult.Status.OK, GetCurrentBatteryStateFormatted());
result.KeepCallback = true;
DispatchCommandResult(result);
}
private void Battery_RemainingChargePercentChanged(object sender, object e)
{
PluginResult result = new PluginResult(PluginResult.Status.OK, GetCurrentBatteryStateFormatted());
result.KeepCallback = true;
DispatchCommandResult(result);
}
private string GetCurrentBatteryStateFormatted()
{
int remainingChargePercent = -1;
#if WP8
remainingChargePercent = battery.RemainingChargePercent;
#endif
string batteryState = String.Format("\"level\":{0},\"isPlugged\":{1}",
remainingChargePercent,
isPlugged ? "true" : "false"
);
batteryState = "{" + batteryState + "}";
return batteryState;
}
}
}

View File

@@ -0,0 +1,14 @@
{
"name": "cordova-plugin-battery-status-tests",
"version": "1.2.4-dev",
"description": "",
"cordova": {
"id": "cordova-plugin-battery-status-tests",
"platforms": []
},
"keywords": [
"ecosystem:cordova"
],
"author": "",
"license": "Apache 2.0"
}

View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:rim="http://www.blackberry.com/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android"
id="cordova-plugin-battery-status-tests"
version="1.2.4">
<name>Cordova Battery Plugin Tests</name>
<license>Apache 2.0</license>
<js-module src="tests.js" name="tests">
</js-module>
</plugin>

View File

@@ -0,0 +1,559 @@
/*
*
* 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.
*
*/
/* jshint jasmine: true */
/* global Windows, WinJS */
exports.defineAutoTests = function () {
var hasPowerManagerAPI = cordova.platformId === "windows" &&
Windows && Windows.System && Windows.System.Power &&
Windows.System.Power.PowerManager;
var batteryStatusUnsupported = cordova.platformId === "windows8" ||
// We don't test battery status on Windows when there is no corresponding APIs available
cordova.platformId === "windows" && !(hasPowerManagerAPI || WinJS.Utilities.isPhone);
var onEvent;
describe('Battery (navigator.battery)', function () {
it("battery.spec.1 should exist", function () {
if (batteryStatusUnsupported) {
pending('Battery status is not supported on windows store');
}
expect(navigator.battery).toBeDefined();
});
});
describe('Battery Events', function () {
describe("batterystatus", function () {
afterEach(function () {
if (!batteryStatusUnsupported) {
try {
window.removeEventListener("batterystatus", onEvent, false);
}
catch (e) {
console.error('Error removing batterystatus event listener: ' + e);
}
}
});
it("battery.spec.2 should fire batterystatus events", function (done) {
if (batteryStatusUnsupported) {
pending('Battery status is not supported on windows store');
}
onEvent = jasmine.createSpy("BatteryStatus");
// batterystatus -> 30
window.addEventListener("batterystatus", onEvent, false);
navigator.battery._status({
level: 30,
isPlugged: false
});
setTimeout(function () {
expect(onEvent).toHaveBeenCalled();
done();
}, 100);
});
});
describe("batterylow", function () {
afterEach(function () {
if (!batteryStatusUnsupported) {
try {
window.removeEventListener("batterylow", onEvent, false);
}
catch (e) {
console.error('Error removing batterylow event listener: ' + e);
}
}
});
it("battery.spec.3 should fire batterylow event (30 -> 20)", function (done) {
if (batteryStatusUnsupported) {
pending('Battery status is not supported on windows store');
}
onEvent = jasmine.createSpy("BatteryLow");
// batterylow 30 -> 20
window.addEventListener("batterylow", onEvent, false);
navigator.battery._status({
level : 30,
isPlugged : false
});
navigator.battery._status({
level : 20,
isPlugged : false
});
setTimeout(function () {
expect(onEvent).toHaveBeenCalled();
done();
}, 100);
});
it("battery.spec.3.1 should fire batterylow event (30 -> 19)", function (done) {
if (batteryStatusUnsupported) {
pending('Battery status is not supported on windows store');
}
onEvent = jasmine.createSpy("BatteryLow");
// batterylow 30 -> 19
window.addEventListener("batterylow", onEvent, false);
navigator.battery._status({
level : 30,
isPlugged : false
});
navigator.battery._status({
level : 19,
isPlugged : false
});
setTimeout(function () {
expect(onEvent).toHaveBeenCalled();
done();
}, 100);
});
it("battery.spec.3.2 should not fire batterylow event (5 -> 20)", function (done) {
if (batteryStatusUnsupported) {
pending('Battery status is not supported on windows store');
}
onEvent = jasmine.createSpy("BatteryLow");
// batterylow should not fire when level increases (5->20) ( CB-4519 )
window.addEventListener("batterylow", onEvent, false);
navigator.battery._status({
level : 5,
isPlugged : false
});
navigator.battery._status({
level: 20,
isPlugged: false
});
setTimeout(function () {
expect(onEvent).not.toHaveBeenCalled();
done();
}, 100);
});
it("battery.spec.3.3 batterylow event(21 -> 20) should not fire if charging", function (done) {
if (batteryStatusUnsupported) {
pending('Battery status is not supported on windows store');
}
onEvent = jasmine.createSpy("BatteryLow");
// batterylow should NOT fire if we are charging ( CB-4520 )
window.addEventListener("batterylow", onEvent, false);
navigator.battery._status({
level : 21,
isPlugged : true
});
navigator.battery._status({
level : 20,
isPlugged : true
});
setTimeout(function () {
expect(onEvent).not.toHaveBeenCalled();
done();
}, 100);
});
});
describe("batterycritical", function () {
afterEach(function () {
if (!batteryStatusUnsupported) {
try {
window.removeEventListener("batterycritical", onEvent, false);
}
catch (e) {
console.error('Error removing batterycritical event listener: ' + e);
}
}
});
it("battery.spec.4 should fire batterycritical event (19 -> 5)", function (done) {
if (batteryStatusUnsupported) {
pending('Battery status is not supported on windows store');
}
onEvent = jasmine.createSpy("BatteryCritical");
// batterycritical 19->5
window.addEventListener("batterycritical", onEvent, false);
navigator.battery._status({
level: 19,
isPlugged: false
});
navigator.battery._status({
level: 5,
isPlugged: false
});
setTimeout(function () {
expect(onEvent).toHaveBeenCalled();
done();
}, 100);
});
it("battery.spec.4.1 should fire batterycritical event (19 -> 4)", function (done) {
if (batteryStatusUnsupported) {
pending('Battery status is not supported on windows store');
}
onEvent = jasmine.createSpy("BatteryCritical");
// batterycritical 19->4
window.addEventListener("batterycritical", onEvent, false);
navigator.battery._status({
level: 19,
isPlugged: false
});
navigator.battery._status({
level: 4,
isPlugged: false
});
setTimeout(function () {
expect(onEvent).toHaveBeenCalled();
done();
}, 100);
});
it("battery.spec.4.2 should fire batterycritical event (100 -> 4) when decreases", function (done) {
if (batteryStatusUnsupported) {
pending('Battery status is not supported on windows store');
}
onEvent = jasmine.createSpy("BatteryCritical");
// setup: batterycritical should fire when level decreases (100->4) ( CB-4519 )
window.addEventListener("batterycritical", onEvent, false);
navigator.battery._status({
level: 100,
isPlugged: false
});
navigator.battery._status({
level: 4,
isPlugged: false
});
setTimeout(function () {
expect(onEvent).toHaveBeenCalled();
done();
}, 100);
});
it("battery.spec.4.3 should not fire batterycritical event (4 -> 5) when increasing", function (done) {
if (batteryStatusUnsupported) {
pending('Battery status is not supported on windows store');
}
onEvent = jasmine.createSpy("BatteryCritical");
window.addEventListener("batterycritical", onEvent, false);
// batterycritical should not fire when level increases (4->5)( CB-4519 )
navigator.battery._status({
level: 4,
isPlugged: false
});
navigator.battery._status({
level: 5,
isPlugged: false
});
setTimeout(function () {
expect(onEvent.calls.count()).toBeLessThan(2);
done();
}, 100);
});
it("battery.spec.4.4 should not fire batterycritical event (6 -> 5) if charging", function (done) {
if (batteryStatusUnsupported) {
pending('Battery status is not supported on windows store');
}
onEvent = jasmine.createSpy("BatteryCritical");
window.addEventListener("batterycritical", onEvent, false);
// batterycritical should NOT fire if we are charging ( CB-4520 )
navigator.battery._status({
level: 6,
isPlugged: true
});
navigator.battery._status({
level: 5,
isPlugged: true
});
setTimeout(function () {
expect(onEvent).not.toHaveBeenCalled();
done();
}, 100);
});
});
});
};
//******************************************************************************************
//***************************************Manual Tests***************************************
//******************************************************************************************
exports.defineManualTests = function (contentEl, createActionButton) {
/* Battery */
function updateInfo(info) {
document.getElementById('levelValue').innerText = info.level;
document.getElementById('pluggedValue').innerText = info.isPlugged;
if (info.level > 5) {
document.getElementById('criticalValue').innerText = "false";
}
if (info.level > 20) {
document.getElementById('lowValue').innerText = "false";
}
}
function batteryLow(info) {
document.getElementById('lowValue').innerText = "true";
}
function batteryCritical(info) {
document.getElementById('criticalValue').innerText = "true";
}
function addBattery() {
window.addEventListener("batterystatus", updateInfo, false);
}
function removeBattery() {
window.removeEventListener("batterystatus", updateInfo, false);
}
function addLow() {
window.addEventListener("batterylow", batteryLow, false);
}
function removeLow() {
window.removeEventListener("batterylow", batteryLow, false);
}
function addCritical() {
window.addEventListener("batterycritical", batteryCritical, false);
}
function removeCritical() {
window.removeEventListener("batterycritical", batteryCritical, false);
}
//Generate Dynamic Table
function generateTable(tableId, rows, cells, elements) {
var table = document.createElement('table');
for (var r = 0; r < rows; r++) {
var row = table.insertRow(r);
for (var c = 0; c < cells; c++) {
var cell = row.insertCell(c);
cell.setAttribute("align", "center");
for (var e in elements) {
if (elements[e].position.row == r && elements[e].position.cell == c) {
var htmlElement = document.createElement(elements[e].tag);
var content;
if (elements[e].content !== "") {
content = document.createTextNode(elements[e].content);
htmlElement.appendChild(content);
}
if (elements[e].type) {
htmlElement.type = elements[e].type;
}
htmlElement.setAttribute("id", elements[e].id);
cell.appendChild(htmlElement);
}
}
}
}
table.setAttribute("align", "center");
table.setAttribute("id", tableId);
return table;
}
// Battery Elements
var batteryElements =
[{
id : "statusTag",
content : "Status:",
tag : "div",
position : {
row : 0,
cell : 0
}
}, {
id : "statusValue",
content : "",
tag : "div",
position : {
row : 0,
cell : 1
}
}, {
id : "levelTag",
content : "Level:",
tag : "div",
position : {
row : 1,
cell : 0
}
}, {
id : "levelValue",
content : "",
tag : "div",
position : {
row : 1,
cell : 1
}
}, {
id : "pluggedTag",
content : "Plugged:",
tag : "div",
position : {
row : 2,
cell : 0
}
}, {
id : "pluggedValue",
content : "",
tag : "div",
position : {
row : 2,
cell : 1
}
}, {
id : "lowTag",
content : "Low:",
tag : "div",
position : {
row : 3,
cell : 0
}
}, {
id : "lowValue",
content : "",
tag : "div",
position : {
row : 3,
cell : 1
}
}, {
id : "criticalTag",
content : "Critical:",
tag : "div",
position : {
row : 4,
cell : 0
}
}, {
id : "criticalValue",
content : "",
tag : "div",
position : {
row : 4,
cell : 1
}
}
];
//Title audio results
var div = document.createElement('h2');
div.appendChild(document.createTextNode('Battery Status'));
div.setAttribute("align", "center");
contentEl.appendChild(div);
var batteryTable = generateTable('info', 5, 3, batteryElements);
contentEl.appendChild(batteryTable);
div = document.createElement('h2');
div.appendChild(document.createTextNode('Actions'));
div.setAttribute("align", "center");
contentEl.appendChild(div);
contentEl.innerHTML += '<h3>Battery Status Tests</h3>' +
'Will update values for level and plugged when they change. If battery low and critical values are false, they will get updated in status box, but only once' +
'<div id="addBS"></div><div id="remBs"></div>' +
'<h3>Battery Low Tests</h3>' +
'</p> Will update value for battery low to true when battery is below 20%' +
'<div id="addBl"></div><div id="remBl"></div>' +
'<h3>Battery Critical Tests</h3>' +
'</p> Will update value for battery critical to true when battery is below 5%' +
'<div id="addBc"></div><div id="remBc"></div>';
createActionButton('Add "batterystatus" listener', function () {
addBattery();
}, 'addBS');
createActionButton('Remove "batterystatus" listener', function () {
removeBattery();
}, 'remBs');
createActionButton('Add "batterylow" listener', function () {
addLow();
}, 'addBl');
createActionButton('Remove "batterylow" listener', function () {
removeLow();
}, 'remBl');
createActionButton('Add "batterycritical" listener', function () {
addCritical();
}, 'addBc');
createActionButton('Remove "batterycritical" listener', function () {
removeCritical();
}, 'remBc');
};

View File

@@ -0,0 +1,125 @@
// Type definitions for Apache Cordova BatteryStatus plugin
// Project: https://github.com/apache/cordova-plugin-battery-status
// Definitions by: Microsoft Open Technologies Inc <http://msopentech.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
//
// Copyright (c) Microsoft Open Technologies Inc
// Licensed under the MIT license.
interface Window {
onbatterystatus: (type: BatteryStatusEvent) => void;
onbatterycritical: (type: BatteryStatusEvent) => void;
onbatterylow: (type: BatteryStatusEvent) => void;
/**
* Adds a listener for an event from the BatteryStatus plugin.
* @param type the event to listen for
* batterystatus: event fires when the percentage of battery charge
* changes by at least 1 percent, or if the device is plugged in or unplugged.
* batterycritical: event fires when the percentage of battery charge has reached
* the critical battery threshold. The value is device-specific.
* batterylow: event fires when the percentage of battery charge has
* reached the low battery threshold, device-specific value.
* @param listener the function that executes when the event fires. The function is
* passed an BatteryStatusEvent object as a parameter.
*/
addEventListener(type: "batterystatus", listener: (ev: BatteryStatusEvent) => any, useCapture?: boolean): void;
/**
* Adds a listener for an event from the BatteryStatus plugin.
* @param type the event to listen for
* batterystatus: event fires when the percentage of battery charge
* changes by at least 1 percent, or if the device is plugged in or unplugged.
* batterycritical: event fires when the percentage of battery charge has reached
* the critical battery threshold. The value is device-specific.
* batterylow: event fires when the percentage of battery charge has
* reached the low battery threshold, device-specific value.
* @param listener the function that executes when the event fires. The function is
* passed an BatteryStatusEvent object as a parameter.
*/
addEventListener(type: "batterycritical", listener: (ev: BatteryStatusEvent) => any, useCapture?: boolean): void;
/**
* Adds a listener for an event from the BatteryStatus plugin.
* @param type the event to listen for
* batterystatus: event fires when the percentage of battery charge
* changes by at least 1 percent, or if the device is plugged in or unplugged.
* batterycritical: event fires when the percentage of battery charge has reached
* the critical battery threshold. The value is device-specific.
* batterylow: event fires when the percentage of battery charge has
* reached the low battery threshold, device-specific value.
* @param listener the function that executes when the event fires. The function is
* passed an BatteryStatusEvent object as a parameter.
*/
addEventListener(type: "batterylow", listener: (ev: BatteryStatusEvent) => any, useCapture?: boolean): void;
/**
* Adds a listener for an event from the BatteryStatus plugin.
* @param type the event to listen for
* batterystatus: event fires when the percentage of battery charge
* changes by at least 1 percent, or if the device is plugged in or unplugged.
* batterycritical: event fires when the percentage of battery charge has reached
* the critical battery threshold. The value is device-specific.
* batterylow: event fires when the percentage of battery charge has
* reached the low battery threshold, device-specific value.
* @param listener the function that executes when the event fires. The function is
* passed an BatteryStatusEvent object as a parameter.
*/
addEventListener(type: string, listener: (ev: Event) => any, useCapture?: boolean): void;
/**
* Removes a listener for an event from the BatteryStatus plugin.
* @param type The event to stop listening for.
* batterystatus: event fires when the percentage of battery charge
* changes by at least 1 percent, or if the device is plugged in or unplugged.
* batterycritical: event fires when the percentage of battery charge has reached
* the critical battery threshold. The value is device-specific.
* batterylow: event fires when the percentage of battery charge has
* reached the low battery threshold, device-specific value.
* @param callback the function that executes when the event fires. The function is
* passed an BatteryStatusEvent object as a parameter.
*/
removeEventListener(type: "batterystatus", listener: (ev: BatteryStatusEvent) => any, useCapture?: boolean): void;
/**
* Removes a listener for an event from the BatteryStatus plugin.
* @param type The event to stop listening for.
* batterystatus: event fires when the percentage of battery charge
* changes by at least 1 percent, or if the device is plugged in or unplugged.
* batterycritical: event fires when the percentage of battery charge has reached
* the critical battery threshold. The value is device-specific.
* batterylow: event fires when the percentage of battery charge has
* reached the low battery threshold, device-specific value.
* @param callback the function that executes when the event fires. The function is
* passed an BatteryStatusEvent object as a parameter.
*/
removeEventListener(type: "batterycritical", listener: (ev: BatteryStatusEvent) => any, useCapture?: boolean): void;
/**
* Removes a listener for an event from the BatteryStatus plugin.
* @param type The event to stop listening for.
* batterystatus: event fires when the percentage of battery charge
* changes by at least 1 percent, or if the device is plugged in or unplugged.
* batterycritical: event fires when the percentage of battery charge has reached
* the critical battery threshold. The value is device-specific.
* batterylow: event fires when the percentage of battery charge has
* reached the low battery threshold, device-specific value.
* @param callback the function that executes when the event fires. The function is
* passed an BatteryStatusEvent object as a parameter.
*/
removeEventListener(type: "batterylow", listener: (ev: BatteryStatusEvent) => any, useCapture?: boolean): void;
/**
* Removes a listener for an event from the BatteryStatus plugin.
* @param type The event to stop listening for.
* batterystatus: event fires when the percentage of battery charge
* changes by at least 1 percent, or if the device is plugged in or unplugged.
* batterycritical: event fires when the percentage of battery charge has reached
* the critical battery threshold. The value is device-specific.
* batterylow: event fires when the percentage of battery charge has
* reached the low battery threshold, device-specific value.
* @param callback the function that executes when the event fires. The function is
* passed an BatteryStatusEvent object as a parameter.
*/
removeEventListener(type: string, listener: (ev: Event) => any, useCapture?: boolean): void;
}
/** Object, that passed into battery event listener */
interface BatteryStatusEvent extends Event {
/* The percentage of battery charge (0-100). */
level: number;
/* A boolean that indicates whether the device is plugged in. */
isPlugged: boolean;
}

View File

@@ -0,0 +1,110 @@
/*
*
* 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');
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;
}
};
function handlers() {
return battery.channels.batterystatus.numHandlers +
battery.channels.batterylow.numHandlers +
battery.channels.batterycritical.numHandlers;
}
/**
* 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(); // jshint ignore:line
module.exports = battery;

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Martin Reinhardt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,56 @@
# Certificate Plugin for Apache Cordova
[![Build Status](https://travis-ci.org/hypery2k/cordova-certificate-plugin.svg?branch=master)](https://travis-ci.org/hypery2k/cordova-certificate-plugin) [![npm version](https://badge.fury.io/js/cordova-plugin-certificates.svg)](http://badge.fury.io/js/cordova-plugin-certificates)[![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=2596540)](https://www.bountysource.com/trackers/2596540-hypery2k-cordova-certificate-plugin?utm_source=2596540&utm_medium=shield&utm_campaign=TRACKER_BADGE)
> cordova Plugin to configure SSL Certificates, currently used to enable usage of untrusted aka self-signed SSL certifcates
[![NPM](https://nodei.co/npm/cordova-plugin-certificates.png)](https://nodei.co/npm/cordova-plugin-certificates/)
Feel free to **donate**
<a href='http://www.pledgie.com/campaigns/25442'><img alt='Click here to lend your support to: Owncloud Apps and make a donation at www.pledgie.com !' src='http://www.pledgie.com/campaigns/23447.png?skin_name=chrome' border='0' /></a>
<a target="_blank" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=AGPGLZYNV6Y5S">
<img alt="" border="0" src="https://www.paypalobjects.com/de_DE/DE/i/btn/btn_donateCC_LG.gif"/>
</img></a>
## Documentation
### Install
```
cordova plugin add cordova-plugin-certificates
```
> For Cordova-Android before 4.1.0 you need to install this version
```
cordova plugin add cordova-plugin-certificates@0.5.0
```
### Usage
Activate insecure certificates
```
cordova.plugins.certificates.trustUnsecureCerts(true)
```
Dectivate insecure certificates
```
cordova.plugins.certificates.trustUnsecureCerts(false)
```
## Development
### Running integration tests
execute the `runIntegrationTests.sh` script for a specific platform:
```
PLATFORM='android' ./runIntegrationTests.sh
```
```
PLATFORM='ios' ./runIntegrationTests.sh
```

View File

@@ -0,0 +1,95 @@
{
"_args": [
[
{
"raw": "cordova-plugin-certificates",
"scope": null,
"escapedName": "cordova-plugin-certificates",
"name": "cordova-plugin-certificates",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"D:\\pWork\\yunkong2.vis.cordova\\node_modules"
]
],
"_from": "cordova-plugin-certificates@latest",
"_id": "cordova-plugin-certificates@0.6.4",
"_inCache": true,
"_location": "/cordova-plugin-certificates",
"_nodeVersion": "6.11.1",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/cordova-plugin-certificates-0.6.4.tgz_1501142806424_0.2454286552965641"
},
"_npmUser": {
"name": "hypery2k",
"email": "contact@martinreinhardt-online.de"
},
"_npmVersion": "3.10.10",
"_phantomChildren": {},
"_requested": {
"raw": "cordova-plugin-certificates",
"scope": null,
"escapedName": "cordova-plugin-certificates",
"name": "cordova-plugin-certificates",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/cordova-plugin-certificates/-/cordova-plugin-certificates-0.6.4.tgz",
"_shasum": "8051339be00c691c824338d8fa086ff5f6be2bb9",
"_shrinkwrap": null,
"_spec": "cordova-plugin-certificates",
"_where": "D:\\pWork\\yunkong2.vis.cordova\\node_modules",
"author": {
"name": "Martin Reinhardt"
},
"bugs": {
"url": "https://github.com/hypery2k/cordova-certificate-plugin/issues"
},
"cordova": {
"id": "cordova-plugin-certificates",
"platforms": [
"android",
"ios"
]
},
"dependencies": {},
"description": "Cordova Certificate Plugin",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "8051339be00c691c824338d8fa086ff5f6be2bb9",
"tarball": "https://registry.npmjs.org/cordova-plugin-certificates/-/cordova-plugin-certificates-0.6.4.tgz"
},
"gitHead": "762175849f553a4a98a47f6ab55438df8223647e",
"homepage": "https://github.com/hypery2k/cordova-certificate-plugin#readme",
"keywords": [
"cordova",
"certificates",
"ecosystem:cordova",
"cordova-android",
"cordova-ios"
],
"license": "MIT",
"maintainers": [
{
"name": "hypery2k",
"email": "npm@martinreinhardt-online.de"
}
],
"name": "cordova-plugin-certificates",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/hypery2k/cordova-certificate-plugin.git"
},
"scripts": {},
"version": "0.6.4"
}

View File

@@ -0,0 +1,76 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The MIT License (MIT)
Copyright (c) 2015 Martin Reinhardt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
id="cordova-plugin-certificates"
version="0.6.4">
<name>Certificate Plugin</name>
<description>
Cordova Certificate Plugin
</description>
<author>Martin Reinhardt</author>
<license>MIT</license>
<keywords>cordova,certificates,ssl</keywords>
<repo>https://github.com/hypery2k/cordova-certificate-plugin.git</repo>
<issue>https://github.com/hypery2k/cordova-certificate-plugin/issues</issue>
<engines>
<engine name="cordova-android" version=">=4.1.0" />
<engine name="cordova-ios" version=">=3.4.0" />
</engines>
<js-module src="www/certificate.js" name="Certificates">
<clobbers target="cordova.plugins.certificates" />
</js-module>
<!-- ios -->
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="CDVCertificate">
<param name="ios-package" value="CDVCertificate"/>
</feature>
</config-file>
<header-file src="src/ios/CDVCertificate.h" />
<source-file src="src/ios/CDVCertificate.m" />
<header-file src="src/ios/NSURLRequest+AllowUntrustedCertificates.h" />
<source-file src="src/ios/NSURLRequest+AllowUntrustedCertificates.m" />
</platform>
<!-- android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="CertificatesPlugin" >
<param name="android-package" value="de.martinreinhardt.cordova.plugins.CertificatesPlugin"/>
</feature>
</config-file>
<source-file src="src/android/de/martinreinhardt/cordova/plugins/CertificatesCordovaWebViewClient.java" target-dir="src/de/martinreinhardt/cordova/plugins/" />
<source-file src="src/android/de/martinreinhardt/cordova/plugins/CertificatesPlugin.java" target-dir="src/de/martinreinhardt/cordova/plugins/" />
</platform>
</plugin>

View File

@@ -0,0 +1,16 @@
#!/bin/sh
cwd=$(pwd)
cd ..
rm -rf cordova-test-app
git clone https://github.com/hypery2k/cordova-demo-app.git cordova-test-app
cd cordova-test-app
npm install
bower install
echo "Building vanilla cordova app"
grunt "ci:$PLATFORM" "$PLATFORM"
echo "Adding plugin"
cordova plugin add ../cordova-certificate-plugin/
echo "Building vanilla cordova app with added plugin"
grunt "$PLATFORM"
echo "Changing back to plugin directy: "$cwd
cd $cwd

View File

@@ -0,0 +1,96 @@
/*
The MIT License (MIT)
Copyright (c) 2015 Martin Reinhardt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Certificate Plugin for Cordova
*/
package de.martinreinhardt.cordova.plugins;
import org.apache.cordova.engine.SystemWebViewEngine;
import org.apache.cordova.engine.SystemWebViewClient;
import android.net.http.SslError;
import android.util.Log;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
/**
*
* Certificates Cordova WebView Client
*
* author, Martin Reinhardt on 23.06.14.
*
* Copyright Martin Reinhardt 2014. All rights reserved.
*
*/
public class CertificatesCordovaWebViewClient extends SystemWebViewClient {
/**
* Logging Tag
*/
public static final String TAG = "CertificatesCordovaWebViewClient";
private boolean allowUntrusted = false;
/**
*
* @param cordova
*/
public CertificatesCordovaWebViewClient(SystemWebViewEngine parentEngine) {
super(parentEngine);
}
/**
* @return true of usage of untrusted (self-signed) certificates is allowed,
* otherwise false
*/
public boolean isAllowUntrusted() {
return allowUntrusted;
}
/**
*
*
* @param pAllowUntrusted
* the allowUntrusted to set
*/
public void setAllowUntrusted(final boolean pAllowUntrusted) {
this.allowUntrusted = pAllowUntrusted;
}
/**
* @see org.apache.cordova.SystemWebViewClient#onReceivedSslError(WebView,
* SslErrorHandler, SslError)
*/
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
Log.d(TAG, "onReceivedSslError. Proceed? " + isAllowUntrusted());
if (isAllowUntrusted()) {
handler.proceed();
} else {
super.onReceivedSslError(view, handler, error);
}
}
}

View File

@@ -0,0 +1,118 @@
/*
The MIT License (MIT)
Copyright (c) 2014 Martin Reinhardt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Certificate Plugin for Cordova
*/
package de.martinreinhardt.cordova.plugins;
import org.apache.cordova.engine.SystemWebViewEngine;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
/**
*
* Certificate Plugin for Cordova
*
* author, Martin Reinhardt on 23.06.14.
*
* Copyright Martin Reinhardt 2014. All rights reserved.
*
*/
public class CertificatesPlugin extends CordovaPlugin {
/**
* Logging Tag
*/
private static final String LOG_TAG = "Certificates";
/**
* Untrusted Variable
*/
private boolean allowUntrusted = false;
/**
* Executes the request.
*
* This method is called from the WebView thread. To do a non-trivial amount
* of work, use: cordova.getThreadPool().execute(runnable);
*
* To run on the UI thread, use:
* cordova.getActivity().runOnUiThread(runnable);
*
* @param action
* The action to execute. (Currently "setUntrusted only")
* @param args
* The exec() arguments.
* @param callbackContext
* The callback context used when calling back into JavaScript.
* @return Whether the action was valid.
*
*
*/
@Override
public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {
if (action.equals("setUntrusted")) {
try {
allowUntrusted = args.getBoolean(0);
Log.d(LOG_TAG, "Setting allowUntrusted to " + allowUntrusted);
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
CordovaActivity ca = (CordovaActivity) cordova.getActivity();
SystemWebView view = (SystemWebView)webView.getView();
CertificatesCordovaWebViewClient cWebClient =
new CertificatesCordovaWebViewClient((SystemWebViewEngine)webView.getEngine());
cWebClient.setAllowUntrusted(allowUntrusted);
webView.clearCache();
// this fixes a crash that displays the error message:
// "The connection to the server was unsuccessful.
webView.stopLoading();
view.setWebViewClient(cWebClient);
} catch(Exception e){
Log.e(LOG_TAG, "Got unkown error during setting webview in activity", e);
}
}
});
callbackContext.success();
return true;
} catch(Exception e){
Log.e(LOG_TAG, "Got unkown error during passing to UI Thread", e);
}
}
callbackContext.error("Invalid Command");
return false;
}
}

View File

@@ -0,0 +1,39 @@
/*
The MIT License (MIT)
Copyright (c) 2014 Martin Reinhardt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
//
// CDVCertificate.h
//
// Created by Martin Reinhardt on 23.06.2014.
// Copyright Martin Reinhardt 2014. All rights reserved.
#import <Cordova/CDVPlugin.h>
@interface CDVCertificate : CDVPlugin
- (void)setUntrusted:(CDVInvokedUrlCommand*)command;
@end

View File

@@ -0,0 +1,49 @@
/*
The MIT License (MIT)
Copyright (c) 2014 Martin Reinhardt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
//
// CDVCertificate.m
//
// Created by Martin Reinhardt on 23.06.2014.
// Copyright Martin Reinhardt 2014. All rights reserved.
//
#import "CDVCertificate.h"
#import <Cordova/CDV.h>
#import "NSURLRequest+AllowUntrustedCertificates.h"
@implementation CDVCertificate
- (void)setUntrusted:(CDVInvokedUrlCommand*)command {
bool isUntrusted = [[command.arguments objectAtIndex:0] boolValue];
[NSURLRequest setAllowAllRequests:isUntrusted];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end

View File

@@ -0,0 +1,38 @@
/*
The MIT License (MIT)
Copyright (c) 2014 Martin Reinhardt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
//
// NSURLRequest+AllowUntrustedCertificates.h
//
// Created by Martin Reinhardt on 23.06.2014.
// Copyright Martin Reinhardt 2014. All rights reserved.
#import <Foundation/Foundation.h>
@interface NSURLRequest (AllowUntrustedCertificates)
+(void)setAllowAllRequests:(BOOL)allowRequests;
@end

View File

@@ -0,0 +1,54 @@
/*
The MIT License (MIT)
Copyright (c) 2014 Martin Reinhardt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
//
// NSURLRequest+AllowUntrustedCertificates.m
//
// Created by Martin Reinhardt on 23.06.2014.
// Copyright Martin Reinhardt 2014. All rights reserved.
#import "NSURLRequest+AllowUntrustedCertificates.h"
@interface NSURLRequest(AllowUntrustedCertificates_hidden)
+(bool)getAllowAllRequests;
@end
@implementation NSURLRequest (AllowUntrustedCertificates)
static bool _allowRequests = false;
+(void)setAllowAllRequests:(BOOL)allowRequests
{
_allowRequests = allowRequests;
}
+(bool)getAllowAllRequests
{
return _allowRequests;
}
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
return [NSURLRequest getAllowAllRequests];
}
@end

View File

@@ -0,0 +1,49 @@
/*
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Martin Reinhardt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
var Certificate = function () {
};
Certificate.prototype = {
/**
* Activates or deactivates the acceptance of self signed/unsecure SSL certificates
*
* @param {Function} boolActivateUnsecure
* boolean value to set desired behaviour
*/
trustUnsecureCerts: function (boolActivateUnsecure) {
if (cordova.platformId == 'android')
cordova.exec(null, null, 'CertificatesPlugin', 'setUntrusted', [boolActivateUnsecure]);
else
cordova.exec(null, null, 'CDVCertificate', 'setUntrusted', [boolActivateUnsecure]);
}
};
var plugin = new Certificate();
module.exports = plugin;

View File

@@ -0,0 +1,25 @@
<!--
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
-->
cordova-plugin-compat
------------------------
This repo is for remaining backwards compatible with previous versions of Cordova.

View File

@@ -0,0 +1,97 @@
{
"_args": [
[
{
"raw": "cordova-plugin-compat@1.0.0",
"scope": null,
"escapedName": "cordova-plugin-compat",
"name": "cordova-plugin-compat",
"rawSpec": "1.0.0",
"spec": "1.0.0",
"type": "version"
},
"D:\\pWork\\yunkong2.vis.cordova\\node_modules"
]
],
"_from": "cordova-plugin-compat@1.0.0",
"_id": "cordova-plugin-compat@1.0.0",
"_inCache": true,
"_location": "/cordova-plugin-compat",
"_nodeVersion": "4.2.2",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/cordova-plugin-compat-1.0.0.tgz_1459869228517_0.12971219676546752"
},
"_npmUser": {
"name": "macdonst",
"email": "simon.macdonald@gmail.com"
},
"_npmVersion": "2.14.7",
"_phantomChildren": {},
"_requested": {
"raw": "cordova-plugin-compat@1.0.0",
"scope": null,
"escapedName": "cordova-plugin-compat",
"name": "cordova-plugin-compat",
"rawSpec": "1.0.0",
"spec": "1.0.0",
"type": "version"
},
"_requiredBy": [
"#USER"
],
"_resolved": "https://registry.npmjs.org/cordova-plugin-compat/-/cordova-plugin-compat-1.0.0.tgz",
"_shasum": "54b773fa6a212fe8e60ad496bacb57aa01da4232",
"_shrinkwrap": null,
"_spec": "cordova-plugin-compat@1.0.0",
"_where": "D:\\pWork\\yunkong2.vis.cordova\\node_modules",
"author": {
"name": "Apache Software Foundation"
},
"bugs": {
"url": "https://github.com/apache/cordova-plugin-compat/issues"
},
"cordova": {
"id": "cordova-plugin-compat",
"platforms": [
"android"
]
},
"dependencies": {},
"description": "This repo is for remaining backwards compatible with previous versions of Cordova.",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "54b773fa6a212fe8e60ad496bacb57aa01da4232",
"tarball": "https://registry.npmjs.org/cordova-plugin-compat/-/cordova-plugin-compat-1.0.0.tgz"
},
"engines": [
{
"name": "cordova",
"version": ">=5.0.0"
}
],
"gitHead": "c10a3151f1b0113ade3a7f6d5136b508ffdcfb76",
"homepage": "http://github.com/apache/cordova-plugin-compat#readme",
"keywords": [
"ecosystem:cordova",
"ecosystem:phonegap",
"cordova-android"
],
"license": "Apache-2.0",
"maintainers": [
{
"name": "macdonst",
"email": "simon.macdonald@gmail.com"
}
],
"name": "cordova-plugin-compat",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/apache/cordova-plugin-compat.git"
},
"scripts": {},
"version": "1.0.0"
}

View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<plugin xmlns="http://cordova.apache.org/ns/plugins/1.0"
id="cordova-plugin-compat"
version="1.0.0">
<name>Compat</name>
<description>Cordova Compatibility Plugin</description>
<license>Apache 2.0</license>
<keywords>cordova,compat</keywords>
<repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-compat.git</repo>
<!-- android -->
<platform name="android">
<source-file src="src/android/PermissionHelper.java" target-dir="src/org/apache/cordova" />
</platform>
</plugin>

View File

@@ -0,0 +1,138 @@
/*
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;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import android.content.pm.PackageManager;
/**
* This class provides reflective methods for permission requesting and checking so that plugins
* written for cordova-android 5.0.0+ can still compile with earlier cordova-android versions.
*/
public class PermissionHelper {
private static final String LOG_TAG = "CordovaPermissionHelper";
/**
* Requests a "dangerous" permission for the application at runtime. This is a helper method
* alternative to cordovaInterface.requestPermission() that does not require the project to be
* built with cordova-android 5.0.0+
*
* @param plugin The plugin the permission is being requested for
* @param requestCode A requestCode to be passed to the plugin's onRequestPermissionResult()
* along with the result of the permission request
* @param permission The permission to be requested
*/
public static void requestPermission(CordovaPlugin plugin, int requestCode, String permission) {
PermissionHelper.requestPermissions(plugin, requestCode, new String[] {permission});
}
/**
* Requests "dangerous" permissions for the application at runtime. This is a helper method
* alternative to cordovaInterface.requestPermissions() that does not require the project to be
* built with cordova-android 5.0.0+
*
* @param plugin The plugin the permissions are being requested for
* @param requestCode A requestCode to be passed to the plugin's onRequestPermissionResult()
* along with the result of the permissions request
* @param permissions The permissions to be requested
*/
public static void requestPermissions(CordovaPlugin plugin, int requestCode, String[] permissions) {
try {
Method requestPermission = CordovaInterface.class.getDeclaredMethod(
"requestPermissions", CordovaPlugin.class, int.class, String[].class);
// If there is no exception, then this is cordova-android 5.0.0+
requestPermission.invoke(plugin.cordova, plugin, requestCode, permissions);
} catch (NoSuchMethodException noSuchMethodException) {
// cordova-android version is less than 5.0.0, so permission is implicitly granted
LOG.d(LOG_TAG, "No need to request permissions " + Arrays.toString(permissions));
// Notify the plugin that all were granted by using more reflection
deliverPermissionResult(plugin, requestCode, permissions);
} catch (IllegalAccessException illegalAccessException) {
// Should never be caught; this is a public method
LOG.e(LOG_TAG, "IllegalAccessException when requesting permissions " + Arrays.toString(permissions), illegalAccessException);
} catch(InvocationTargetException invocationTargetException) {
// This method does not throw any exceptions, so this should never be caught
LOG.e(LOG_TAG, "invocationTargetException when requesting permissions " + Arrays.toString(permissions), invocationTargetException);
}
}
/**
* Checks at runtime to see if the application has been granted a permission. This is a helper
* method alternative to cordovaInterface.hasPermission() that does not require the project to
* be built with cordova-android 5.0.0+
*
* @param plugin The plugin the permission is being checked against
* @param permission The permission to be checked
*
* @return True if the permission has already been granted and false otherwise
*/
public static boolean hasPermission(CordovaPlugin plugin, String permission) {
try {
Method hasPermission = CordovaInterface.class.getDeclaredMethod("hasPermission", String.class);
// If there is no exception, then this is cordova-android 5.0.0+
return (Boolean) hasPermission.invoke(plugin.cordova, permission);
} catch (NoSuchMethodException noSuchMethodException) {
// cordova-android version is less than 5.0.0, so permission is implicitly granted
LOG.d(LOG_TAG, "No need to check for permission " + permission);
return true;
} catch (IllegalAccessException illegalAccessException) {
// Should never be caught; this is a public method
LOG.e(LOG_TAG, "IllegalAccessException when checking permission " + permission, illegalAccessException);
} catch(InvocationTargetException invocationTargetException) {
// This method does not throw any exceptions, so this should never be caught
LOG.e(LOG_TAG, "invocationTargetException when checking permission " + permission, invocationTargetException);
}
return false;
}
private static void deliverPermissionResult(CordovaPlugin plugin, int requestCode, String[] permissions) {
// Generate the request results
int[] requestResults = new int[permissions.length];
Arrays.fill(requestResults, PackageManager.PERMISSION_GRANTED);
try {
Method onRequestPermissionResult = CordovaPlugin.class.getDeclaredMethod(
"onRequestPermissionResult", int.class, String[].class, int[].class);
onRequestPermissionResult.invoke(plugin, requestCode, permissions, requestResults);
} catch (NoSuchMethodException noSuchMethodException) {
// Should never be caught since the plugin must be written for cordova-android 5.0.0+ if it
// made it to this point
LOG.e(LOG_TAG, "NoSuchMethodException when delivering permissions results", noSuchMethodException);
} catch (IllegalAccessException illegalAccessException) {
// Should never be caught; this is a public method
LOG.e(LOG_TAG, "IllegalAccessException when delivering permissions results", illegalAccessException);
} catch(InvocationTargetException invocationTargetException) {
// This method may throw a JSONException. We are just duplicating cordova-android's
// exception handling behavior here; all it does is log the exception in CordovaActivity,
// print the stacktrace, and ignore it
LOG.e(LOG_TAG, "InvocationTargetException when delivering permissions results", invocationTargetException);
}
}
}

View File

@@ -0,0 +1,37 @@
<!--
#
# 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.
#
-->
# Contributing to Apache Cordova
Anyone can contribute to Cordova. And we need your contributions.
There are multiple ways to contribute: report bugs, improve the docs, and
contribute code.
For instructions on this, start with the
[contribution overview](http://cordova.apache.org/contribute/).
The details are explained there, but the important items are:
- Sign and submit an Apache ICLA (Contributor License Agreement).
- Have a Jira issue open that corresponds to your contribution.
- Run the tests so your patch doesn't break existing functionality.
We look forward to your contributions!

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed 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.

View File

@@ -0,0 +1,5 @@
Apache Cordova
Copyright 2012 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).

View File

@@ -0,0 +1,868 @@
---
title: File
description: Read/write files on the device.
---
<!--
# license: 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.
-->
|Android 4.4|Android 5.1|Android 6.0|iOS 9.3|iOS 10.0|Windows 10 Store|Travis CI|
|:-:|:-:|:-:|:-:|:-:|:-:|:-:|
|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-file/)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-file.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-file)|
# cordova-plugin-file
This plugin implements a File API allowing read/write access to files residing on the device.
This plugin is based on several specs, including :
The HTML5 File API
[http://www.w3.org/TR/FileAPI/](http://www.w3.org/TR/FileAPI/)
The Directories and System extensions
Latest:
[http://www.w3.org/TR/2012/WD-file-system-api-20120417/](http://www.w3.org/TR/2012/WD-file-system-api-20120417/)
Although most of the plugin code was written when an earlier spec was current:
[http://www.w3.org/TR/2011/WD-file-system-api-20110419/](http://www.w3.org/TR/2011/WD-file-system-api-20110419/)
It also implements the FileWriter spec :
[http://dev.w3.org/2009/dap/file-system/file-writer.html](http://dev.w3.org/2009/dap/file-system/file-writer.html)
>*Note* While the W3C FileSystem spec is deprecated for web browsers, the FileSystem APIs are supported in Cordova applications with this plugin for the platforms listed in the _Supported Platforms_ list, with the exception of the Browser platform.
To get a few ideas how to use the plugin, check out the [sample](#sample) at the bottom of this page. For additional examples (browser focused), see the HTML5 Rocks' [FileSystem article.](http://www.html5rocks.com/en/tutorials/file/filesystem/)
For an overview of other storage options, refer to Cordova's
[storage guide](http://cordova.apache.org/docs/en/latest/cordova/storage/storage.html).
This plugin defines global `cordova.file` object.
Although in the global scope, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(cordova.file);
}
Report issues on the [Apache Cordova issue tracker](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20%28Open%2C%20%22In%20Progress%22%2C%20Reopened%29%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20File%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC)
## Installation
cordova plugin add cordova-plugin-file
## Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- OS X
- Windows Phone 7 and 8*
- Windows 8*
- Windows*
- Browser
\* _These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`._
## Where to Store Files
As of v1.2.0, URLs to important file-system directories are provided.
Each URL is in the form _file:///path/to/spot/_, and can be converted to a
`DirectoryEntry` using `window.resolveLocalFileSystemURL()`.
* `cordova.file.applicationDirectory` - Read-only directory where the application
is installed. (_iOS_, _Android_, _BlackBerry 10_, _OSX_, _windows_)
* `cordova.file.applicationStorageDirectory` - Root directory of the application's
sandbox; on iOS & windows this location is read-only (but specific subdirectories [like
`/Documents` on iOS or `/localState` on windows] are read-write). All data contained within
is private to the app. (_iOS_, _Android_, _BlackBerry 10_, _OSX_)
* `cordova.file.dataDirectory` - Persistent and private data storage within the
application's sandbox using internal memory (on Android, if you need to use
external memory, use `.externalDataDirectory`). On iOS, this directory is not
synced with iCloud (use `.syncedDataDirectory`). (_iOS_, _Android_, _BlackBerry 10_, _windows_)
* `cordova.file.cacheDirectory` - Directory for cached data files or any files
that your app can re-create easily. The OS may delete these files when the device
runs low on storage, nevertheless, apps should not rely on the OS to delete files
in here. (_iOS_, _Android_, _BlackBerry 10_, _OSX_, _windows_)
* `cordova.file.externalApplicationStorageDirectory` - Application space on
external storage. (_Android_)
* `cordova.file.externalDataDirectory` - Where to put app-specific data files on
external storage. (_Android_)
* `cordova.file.externalCacheDirectory` - Application cache on external storage.
(_Android_)
* `cordova.file.externalRootDirectory` - External storage (SD card) root. (_Android_, _BlackBerry 10_)
* `cordova.file.tempDirectory` - Temp directory that the OS can clear at will. Do not
rely on the OS to clear this directory; your app should always remove files as
applicable. (_iOS_, _OSX_, _windows_)
* `cordova.file.syncedDataDirectory` - Holds app-specific files that should be synced
(e.g. to iCloud). (_iOS_, _windows_)
* `cordova.file.documentsDirectory` - Files private to the app, but that are meaningful
to other application (e.g. Office files). Note that for _OSX_ this is the user's `~/Documents` directory. (_iOS_, _OSX_)
* `cordova.file.sharedDirectory` - Files globally available to all applications (_BlackBerry 10_)
## File System Layouts
Although technically an implementation detail, it can be very useful to know how
the `cordova.file.*` properties map to physical paths on a real device.
### iOS File System Layout
| Device Path | `cordova.file.*` | `iosExtraFileSystems` | r/w? | persistent? | OS clears | sync | private |
|:-----------------------------------------------|:----------------------------|:----------------------|:----:|:-----------:|:---------:|:----:|:-------:|
| `/var/mobile/Applications/<UUID>/` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;`appname.app/` | applicationDirectory | bundle | r | N/A | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`www/` | - | - | r | N/A | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;`Documents/` | documentsDirectory | documents | r/w | Yes | No | Yes | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`NoCloud/` | - | documents-nosync | r/w | Yes | No | No | Yes |
| &nbsp;&nbsp;&nbsp;`Library` | - | library | r/w | Yes | No | Yes? | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`NoCloud/` | dataDirectory | library-nosync | r/w | Yes | No | No | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Cloud/` | syncedDataDirectory | - | r/w | Yes | No | Yes | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Caches/` | cacheDirectory | cache | r/w | Yes* | Yes\*\*\*| No | Yes |
| &nbsp;&nbsp;&nbsp;`tmp/` | tempDirectory | - | r/w | No\*\* | Yes\*\*\*| No | Yes |
\* Files persist across app restarts and upgrades, but this directory can
be cleared whenever the OS desires. Your app should be able to recreate any
content that might be deleted.
\*\* Files may persist across app restarts, but do not rely on this behavior. Files
are not guaranteed to persist across updates. Your app should remove files from
this directory when it is applicable, as the OS does not guarantee when (or even
if) these files are removed.
\*\*\* The OS may clear the contents of this directory whenever it feels it is
necessary, but do not rely on this. You should clear this directory as
appropriate for your application.
### Android File System Layout
| Device Path | `cordova.file.*` | `AndroidExtraFileSystems` | r/w? | persistent? | OS clears | private |
|:------------------------------------------------|:----------------------------|:--------------------------|:----:|:-----------:|:---------:|:-------:|
| `file:///android_asset/` | applicationDirectory | assets | r | N/A | N/A | Yes |
| `/data/data/<app-id>/` | applicationStorageDirectory | - | r/w | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;`cache` | cacheDirectory | cache | r/w | Yes | Yes\* | Yes |
| &nbsp;&nbsp;&nbsp;`files` | dataDirectory | files | r/w | Yes | No | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Documents` | | documents | r/w | Yes | No | Yes |
| `<sdcard>/` | externalRootDirectory | sdcard | r/w | Yes | No | No |
| &nbsp;&nbsp;&nbsp;`Android/data/<app-id>/` | externalApplicationStorageDirectory | - | r/w | Yes | No | No |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`cache` | externalCacheDirectry | cache-external | r/w | Yes | No\*\*| No |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`files` | externalDataDirectory | files-external | r/w | Yes | No | No |
\* The OS may periodically clear this directory, but do not rely on this behavior. Clear
the contents of this directory as appropriate for your application. Should a user
purge the cache manually, the contents of this directory are removed.
\*\* The OS does not clear this directory automatically; you are responsible for managing
the contents yourself. Should the user purge the cache manually, the contents of the
directory are removed.
**Note**: If external storage can't be mounted, the `cordova.file.external*`
properties are `null`.
### BlackBerry 10 File System Layout
| Device Path | `cordova.file.*` | r/w? | persistent? | OS clears | private |
|:-------------------------------------------------------------|:----------------------------|:----:|:-----------:|:---------:|:-------:|
| `file:///accounts/1000/appdata/<app id>/` | applicationStorageDirectory | r | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;`app/native` | applicationDirectory | r | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;`data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | No | Yes | Yes |
| &nbsp;&nbsp;&nbsp;`data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Yes | No | Yes |
| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | Yes | No | No |
| `file:///accounts/1000/shared` | sharedDirectory | r/w | Yes | No | No |
*Note*: When application is deployed to work perimeter, all paths are relative to /accounts/1000-enterprise.
### OS X File System Layout
| Device Path | `cordova.file.*` | `iosExtraFileSystems` | r/w? | OS clears | private |
|:-------------------------------------------------|:----------------------------|:----------------------|:----:|:---------:|:-------:|
| `/Applications/<appname>.app/` | - | bundle | r | N/A | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;`Content/Resources/` | applicationDirectory | - | r | N/A | Yes |
| `~/Library/Application Support/<bundle-id>/` | applicationStorageDirectory | - | r/w | No | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;`files/` | dataDirectory | - | r/w | No | Yes |
| `~/Documents/` | documentsDirectory | documents | r/w | No | No |
| `~/Library/Caches/<bundle-id>/` | cacheDirectory | cache | r/w | No | Yes |
| `/tmp/` | tempDirectory | - | r/w | Yes\* | Yes |
| `/` | rootDirectory | root | r/w | No\*\* | No |
**Note**: This is the layout for non sandboxed applications. I you enable sandboxing, the `applicationStorageDirectory` will be below ` ~/Library/Containers/<bundle-id>/Data/Library/Application Support`.
\* Files persist across app restarts and upgrades, but this directory can
be cleared whenever the OS desires. Your app should be able to recreate any
content that might be deleted. You should clear this directory as
appropriate for your application.
\*\* Allows access to the entire file system. This is only available for non sandboxed apps.
### Windows File System Layout
| Device Path | `cordova.file.*` | r/w? | persistent? | OS clears | private |
|:------------------------------------------------------|:----------------------------|:----:|:-----------:|:---------:|:-------:|
| `ms-appdata:///` | applicationDirectory | r | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;`local/` | dataDirectory | r/w | Yes | No | Yes |
| &nbsp;&nbsp;&nbsp;`temp/` | cacheDirectory | r/w | No | Yes\* | Yes |
| &nbsp;&nbsp;&nbsp;`temp/` | tempDirectory | r/w | No | Yes\* | Yes |
| &nbsp;&nbsp;&nbsp;`roaming/` | syncedDataDirectory | r/w | Yes | No | Yes |
\* The OS may periodically clear this directory
## Android Quirks
### Android Persistent storage location
There are multiple valid locations to store persistent files on an Android
device. See [this page](http://developer.android.com/guide/topics/data/data-storage.html)
for an extensive discussion of the various possibilities.
Previous versions of the plugin would choose the location of the temporary and
persistent files on startup, based on whether the device claimed that the SD
Card (or equivalent storage partition) was mounted. If the SD Card was mounted,
or if a large internal storage partition was available (such as on Nexus
devices,) then the persistent files would be stored in the root of that space.
This meant that all Cordova apps could see all of the files available on the
card.
If the SD card was not available, then previous versions would store data under
`/data/data/<packageId>`, which isolates apps from each other, but may still
cause data to be shared between users.
It is now possible to choose whether to store files in the internal file
storage location, or using the previous logic, with a preference in your
application's `config.xml` file. To do this, add one of these two lines to
`config.xml`:
<preference name="AndroidPersistentFileLocation" value="Internal" />
<preference name="AndroidPersistentFileLocation" value="Compatibility" />
Without this line, the File plugin will use `Internal` as the default. If
a preference tag is present, and is not one of these values, the application
will not start.
If your application has previously been shipped to users, using an older (pre-
3.0.0) version of this plugin, and has stored files in the persistent filesystem,
then you should set the preference to `Compatibility` if your config.xml does not specify a location for the persistent filesystem. Switching the location to
"Internal" would mean that existing users who upgrade their application may be
unable to access their previously-stored files, depending on their device.
If your application is new, or has never previously stored files in the
persistent filesystem, then the `Internal` setting is generally recommended.
### Slow recursive operations for /android_asset
Listing asset directories is really slow on Android. You can speed it up though, by
adding `src/android/build-extras.gradle` to the root of your android project (also
requires cordova-android@4.0.0 or greater).
### Permisson to write to external storage when it's not mounted on Marshmallow
Marshmallow requires the apps to ask for permissions when reading/writing to external locations. By
[default](http://developer.android.com/guide/topics/data/data-storage.html#filesExternal), your app has permission to write to
`cordova.file.applicationStorageDirectory` and `cordova.file.externalApplicationStorageDirectory`, and the plugin doesn't request permission
for these two directories unless external storage is not mounted. However due to a limitation, when external storage is not mounted, it would ask for
permission to write to `cordova.file.externalApplicationStorageDirectory`.
## iOS Quirks
- `cordova.file.applicationStorageDirectory` is read-only; attempting to store
files within the root directory will fail. Use one of the other `cordova.file.*`
properties defined for iOS (only `applicationDirectory` and `applicationStorageDirectory` are
read-only).
- `FileReader.readAsText(blob, encoding)`
- The `encoding` parameter is not supported, and UTF-8 encoding is always in effect.
### iOS Persistent storage location
There are two valid locations to store persistent files on an iOS device: the
Documents directory and the Library directory. Previous versions of the plugin
only ever stored persistent files in the Documents directory. This had the
side-effect of making all of an application's files visible in iTunes, which
was often unintended, especially for applications which handle lots of small
files, rather than producing complete documents for export, which is the
intended purpose of the directory.
It is now possible to choose whether to store files in the documents or library
directory, with a preference in your application's `config.xml` file. To do this,
add one of these two lines to `config.xml`:
<preference name="iosPersistentFileLocation" value="Library" />
<preference name="iosPersistentFileLocation" value="Compatibility" />
Without this line, the File plugin will use `Compatibility` as the default. If
a preference tag is present, and is not one of these values, the application
will not start.
If your application has previously been shipped to users, using an older (pre-
1.0) version of this plugin, and has stored files in the persistent filesystem,
then you should set the preference to `Compatibility`. Switching the location to
`Library` would mean that existing users who upgrade their application would be
unable to access their previously-stored files.
If your application is new, or has never previously stored files in the
persistent filesystem, then the `Library` setting is generally recommended.
## Firefox OS Quirks
The File System API is not natively supported by Firefox OS and is implemented
as a shim on top of indexedDB.
* Does not fail when removing non-empty directories
* Does not support metadata for directories
* Methods `copyTo` and `moveTo` do not support directories
The following data paths are supported:
* `applicationDirectory` - Uses `xhr` to get local files that are packaged with the app.
* `dataDirectory` - For persistent app-specific data files.
* `cacheDirectory` - Cached files that should survive app restarts (Apps should not rely
on the OS to delete files in here).
## Browser Quirks
### Common quirks and remarks
- Each browser uses its own sandboxed filesystem. IE and Firefox use IndexedDB as a base.
All browsers use forward slash as directory separator in a path.
- Directory entries have to be created successively.
For example, the call `fs.root.getDirectory('dir1/dir2', {create:true}, successCallback, errorCallback)`
will fail if dir1 did not exist.
- The plugin requests user permission to use persistent storage at the application first start.
- Plugin supports `cdvfile://localhost` (local resources) only. I.e. external resources are not supported via `cdvfile`.
- The plugin does not follow ["File System API 8.3 Naming restrictions"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions).
- Blob and File' `close` function is not supported.
- `FileSaver` and `BlobBuilder` are not supported by this plugin and don't have stubs.
- The plugin does not support `requestAllFileSystems`. This function is also missing in the specifications.
- Entries in directory will not be removed if you use `create: true` flag for existing directory.
- Files created via constructor are not supported. You should use entry.file method instead.
- Each browser uses its own form for blob URL references.
- `readAsDataURL` function is supported, but the mediatype in Chrome depends on entry name extension,
mediatype in IE is always empty (which is the same as `text-plain` according the specification),
the mediatype in Firefox is always `application/octet-stream`.
For example, if the content is `abcdefg` then Firefox returns `data:application/octet-stream;base64,YWJjZGVmZw==`,
IE returns `data:;base64,YWJjZGVmZw==`, Chrome returns `data:<mediatype depending on extension of entry name>;base64,YWJjZGVmZw==`.
- `toInternalURL` returns the path in the form `file:///persistent/path/to/entry` (Firefox, IE).
Chrome returns the path in the form `cdvfile://localhost/persistent/file`.
### Chrome quirks
- Chrome filesystem is not immediately ready after device ready event. As a workaround you can subscribe to `filePluginIsReady` event.
Example:
```javascript
window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
```
You can use `window.isFilePluginReadyRaised` function to check whether event was already raised.
- window.requestFileSystem TEMPORARY and PERSISTENT filesystem quotas are not limited in Chrome.
- To increase persistent storage in Chrome you need to call `window.initPersistentFileSystem` method. Persistent storage quota is 5 MB by default.
- Chrome requires `--allow-file-access-from-files` run argument to support API via `file:///` protocol.
- `File` object will be not changed if you use flag `{create:true}` when getting an existing `Entry`.
- events `cancelable` property is set to true in Chrome. This is contrary to the [specification](http://dev.w3.org/2009/dap/file-system/file-writer.html).
- `toURL` function in Chrome returns `filesystem:`-prefixed path depending on application host.
For example, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`.
- `toURL` function result does not contain trailing slash in case of directory entry.
Chrome resolves directories with slash-trailed urls correctly though.
- `resolveLocalFileSystemURL` method requires the inbound `url` to have `filesystem` prefix. For example, `url` parameter for `resolveLocalFileSystemURL`
should be in the form `filesystem:file:///persistent/somefile.txt` as opposed to the form `file:///persistent/somefile.txt` in Android.
- Deprecated `toNativeURL` function is not supported and does not have a stub.
- `setMetadata` function is not stated in the specifications and not supported.
- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of SYNTAX_ERR(code: 8) on requesting of a non-existant filesystem.
- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of PATH_EXISTS_ERR(code: 12) on trying to exclusively create a file or directory, which already exists.
- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of NO_MODIFICATION_ALLOWED_ERR(code: 6) on trying to call removeRecursively on the root file system.
- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of NOT_FOUND_ERR(code: 1) on trying to moveTo directory that does not exist.
### IndexedDB-based impl quirks (Firefox and IE)
- `.` and `..` are not supported.
- IE does not support `file:///`-mode; only hosted mode is supported (http://localhost:xxxx).
- Firefox filesystem size is not limited but each 50MB extension will request a user permission.
IE10 allows up to 10mb of combined AppCache and IndexedDB used in implementation of filesystem without prompting,
once you hit that level you will be asked if you want to allow it to be increased up to a max of 250mb per site.
So `size` parameter for `requestFileSystem` function does not affect filesystem in Firefox and IE.
- `readAsBinaryString` function is not stated in the Specs and not supported in IE and does not have a stub.
- `file.type` is always null.
- You should not create entry using DirectoryEntry instance callback result which was deleted.
Otherwise, you will get a 'hanging entry'.
- Before you can read a file, which was just written you need to get a new instance of this file.
- `setMetadata` function, which is not stated in the Specs supports `modificationTime` field change only.
- `copyTo` and `moveTo` functions do not support directories.
- Directories metadata is not supported.
- Both Entry.remove and directoryEntry.removeRecursively don't fail when removing
non-empty directories - directories being removed are cleaned along with contents instead.
- `abort` and `truncate` functions are not supported.
- progress events are not fired. For example, this handler will be not executed:
```javascript
writer.onprogress = function() { /*commands*/ };
```
## Upgrading Notes
In v1.0.0 of this plugin, the `FileEntry` and `DirectoryEntry` structures have changed,
to be more in line with the published specification.
Previous (pre-1.0.0) versions of the plugin stored the device-absolute-file-location
in the `fullPath` property of `Entry` objects. These paths would typically look like
/var/mobile/Applications/<application UUID>/Documents/path/to/file (iOS)
/storage/emulated/0/path/to/file (Android)
These paths were also returned by the `toURL()` method of the `Entry` objects.
With v1.0.0, the `fullPath` attribute is the path to the file, _relative to the root of
the HTML filesystem_. So, the above paths would now both be represented by a `FileEntry`
object with a `fullPath` of
/path/to/file
If your application works with device-absolute-paths, and you previously retrieved those
paths through the `fullPath` property of `Entry` objects, then you should update your code
to use `entry.toURL()` instead.
For backwards compatibility, the `resolveLocalFileSystemURL()` method will accept a
device-absolute-path, and will return an `Entry` object corresponding to it, as long as that
file exists within either the `TEMPORARY` or `PERSISTENT` filesystems.
This has particularly been an issue with the File-Transfer plugin, which previously used
device-absolute-paths (and can still accept them). It has been updated to work correctly
with FileSystem URLs, so replacing `entry.fullPath` with `entry.toURL()` should resolve any
issues getting that plugin to work with files on the device.
In v1.1.0 the return value of `toURL()` was changed (see [CB-6394](https://issues.apache.org/jira/browse/CB-6394))
to return an absolute 'file://' URL. wherever possible. To ensure a 'cdvfile:'-URL you can use `toInternalURL()` now.
This method will now return filesystem URLs of the form
cdvfile://localhost/persistent/path/to/file
which can be used to identify the file uniquely.
## cdvfile protocol
**Purpose**
`cdvfile://localhost/persistent|temporary|another-fs-root*/path/to/file` can be used for platform-independent file paths.
cdvfile paths are supported by core plugins - for example you can download an mp3 file to cdvfile-path via `cordova-plugin-file-transfer` and play it via `cordova-plugin-media`.
__*Note__: See [Where to Store Files](#where-to-store-files), [File System Layouts](#file-system-layouts) and [Configuring the Plugin](#configuring-the-plugin-optional) for more details about available fs roots.
To use `cdvfile` as a tag' `src` you can convert it to native path via `toURL()` method of the resolved fileEntry, which you can get via `resolveLocalFileSystemURL` - see examples below.
You can also use `cdvfile://` paths directly in the DOM, for example:
```HTML
<img src="cdvfile://localhost/persistent/img/logo.png" />
```
__Note__: This method requires following Content Security rules updates:
* Add `cdvfile:` scheme to `Content-Security-Policy` meta tag of the index page, e.g.:
- `<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: `**cdvfile:**` https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">`
* Add `<access origin="cdvfile://*" />` to `config.xml`.
**Converting cdvfile:// to native path**
```javascript
resolveLocalFileSystemURL('cdvfile://localhost/temporary/path/to/file.mp4', function(entry) {
var nativePath = entry.toURL();
console.log('Native URI: ' + nativePath);
document.getElementById('video').src = nativePath;
```
**Converting native path to cdvfile://**
```javascript
resolveLocalFileSystemURL(nativePath, function(entry) {
console.log('cdvfile URI: ' + entry.toInternalURL());
```
**Using cdvfile in core plugins**
```javascript
fileTransfer.download(uri, 'cdvfile://localhost/temporary/path/to/file.mp3', function (entry) { ...
```
```javascript
var my_media = new Media('cdvfile://localhost/temporary/path/to/file.mp3', ...);
my_media.play();
```
#### cdvfile quirks
- Using `cdvfile://` paths in the DOM is not supported on Windows platform (a path can be converted to native instead).
## List of Error Codes and Meanings
When an error is thrown, one of the following codes will be used.
| Code | Constant |
|-----:|:------------------------------|
| 1 | `NOT_FOUND_ERR` |
| 2 | `SECURITY_ERR` |
| 3 | `ABORT_ERR` |
| 4 | `NOT_READABLE_ERR` |
| 5 | `ENCODING_ERR` |
| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
| 7 | `INVALID_STATE_ERR` |
| 8 | `SYNTAX_ERR` |
| 9 | `INVALID_MODIFICATION_ERR` |
| 10 | `QUOTA_EXCEEDED_ERR` |
| 11 | `TYPE_MISMATCH_ERR` |
| 12 | `PATH_EXISTS_ERR` |
## Configuring the Plugin (Optional)
The set of available filesystems can be configured per-platform. Both iOS and
Android recognize a <preference> tag in `config.xml` which names the
filesystems to be installed. By default, all file-system roots are enabled.
<preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" />
<preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,assets,root" />
### Android
* `files`: The application's internal file storage directory
* `files-external`: The application's external file storage directory
* `sdcard`: The global external file storage directory (this is the root of the SD card, if one is installed). You must have the `android.permission.WRITE_EXTERNAL_STORAGE` permission to use this.
* `cache`: The application's internal cache directory
* `cache-external`: The application's external cache directory
* `assets`: The application's bundle (read-only)
* `root`: The entire device filesystem
Android also supports a special filesystem named "documents", which represents a "/Documents/" subdirectory within the "files" filesystem.
### iOS
* `library`: The application's Library directory
* `documents`: The application's Documents directory
* `cache`: The application's Cache directory
* `bundle`: The application's bundle; the location of the app itself on disk (read-only)
* `root`: The entire device filesystem
By default, the library and documents directories can be synced to iCloud. You can also request two additional filesystems, `library-nosync` and `documents-nosync`, which represent a special non-synced directory within the `/Library` or `/Documents` filesystem.
## Sample: Create Files and Directories, Write, Read, and Append files <a name="sample"></a>
The File plugin allows you to do things like store files in a temporary or persistent storage location for your app (sandboxed storage) and to store files in other platform-dependent locations. The code snippets in this section demonstrate different tasks including:
* [Accessing the file system](#persistent)
* Using cross-platform Cordova file URLs to [store your files](#appendFile) (see _Where to Store Files_ for more info)
* Creating [files](#persistent) and [directories](#createDir)
* [Writing to files](#writeFile)
* [Reading files](#readFile)
* [Appending files](#appendFile)
* [Display an image file](#displayImage)
## Create a persistent file <a name="persistent"></a>
Before you use the File plugin APIs, you can get access to the file system using `requestFileSystem`. When you do this, you can request either persistent or temporary storage. Persistent storage will not be removed unless permission is granted by the user.
When you get file system access using `requestFileSystem`, access is granted for the sandboxed file system only (the sandbox limits access to the app itself), not for general access to any file system location on the device. (To access file system locations outside the sandboxed storage, use other methods such as window.requestLocalFileSystemURL, which support platform-specific locations. For one example of this, see _Append a File_.)
Here is a request for persistent storage.
>*Note* When targeting WebView clients (instead of a browser) or native apps (Windows), you dont need to use `requestQuota` before using persistent storage.
```js
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
console.log('file system open: ' + fs.name);
fs.root.getFile("newPersistentFile.txt", { create: true, exclusive: false }, function (fileEntry) {
console.log("fileEntry is file?" + fileEntry.isFile.toString());
// fileEntry.name == 'someFile.txt'
// fileEntry.fullPath == '/someFile.txt'
writeFile(fileEntry, null);
}, onErrorCreateFile);
}, onErrorLoadFs);
```
The success callback receives FileSystem object (fs). Use `fs.root` to return a DirectoryEntry object, which you can use to create or get a file (by calling `getFile`). In this example, `fs.root` is a DirectoryEntry object that represents the persistent storage in the sandboxed file system.
The success callback for `getFile` receives a FileEntry object. You can use this to perform file write and file read operations.
## Create a temporary file
Here is an example of a request for temporary storage. Temporary storage may be deleted by the operating system if the device runs low on memory.
```js
window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
console.log('file system open: ' + fs.name);
createFile(fs.root, "newTempFile.txt", false);
}, onErrorLoadFs);
```
When you are using temporary storage, you can create or get the file by calling `getFile`. As in the persistent storage example, this will give you a FileEntry object that you can use for read or write operations.
```js
function createFile(dirEntry, fileName, isAppend) {
// Creates a new file or returns the file if it already exists.
dirEntry.getFile(fileName, {create: true, exclusive: false}, function(fileEntry) {
writeFile(fileEntry, null, isAppend);
}, onErrorCreateFile);
}
```
## Write to a file <a name="writeFile"></a>
Once you have a FileEntry object, you can write to the file by calling `createWriter`, which returns a FileWriter object in the success callback. Call the `write` method of FileWriter to write to the file.
```js
function writeFile(fileEntry, dataObj) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log("Successful file write...");
readFile(fileEntry);
};
fileWriter.onerror = function (e) {
console.log("Failed file write: " + e.toString());
};
// If data object is not passed in,
// create a new Blob instead.
if (!dataObj) {
dataObj = new Blob(['some file data'], { type: 'text/plain' });
}
fileWriter.write(dataObj);
});
}
```
## Read a file <a name="readFile"></a>
You also need a FileEntry object to read an existing file. Use the file property of FileEntry to get the file reference, and then create a new FileReader object. You can use methods like `readAsText` to start the read operation. When the read operation is complete, `this.result` stores the result of the read operation.
```js
function readFile(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
console.log("Successful file read: " + this.result);
displayFileData(fileEntry.fullPath + ": " + this.result);
};
reader.readAsText(file);
}, onErrorReadFile);
}
```
## Append a file using alternative methods <a name="appendFile"></a>
Of course, you will often want to append existing files instead of creating new ones. Here is an example of that. This example shows another way that you can access the file system using window.resolveLocalFileSystemURL. In this example, pass the cross-platform Cordova file URL, cordova.file.dataDirectory, to the function. The success callback receives a DirectoryEntry object, which you can use to do things like create a file.
```js
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dirEntry) {
console.log('file system open: ' + dirEntry.name);
var isAppend = true;
createFile(dirEntry, "fileToAppend.txt", isAppend);
}, onErrorLoadFs);
```
In addition to this usage, you can use `resolveLocalFileSystemURL` to get access to some file system locations that are not part of the sandboxed storage system. See _Where to store Files_ for more information; many of these storage locations are platform-specific. You can also pass cross-platform file system locations to `resolveLocalFileSystemURL` using the _cdvfile protocol_.
For the append operation, there is nothing new in the `createFile` function that is called in the preceding code (see the preceding examples for the actual code). `createFile` calls `writeFile`. In `writeFile`, you check whether an append operation is requested.
Once you have a FileWriter object, call the `seek` method, and pass in the index value for the position where you want to write. In this example, you also test whether the file exists. After calling seek, then call the write method of FileWriter.
```js
function writeFile(fileEntry, dataObj, isAppend) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log("Successful file read...");
readFile(fileEntry);
};
fileWriter.onerror = function (e) {
console.log("Failed file read: " + e.toString());
};
// If we are appending data to file, go to the end of the file.
if (isAppend) {
try {
fileWriter.seek(fileWriter.length);
}
catch (e) {
console.log("file doesn't exist!");
}
}
fileWriter.write(dataObj);
});
}
```
## Store an existing binary file <a name="binaryFile"></a>
We already showed how to write to a file that you just created in the sandboxed file system. What if you need to get access to an existing file and convert that to something you can store on your device? In this example, you obtain a file using an xhr request, and then save it to the cache in the sandboxed file system.
Before you get the file, get a FileSystem reference using `requestFileSystem`. By passing window.TEMPORARY in the method call (same as before), the returned FileSystem object (fs) represents the cache in the sandboxed file system. Use `fs.root` to get the DirectoryEntry object that you need.
```js
window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
console.log('file system open: ' + fs.name);
getSampleFile(fs.root);
}, onErrorLoadFs);
```
For completeness, here is the xhr request to get a Blob image. There is nothing Cordova-specific in this code, except that you forward the DirectoryEntry reference that you already obtained as an argument to the saveFile function. You will save the blob image and display it later after reading the file (to validate the operation).
```js
function getSampleFile(dirEntry) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://cordova.apache.org/static/img/cordova_bot.png', true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status == 200) {
var blob = new Blob([this.response], { type: 'image/png' });
saveFile(dirEntry, blob, "downloadedImage.png");
}
};
xhr.send();
}
```
>*Note* For Cordova 5 security, the preceding code requires that you add the domain name, http://cordova.apache.org, to the Content-Security-Policy <meta> element in index.html.
After getting the file, copy the contents to a new file. The current DirectoryEntry object is already associated with the app cache.
```js
function saveFile(dirEntry, fileData, fileName) {
dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
writeFile(fileEntry, fileData);
}, onErrorCreateFile);
}
```
In writeFile, you pass in the Blob object as the dataObj and you will save that in the new file.
```js
function writeFile(fileEntry, dataObj, isAppend) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log("Successful file write...");
if (dataObj.type == "image/png") {
readBinaryFile(fileEntry);
}
else {
readFile(fileEntry);
}
};
fileWriter.onerror = function(e) {
console.log("Failed file write: " + e.toString());
};
fileWriter.write(dataObj);
});
}
```
After writing to the file, read it and display it. You saved the image as binary data, so you can read it using FileReader.readAsArrayBuffer.
```js
function readBinaryFile(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
console.log("Successful file write: " + this.result);
displayFileData(fileEntry.fullPath + ": " + this.result);
var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
displayImage(blob);
};
reader.readAsArrayBuffer(file);
}, onErrorReadFile);
}
```
After reading the data, you can display the image using code like this. Use window.URL.createObjectURL to get a DOM string for the Blob image.
```js
function displayImage(blob) {
// Displays image if result is a valid DOM string for an image.
var elem = document.getElementById('imageFile');
// Note: Use window.URL.revokeObjectURL when finished with image.
elem.src = window.URL.createObjectURL(blob);
}
```
## Display an image file <a name="displayImage"></a>
To display an image using a FileEntry, you can call the `toURL` method.
```js
function displayImageByFileURL(fileEntry) {
var elem = document.getElementById('imageFile');
elem.src = fileEntry.toURL();
}
```
If you are using some platform-specific URIs instead of a FileEntry and you want to display an image, you may need to include the main part of the URI in the Content-Security-Policy <meta> element in index.html. For example, on Windows 10, you can include `ms-appdata:` in your <meta> element. Here is an example.
```html
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: ms-appdata: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
```
## Create Directories <a name="createDir"></a>
In the code here, you create directories in the root of the app storage location. You could use this code with any writable storage location (that is, any DirectoryEntry). Here, you write to the application cache (assuming that you used window.TEMPORARY to get your FileSystem object) by passing fs.root into this function.
This code creates the /NewDirInRoot/images folder in the application cache. For platform-specific values, look at _File System Layouts_.
```js
function createDirectory(rootDirEntry) {
rootDirEntry.getDirectory('NewDirInRoot', { create: true }, function (dirEntry) {
dirEntry.getDirectory('images', { create: true }, function (subDirEntry) {
createFile(subDirEntry, "fileInNewSubDir.txt");
}, onErrorGetDir);
}, onErrorGetDir);
}
```
When creating subfolders, you need to create each folder separately as shown in the preceding code.

View File

@@ -0,0 +1,455 @@
<!--
#
# 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.
#
-->
# Release Notes
### 4.3.3 (Apr 27, 2017)
* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) Added **Android 6.0** build badge to `README`
* [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder
### 4.3.2 (Feb 28, 2017)
* [CB-12353](https://issues.apache.org/jira/browse/CB-12353) Corrected merges usage in `plugin.xml`
* [CB-12369](https://issues.apache.org/jira/browse/CB-12369) Add plugin typings from `DefinitelyTyped`
* [CB-12363](https://issues.apache.org/jira/browse/CB-12363) Added build badges for **iOS 9.3** and **iOS 10.0**
* [CB-12230](https://issues.apache.org/jira/browse/CB-12230) Removed **Windows 8.1** build badges
### 4.3.1 (Dec 07, 2016)
* [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Updated version and RELEASENOTES.md for release 4.3.1
* [CB-12112](https://issues.apache.org/jira/browse/CB-12112) windows: Make available to move folder trees
* fix ENCODING_ERR for applicationDirectory
* [CB-11848](https://issues.apache.org/jira/browse/CB-11848) windows: Remove duplicate slash after file system path
* [CB-11917](https://issues.apache.org/jira/browse/CB-11917) - Remove pull request template checklist item: "iCLA has been submitted…"
* [CB-11947](https://issues.apache.org/jira/browse/CB-11947) fixed typo that occurs when adding file-transfer plugin
* [CB-11832](https://issues.apache.org/jira/browse/CB-11832) Incremented plugin version.
### 4.3.0 (Sep 08, 2016)
* [CB-11795](https://issues.apache.org/jira/browse/CB-11795) Add 'protective' entry to cordovaDependencies
* Add handling for `SecurityException`
* [CB-11368](https://issues.apache.org/jira/browse/CB-11368) **android**: Resolve content `URLs` produced by contacts plugin
* Plugin uses `Android Log class` and not `Cordova LOG class`
* [CB-11693](https://issues.apache.org/jira/browse/CB-11693) **ios**: Run copy and move operations in the background thread
* [CB-11699](https://issues.apache.org/jira/browse/CB-11699) Read files as Data URLs properly
* [CB-11305](https://issues.apache.org/jira/browse/CB-11305) Enable `cdvfile: assets fs root` for `DOM` requests
* [CB-11385](https://issues.apache.org/jira/browse/CB-11385) android: Import java.nio.charset.Charset in LocalFileSystem class
* Add badges for paramedic builds on Jenkins
* [CB-11407](https://issues.apache.org/jira/browse/CB-11407) ios: added extern keyword to constants to fix phonegap-webview-ios template issue.
* [CB-11385](https://issues.apache.org/jira/browse/CB-11385) **android**: Does not pass sonarqube scan
* Add pull request template.
* Minor edits to the `README.md`
* [CB-11142](https://issues.apache.org/jira/browse/CB-11142) Fix the `NeedPermission` code for the case when external media is not mounted in Android
* [CB-11003](https://issues.apache.org/jira/browse/CB-11003) Adding samples to Readme.
* [CB-10996](https://issues.apache.org/jira/browse/CB-10996) Adding front matter to README.md
* [CB-11115](https://issues.apache.org/jira/browse/CB-11115) **android**: Removing dependency on FileDescriptor toString in content provider tests
### 4.2.0 (Apr 15, 2016)
* [CB-10960](https://issues.apache.org/jira/browse/CB-10960) Uncaught `#<FileError>` in `write()` when `readyState != WRITING ?`
* Replace `PermissionHelper.java` with `cordova-plugin-compat`
* [CB-10977](https://issues.apache.org/jira/browse/CB-10977) **Android** Removing global state used for permission requests
* CB-10798, [CB-10384](https://issues.apache.org/jira/browse/CB-10384) Fixing permissions for **Marshmallow**.
* Fix test failure on **WP 8.1**
* [CB-10577](https://issues.apache.org/jira/browse/CB-10577) **Windows** `resolveLocalFileSystemURL` should omit trailing slash for file
* [CB-7862](https://issues.apache.org/jira/browse/CB-7862) `FileReader` reads large files in chunks with progress.
* [CB-10577](https://issues.apache.org/jira/browse/CB-10577) **Android** `resolveLocalFileSystemURL` should detect directory vs file.
* [CB-9753](https://issues.apache.org/jira/browse/CB-9753) index out of bounds on `requestFileSystem`.
* Remove `warning` emoji, as it doesn't correctly display in the docs website: cordova.apache.org/docs/en/dev/cordova-plugin-file/index.html. This closes #166
* [CB-10636](https://issues.apache.org/jira/browse/CB-10636) Add `JSHint` for plugins
* [CB-10411](https://issues.apache.org/jira/browse/CB-10411) Error in `file.spec.129` of `cordova-plugin-file`
### 4.1.1 (Feb 09, 2016)
* Edit package.json license to match SPDX id
* [CB-10419](https://issues.apache.org/jira/browse/CB-10419) cordova-plugin-file 4.0.0 error with browserify workflow
### 4.1.0 (Jan 15, 2016)
* added `.ratignore` file
* [CB-10319](https://issues.apache.org/jira/browse/CB-10319) **android** Adding reflective helper methods for permission requests
* [CB-10023](https://issues.apache.org/jira/browse/CB-10023) Fix `proxy not found error` on Chrome.
* [CB-8863](https://issues.apache.org/jira/browse/CB-8863) **ios** Fix block usage of self
### 4.0.0 (Nov 18, 2015)
* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest
* [CB-8497](https://issues.apache.org/jira/browse/CB-8497) Fix handling of file paths with `#` character
* Do not inject default `AndroidPersistentFileLocation` into `config.xml`
* [CB-9891](https://issues.apache.org/jira/browse/CB-9891): Fix permission errors due to `URI encoding` inconsistency on **Android**
* Fixed `NullPointer Exception` in **Android 5** and above due to invalid column name on cursor
* Fix default persistent file location
* fix `applicationDirectory` to use `ms-appx:///`
* Add **Windows** paths to `cordova.file` object
* [CB-9851](https://issues.apache.org/jira/browse/CB-9851) Document `cdvfile` protocol quirk - using `cdvfile://` in the `DOM` is not supported on **Windows**
* [CB-9752](https://issues.apache.org/jira/browse/CB-9752) `getDirectory` fails on valid directory with assets filesystem
* [CB-7253](https://issues.apache.org/jira/browse/CB-7253) `requestFileSystem` fails when no external storage is present
* Adding permissions for **Marshmallow**. Now supports **Anrdoid 6.0**
* Fixing contribute link.
* always use setters to fix memory issues without `ARC` for **iOS**
* [CB-9331](https://issues.apache.org/jira/browse/CB-9331) `getFreeDiskSpace` **iOS**.
* override `resolveLocalFileSystemURL` by `webkitResolveLocalFileSystemURL` for **browser** platform add `.project` into git ignore list
* Fail with `FileError.ENCODING_ERR` on encoding exception.
* [CB-9544](https://issues.apache.org/jira/browse/CB-9544) Add file plugin for **OSX**
* [CB-9539](https://issues.apache.org/jira/browse/CB-9539) Fixed test failure on **Android** emulator
* Added docs on `CSP` rules needed for using `cdvfile` in DOM src. This closes #120
* Added `cdvfile` protocol purpose description and examples
### 3.0.0 (Aug 18, 2015)
* Make Android default persistent file location internal
* Fixed issue with file paths not existing when using browserify
* [CB-9251](https://issues.apache.org/jira/browse/CB-9251): Changed from Intents to Preferences object as per the issue
* [CB-9215](https://issues.apache.org/jira/browse/CB-9215) Add cordova-plugin-file manual test for windows platform
### 2.1.0 (Jun 17, 2015)
* added missing license header
* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-file documentation translation: cordova-plugin-file
* fix npm md
* [CB-8844](https://issues.apache.org/jira/browse/CB-8844) Increased timeout for asset tests
* Updated resolveFileSystem.js so it can be parsed by uglifyJS
* [CB-8860](https://issues.apache.org/jira/browse/CB-8860) cordova-plugin-file documentation translation: cordova-plugin-file
* [CB-8792](https://issues.apache.org/jira/browse/CB-8792) Fixes reading of json files using readAsText
### 2.0.0 (Apr 15, 2015)
* [CB-8849](https://issues.apache.org/jira/browse/CB-8849) Fixed ReadAsArrayBuffer to return ArrayBuffer and not Array on WP8
* [CB-8819](https://issues.apache.org/jira/browse/CB-8819) Fixed FileReader's readAsBinaryString on wp8
* [CB-8746](https://issues.apache.org/jira/browse/CB-8746) gave plugin major version bump
* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) android: Fix broken unit tests from plugin rename
* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) changed plugin-id to pacakge-name
* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) properly updated translated docs to use new id
* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) updated translated docs to use new id
* Use TRAVIS_BUILD_DIR, install paramedic by npm
* docs: added Windows to supported platforms
* [CB-8699](https://issues.apache.org/jira/browse/CB-8699) [CB-6428](https://issues.apache.org/jira/browse/CB-6428) Fix uncompressed assets being copied as zero length files
* [CB-6428](https://issues.apache.org/jira/browse/CB-6428) android: Fix assets FileEntry having size of -1
* android: Move URLforFullPath into base class (and rename to localUrlforFullPath)
* [CB-6428](https://issues.apache.org/jira/browse/CB-6428) Mention build-extras.gradle in README
* [CB-7109](https://issues.apache.org/jira/browse/CB-7109) android: Parse arguments off of the main thread (close #97)
* [CB-8695](https://issues.apache.org/jira/browse/CB-8695) ios: Fix `blob.slice()` for `asset-library` URLs (close #105)
* Tweak build-extras.gradle to just read/write to main `assets/` instead of `build/`
* [CB-8689](https://issues.apache.org/jira/browse/CB-8689) Fix NPE in makeEntryForNativeUri (was affecting file-transfer)
* [CB-8675](https://issues.apache.org/jira/browse/CB-8675) Revert "CB-8351 ios: Use base64EncodedStringWithOptions instead of CordovaLib's class extension"
* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme
* [CB-8659](https://issues.apache.org/jira/browse/CB-8659): ios: 4.0.x Compatibility: Remove use of initWebView method
* Add a cache to speed up AssetFilesystem directory listings
* [CB-8663](https://issues.apache.org/jira/browse/CB-8663) android: Don't notify MediaScanner of private files
* Don't log stacktrace for normal exceptions (e.g. file not found)
* android: Don't use LimitedInputStream when reading entire file (optimization)
* [CB-6428](https://issues.apache.org/jira/browse/CB-6428) android: Add support for directory copies from assets -> filesystem
* android: Add `listChildren()`: Java-consumable version of `readEntriesAtLocalURL()`
* [CB-6428](https://issues.apache.org/jira/browse/CB-6428) android: Add support for file:///android_asset URLs
* [CB-8642](https://issues.apache.org/jira/browse/CB-8642) android: Fix content URIs not working with resolve / copy
* Tweak tests to fail if deleteEntry fails (rather than time out)
* android: Ensure LocalFilesystemURL can only be created with "cdvfile" URLs
* android: Move CordovaResourceApi into Filesystem base class
* android: Use `CordovaResourceApi.mapUriToFile()` rather than own custom logic in ContentFilesystem
* android: Use Uri.parse rather than manual parsing in resolveLocalFileSystemURI
* Tweak test case that failed twice on error rather than just once
* android: Delete invalid JavaDoc (lint errors)
* android: Use CordovaResourceApi rather than FileHelper
* [CB-8032](https://issues.apache.org/jira/browse/CB-8032) - File Plugin - Add nativeURL external method support for CDVFileSystem->makeEntryForPath:isDirectory: (closes #96)
* [CB-8567](https://issues.apache.org/jira/browse/CB-8567) Integrate TravisCI
* [CB-8438](https://issues.apache.org/jira/browse/CB-8438) cordova-plugin-file documentation translation: cordova-plugin-file
* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file
* [CB-7956](https://issues.apache.org/jira/browse/CB-7956) Add cordova-plugin-file support for browser platform
* [CB-8423](https://issues.apache.org/jira/browse/CB-8423) Corrected usage of done() in async tests
* [CB-8459](https://issues.apache.org/jira/browse/CB-8459) Fixes spec 111 failure due to incorrect relative paths handling
* Code cleanup, whitespace
* Added nativeURL property to FileEntry, implemented readAsArrayBuffer and readAsBinaryString
### 1.3.3 (Feb 04, 2015)
* [CB-7927](https://issues.apache.org/jira/browse/CB-7927) Encoding data to bytes instead of chars when writing a file.
* ios: Fix compile warning about implicit int conversion
* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use base64EncodedStringWithOptions instead of CordovaLib's class extension
* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use argumentForIndex rather than NSArray extension
* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use a local copy of valueForKeyIsNumber rather than CordovaLib's version
* windows: Handle url's containing absolute windows path starting with drive letter and colon (encoded as %3A) through root FS
* windows: Rework to use normal url form
* android: refactor: Make Filesystem base class store its own name, rootUri, and rootEntry
* android: Simplify code a bit by making makeEntryForPath not throw JSONException
* [CB-6431](https://issues.apache.org/jira/browse/CB-6431) android: Fix plugin breaking content: URLs
* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) Never create new FileSystem instances (except on windows since they don't implement requestAllFileSystems())
### 1.3.2 (Dec 02, 2014)
* Gets rid of thread block error in File plugin
* [CB-7917](https://issues.apache.org/jira/browse/CB-7917) Made tests file.spec.114 - 116 pass for **Windows** platform
* [CB-7977](https://issues.apache.org/jira/browse/CB-7977) Mention `deviceready` in plugin docs
* [CB-7602](https://issues.apache.org/jira/browse/CB-7602): Fix `isCopyOnItself` logic
* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-file documentation translation: cordova-plugin-file
* Use one proxy for both **Windows** and **Windows8** platforms
* [CB-6994](https://issues.apache.org/jira/browse/CB-6994) Fixes result, returned by proxy's write method
* [fxos] update `__format__` to match `pathsPrefix`
* [CB-6994](https://issues.apache.org/jira/browse/CB-6994) Improves merged code to be able to write a File
* Optimize `FileProxy` for **Windows** platforms
* Synchronize changes with **Windows** platform
* Fix function write for big files on **Windows 8**
* Write file in background
* [CB-7487](https://issues.apache.org/jira/browse/CB-7487) **Android** Broadcast file write This allows MTP USB shares to show the file immediately without reboot/manual refresh using 3rd party app.
* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-file documentation translation: cordova-plugin-file
* [CB-7571](https://issues.apache.org/jira/browse/CB-7571) Bump version of nested plugin to match parent plugin
### 1.3.1 (Sep 17, 2014)
* [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-file documentation translation
* [CB-7272](https://issues.apache.org/jira/browse/CB-7272) Replace confusing "r/o" abbreviation with just "r"
* [CB-7423](https://issues.apache.org/jira/browse/CB-7423) encode path before attempting to resolve
* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) Fix the filesystem name in resolveLocalFileSystemUri
* [CB-7445](https://issues.apache.org/jira/browse/CB-7445) [BlackBerry10] resolveLocalFileSystemURI - change DEFAULT_SIZE to MAX_SIZE
* [CB-7458](https://issues.apache.org/jira/browse/CB-7458) [BlackBerry10] resolveLocalFileSystemURL - add filesystem property
* [CB-7445](https://issues.apache.org/jira/browse/CB-7445) [BlackBerry10] Add default file system size to prevent quota exceeded error on initial install
* [CB-7431](https://issues.apache.org/jira/browse/CB-7431) Avoid calling done() twice in file.spec.109 test
* [CB-7413](https://issues.apache.org/jira/browse/CB-7413) Adds support of 'ms-appdata://' URIs
* [CB-7422](https://issues.apache.org/jira/browse/CB-7422) [File Tests] Use proper fileSystem to create fullPath
* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) [Entry] get proper filesystem in Entry
* Amazon related changes.
* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) Remove leading slash statement from condition
* Refactored much of the logic in FileMetadata constructor. Directory.size will return 0
* [CB-7419](https://issues.apache.org/jira/browse/CB-7419) [WP8] Added support to get metada from dir
* [CB-7418](https://issues.apache.org/jira/browse/CB-7418) [DirectoryEntry] Added fullPath variable as part of condition
* [CB-7417](https://issues.apache.org/jira/browse/CB-7417) [File tests] added proper matcher to compare fullPath property
* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) Partial revert to resolve WP8 failures
* Overwrite existing file on getFile when create is true
* [CB-7375](https://issues.apache.org/jira/browse/CB-7375) [CB-6148](https://issues.apache.org/jira/browse/CB-6148): Ensure that return values from copy and move operations reference the correct filesystem
* [CB-6724](https://issues.apache.org/jira/browse/CB-6724) changed style detail on documentation
* Added new js files to amazon-fireos platform.
* Adds Windows platform
* Fixes multiple mobilespec tests errors
* Removed test/tests.js module from main plugin.xml
* [CB-7094](https://issues.apache.org/jira/browse/CB-7094) renamed folder to tests + added nested plugin.xml
* added documentation for manual tests
* [CB-6923](https://issues.apache.org/jira/browse/CB-6923) Adding support to handle relative paths
* Style improvements on Manual tests
* [CB-7094](https://issues.apache.org/jira/browse/CB-7094) Ported File manual tests
### 1.3.0 (Aug 06, 2014)
* **FFOS** Remove unsupported paths from requestAllPaths
* **FFOS** Support for resolve URI, request all paths and local app directory.
* [CB-4263](https://issues.apache.org/jira/browse/CB-4263) set ready state to done before onload
* [CB-7167](https://issues.apache.org/jira/browse/CB-7167) [BlackBerry10] copyTo - return wrapped entry rather than native
* [CB-7167](https://issues.apache.org/jira/browse/CB-7167) [BlackBerry10] Add directory support to getFileMetadata
* [CB-7167](https://issues.apache.org/jira/browse/CB-7167) [BlackBerry10] Fix tests detection of blob support (window.Blob is BlobConstructor object)
* [CB-7161](https://issues.apache.org/jira/browse/CB-7161) [BlackBerry10] Add file system directory paths
* [CB-7093](https://issues.apache.org/jira/browse/CB-7093) Create separate plugin.xml for new-style tests
* [CB-7057](https://issues.apache.org/jira/browse/CB-7057) Docs update: elaborate on what directories are for
* [CB-7093](https://issues.apache.org/jira/browse/CB-7093): Undo the effects of an old bad S&R command
* [CB-7093](https://issues.apache.org/jira/browse/CB-7093): Remove a bunch of unneeded log messages
* [CB-7093](https://issues.apache.org/jira/browse/CB-7093): Add JS module to plugin.xml file for auto-tests
* [CB-7093](https://issues.apache.org/jira/browse/CB-7093) Ported automated file tests
* **WINDOWS** remove extra function closure, not needed
* **WINDOWS** remove check for undefined fail(), it is defined by the proxy and always exists
* **WINDOWS** re-apply readAsBinaryString and readAsArrayBuffer
* **WINDOWS** Moved similar calls to be the same calls, aliased long namespaced functions
* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs.
* [CB-6571](https://issues.apache.org/jira/browse/CB-6571) Fix getParentForLocalURL to work correctly with directories with trailing '/' (This closes #58)
* UTTypeCopyPreferredTagWithClass returns nil mimetype for css when there is no network
* updated spec links in docs ( en only )
* [CB-6571](https://issues.apache.org/jira/browse/CB-6571) add trailing space it is missing in DirectoryEnty constructor.
* [CB-6980](https://issues.apache.org/jira/browse/CB-6980) Fixing filesystem:null property in Entry
* Add win8 support for readAsBinaryString and readAsArrayBuffer
* [FFOS] Update FileProxy.js
* [CB-6940](https://issues.apache.org/jira/browse/CB-6940): Fixing up commit from dzeims
* [CB-6940](https://issues.apache.org/jira/browse/CB-6940): Android: cleanup try/catch exception handling
* [CB-6940](https://issues.apache.org/jira/browse/CB-6940): `context.getExternal*` methods return null if sdcard isn't in mounted state, causing exceptions that prevent startup from reaching readystate
* Fix mis-handling of filesystem reference in Entry.moveTo ('this' used in closure).
* [CB-6902](https://issues.apache.org/jira/browse/CB-6902): Use File.lastModified rather than .lastModifiedDate
* [CB-6922](https://issues.apache.org/jira/browse/CB-6922): Remove unused getMetadata native code
* [CB-6922](https://issues.apache.org/jira/browse/CB-6922): Use getFileMetadata consistently to get metadata
* changed fullPath to self.rootDocsPath
* [CB-6890](https://issues.apache.org/jira/browse/CB-6890): Fix pluginManager access for 4.0.x branch
### 1.2.1
* [CB-6922](https://issues.apache.org/jira/browse/CB-6922) Fix inconsistent handling of lastModifiedDate and modificationTime
* [CB-285](https://issues.apache.org/jira/browse/CB-285): Document filesystem root properties
### 1.2.0 (Jun 05, 2014)
* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Spanish and French Translations added. Github close #31
* updated this reference to window
* Add missing semicolon (copy & paste error)
* Fix compiler warning about symbol in interface not matching implementation
* Fix sorting order in supported platforms
* ubuntu: increase quota value
* ubuntu: Change FS URL scheme to 'cdvfile'
* ubuntu: Return size with Entry.getMetadata() method
* [CB-6803](https://issues.apache.org/jira/browse/CB-6803) Add license
* Initial implementation for Firefox OS
* Small wording tweaks
* Fixed toURL() toInternalURL() information in the doku
* ios: Don't fail a write of zero-length payload.
* [CB-285](https://issues.apache.org/jira/browse/CB-285) Docs for cordova.file.\*Directory properties
* [CB-285](https://issues.apache.org/jira/browse/CB-285) Add cordova.file.\*Directory properties for iOS & Android
* [CB-3440](https://issues.apache.org/jira/browse/CB-3440) [BlackBerry10] Proxy based implementation
* Fix typo in docs "app-bundle" -> "bundle"
* [CB-6583](https://issues.apache.org/jira/browse/CB-6583) ios: Fix failing to create entry when space in parent path
* [CB-6571](https://issues.apache.org/jira/browse/CB-6571) android: Make DirectoryEntry.toURL() have a trailing /
* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md
* [CB-6525](https://issues.apache.org/jira/browse/CB-6525) android, ios: Allow file: URLs in all APIs. Fixes FileTransfer.download not being called.
* fix the Windows 8 implementation of the getFile method
* Update File.js for typo: lastModifiedData --> lastModifiedDate (closes #38)
* Add error codes.
* [CB-5980](https://issues.apache.org/jira/browse/CB-5980) Updated version and RELEASENOTES.md for release 1.0.0
* Add NOTICE file
* [CB-6114](https://issues.apache.org/jira/browse/CB-6114) Updated version and RELEASENOTES.md for release 1.0.1
* [CB-5980](https://issues.apache.org/jira/browse/CB-5980) Updated version and RELEASENOTES.md for release 1.0.0
### 1.1.0 (Apr 17, 2014)
* [CB-4965](https://issues.apache.org/jira/browse/CB-4965): Remove tests from file plugin
* Android: Allow file:/ URLs
* [CB-6422](https://issues.apache.org/jira/browse/CB-6422): [windows8] use cordova/exec/proxy
* [CB-6249](https://issues.apache.org/jira/browse/CB-6249): [android] Opportunistically resolve content urls to file
* [CB-6394](https://issues.apache.org/jira/browse/CB-6394): [ios, android] Add extra filesystem roots
* [CB-6394](https://issues.apache.org/jira/browse/CB-6394): [ios, android] Fix file resolution for the device root case
* [CB-6394](https://issues.apache.org/jira/browse/CB-6394): [ios] Return ENCODING_ERR when fs name is not valid
* [CB-6393](https://issues.apache.org/jira/browse/CB-6393): Change behaviour of toURL and toNativeURL
* ios: Style: plugin initialization
* ios: Fix handling of file URLs with encoded spaces
* Always use Android's recommended temp file location for temporary file system
* [CB-6352](https://issues.apache.org/jira/browse/CB-6352): Allow FileSystem objects to be serialized to JSON
* [CB-5959](https://issues.apache.org/jira/browse/CB-5959): size is explicitly 0 if not set, file.spec.46&47 are testing the type of size
* [CB-6242](https://issues.apache.org/jira/browse/CB-6242): [BlackBerry10] Add deprecated version of resolveLocalFileSystemURI
* [CB-6242](https://issues.apache.org/jira/browse/CB-6242): [BlackBerry10] add file:/// prefix for toURI / toURL
* [CB-6242](https://issues.apache.org/jira/browse/CB-6242): [BlackBerry10] Polyfill window.requestAnimationFrame for OS < 10.2
* [CB-6242](https://issues.apache.org/jira/browse/CB-6242): [BlackBerry10] Override window.resolveLocalFileSystemURL
* [CB-6212](https://issues.apache.org/jira/browse/CB-6212): [iOS] fix warnings compiled under arm64 64-bit
* ios: Don't cache responses from CDVFile's URLProtocol
* [CB-6199](https://issues.apache.org/jira/browse/CB-6199): [iOS] Fix toNativeURL() not escaping characters properly
* [CB-6148](https://issues.apache.org/jira/browse/CB-6148): Fix cross-filesystem copy and move
* fixed setMetadata() to use the formatted fullPath
* corrected typo which leads to a "comma expression"
* [CB-4952](https://issues.apache.org/jira/browse/CB-4952): ios: Resolve symlinks in file:// URLs
* Add docs about the extraFileSystems preference
* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers
### 1.0.1 (Feb 28, 2014)
* [CB-6116](https://issues.apache.org/jira/browse/CB-6116) Fix error where resolveLocalFileSystemURL would fail
* [CB-6106](https://issues.apache.org/jira/browse/CB-6106) Add support for nativeURL attribute on Entry objects
* [CB-6110](https://issues.apache.org/jira/browse/CB-6110) iOS: Fix typo in filesystemPathForURL: method
* Android: Use most specific FS match when resolving file: URIs
* iOS: Update fileSystemURLforLocalPath: to return the most match url.
* Allow third-party plugin registration, and the total count of fs type is not limited to just 4.
* [CB-6097](https://issues.apache.org/jira/browse/CB-6097) Added missing files for amazon-fireos platform. Added onLoad flag to true.
* [CB-6087](https://issues.apache.org/jira/browse/CB-6087) Android, iOS: Load file plugin on startup
* [CB-6013](https://issues.apache.org/jira/browse/CB-6013) BlackBerry10: wrap webkit prefixed called in requestAnimationFrame
* Update plugin writers' documentation
* [CB-6080](https://issues.apache.org/jira/browse/CB-6080) Fix file copy when src and dst are on different local file systems
* [CB-6057](https://issues.apache.org/jira/browse/CB-6057) Add methods for plugins to convert between URLs and paths
* [CB-6050](https://issues.apache.org/jira/browse/CB-6050) Public method for returning a FileEntry from a device file path
* [CB-2432](https://issues.apache.org/jira/browse/CB-2432) [CB-3185](https://issues.apache.org/jira/browse/CB-3185), [CB-5975](https://issues.apache.org/jira/browse/CB-5975): Fix Android handling of content:// URLs
* [CB-6022](https://issues.apache.org/jira/browse/CB-6022) Add upgrade notes to doc
* [CB-5233](https://issues.apache.org/jira/browse/CB-5233) Make asset-library urls work properly on iOS
* [CB-6012](https://issues.apache.org/jira/browse/CB-6012) Preserve query strings on cdvfile:// URLs where necessary
* [CB-6010](https://issues.apache.org/jira/browse/CB-6010) Test properly for presence of URLforFilesystemPath method
* [CB-5959](https://issues.apache.org/jira/browse/CB-5959) Entry.getMetadata should return size attribute
### 1.0.0 (Feb 05, 2014)
* [CB-5974](https://issues.apache.org/jira/browse/CB-5974): Use safe 'Compatibilty' mode by default
* [CB-5915](https://issues.apache.org/jira/browse/CB-5915): [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Reorganize preference code to make defaults possible
* [CB-5974](https://issues.apache.org/jira/browse/CB-5974): Android: Don't allow File operations to continue when not configured
* [CB-5960](https://issues.apache.org/jira/browse/CB-5960): ios: android: Properly handle parent references in getFile/getDirectory
* [ubuntu] adopt to recent changes
* Add default FS root to new FS objects
* [CB-5899](https://issues.apache.org/jira/browse/CB-5899): Make DirectoryReader.readEntries return properly formatted Entry objects
* Add constuctor params to FileUploadResult related to [CB-2421](https://issues.apache.org/jira/browse/CB-2421)
* Fill out filesystem attribute of entities returned from resolveLocalFileSystemURL
* [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Create documents directories if they don't exist
* [CB-5915](https://issues.apache.org/jira/browse/CB-5915): Create documents directories if they don't exist
* [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Android: Fix unfortunate NPE in config check
* [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Android: Add "/files/" to persistent files path
* [CB-5915](https://issues.apache.org/jira/browse/CB-5915): ios: Update config preference (and docs) to match issue
* [CB-5916](https://issues.apache.org/jira/browse/CB-5916): Android: Add config preference for Android persistent storage location
* iOS: Add config preference for iOS persistent storage location
* iOS: Android: Allow third-party plugin registration
* Android: Expose filePlugin getter so that other plugins can register filesystems
* Fix typos in deprecation message
* Add backwards-compatibility shim for file-transfer
* Android: Allow third-party plugin registration
* [CB-5810](https://issues.apache.org/jira/browse/CB-5810) [BlackBerry10] resolve local:/// paths (application assets)
* [CB-5774](https://issues.apache.org/jira/browse/CB-5774): create DirectoryEntry instead of FileEntry
* Initial fix for [CB-5747](https://issues.apache.org/jira/browse/CB-5747)
* Change default FS URL scheme to "cdvfile"
* Android: Properly format content urls
* Android, iOS: Replace "filesystem" protocol string with constant
* Android: Allow absolute paths on Entry.getFile / Entry.getDirectory
* Android: Make clear that getFile takes a path, not just a filename
* [CB-5008](https://issues.apache.org/jira/browse/CB-5008): Rename resolveLocalFileSystemURI to resolveLocalFileSystemURL; deprecate original
* Remove old file reference from plugin.xml
* Android: Refactor File API
* [CB-4899](https://issues.apache.org/jira/browse/CB-4899) [BlackBerry10] Fix resolve directories
* [CB-5602](https://issues.apache.org/jira/browse/CB-5602) Windows8. Fix File Api mobile spec tests
* Android: Better support for content urls and cross-filesystem copy/move ops
* [CB-5699](https://issues.apache.org/jira/browse/CB-5699) [BlackBerry10] Update resolveLocalFileSystemURI implementation
* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Update license comment formatting of doc/index.md
* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Add doc.index.md for File plugin.
* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Delete stale snapshot of plugin docs
* [CB-5403](https://issues.apache.org/jira/browse/CB-5403): Backwards-compatibility with file:// urls where possible
* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Fixes for ContentFilesystem
* Android: Add method for testing backwards-compatibility of filetransfer plugin
* iOS: Add method for testing backwards-compatiblity of filetransfer plugin
* Android: Updates to allow FileTransfer to continue to work
* Android: Clean up unclosed file objects
* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Cleanup
* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Add new Android source files to plugin.xml
* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move read, write and truncate methods into modules
* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move copy/move methods into FS modules
* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move getParent into FS modules
* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move getmetadata methods into FS modules
* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move readdir methods into FS modules
* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move remove methods into FS modules
* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Move getFile into FS modules
* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Start refactoring android code: Modular filesystems, rfs, rlfsurl
* [CB-5407](https://issues.apache.org/jira/browse/CB-5407): Update android JS to use FS urls
* [CB-5405](https://issues.apache.org/jira/browse/CB-5405): Use URL formatting for Entry.toURL
* [CB-5532](https://issues.apache.org/jira/browse/CB-5532) Fix
* Log file path for File exceptions.
* Partial fix for iOS File compatibility with previous fileTransfer plugin
* [CB-5532](https://issues.apache.org/jira/browse/CB-5532) WP8. Add binary data support to FileWriter
* [CB-5531](https://issues.apache.org/jira/browse/CB-5531) WP8. File Api readAsText incorrectly handles position args
* Added ubuntu platform support
* Added amazon-fireos platform support
* [CB-5118](https://issues.apache.org/jira/browse/CB-5118) [BlackBerry10] Add check for undefined error handler
* [CB-5406](https://issues.apache.org/jira/browse/CB-5406): Extend public API for dependent plugins
* [CB-5403](https://issues.apache.org/jira/browse/CB-5403): Bump File plugin major version
* [CB-5406](https://issues.apache.org/jira/browse/CB-5406): Split iOS file plugin into modules
* [CB-5406](https://issues.apache.org/jira/browse/CB-5406): Factor out filesystem providers in iOS
* [CB-5408](https://issues.apache.org/jira/browse/CB-5408): Add handler for filesystem:// urls
* [CB-5406](https://issues.apache.org/jira/browse/CB-5406): Update iOS native code to use filesystem URLs internally
* [CB-5405](https://issues.apache.org/jira/browse/CB-5405): Update JS code to use URLs exclusively
* [CB-4816](https://issues.apache.org/jira/browse/CB-4816) Fix file creation outside sandbox for BB10
### 0.2.5 (Oct 28, 2013)
* [CB-5129](https://issues.apache.org/jira/browse/CB-5129): Add a consistent filesystem attribute to FileEntry and DirectoryEntry objects
* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): added repo + issue tag to plugin.xml for file plugin
* [CB-5015](https://issues.apache.org/jira/browse/CB-5015) [BlackBerry10] Add missing dependency for File.slice
* [CB-5010](https://issues.apache.org/jira/browse/CB-5010) Incremented plugin version on dev branch.
### 0.2.4 (Oct 9, 2013)
* [CB-5020](https://issues.apache.org/jira/browse/CB-5020) - File plugin should execute on a separate thread
* [CB-4915](https://issues.apache.org/jira/browse/CB-4915) Incremented plugin version on dev branch.
* [CB-4504](https://issues.apache.org/jira/browse/CB-4504): Updating FileUtils.java to compensate for Java porting failures in the Android SDK. This fails because Java knows nothing about android_asset not being an actual filesystem
### 0.2.3 (Sept 25, 2013)
* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) bumping&resetting version
* [CB-4903](https://issues.apache.org/jira/browse/CB-4903) File Plugin not loading Windows8
* [CB-4903](https://issues.apache.org/jira/browse/CB-4903) File Plugin not loading Windows8
* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming references
* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.file to org.apache.cordova.file
* Rename CHANGELOG.md -> RELEASENOTES.md
* [CB-4771](https://issues.apache.org/jira/browse/CB-4771) Expose TEMPORARY and PERSISTENT constants on window.
* Fix compiler/lint warnings
* [CB-4764](https://issues.apache.org/jira/browse/CB-4764) Move DirectoryManager.java into file plugin
* [CB-4763](https://issues.apache.org/jira/browse/CB-4763) Copy FileHelper.java into the plugin.
* [CB-2901](https://issues.apache.org/jira/browse/CB-2901) [BlackBerry10] Automatically unsandbox filesystem if path is not in app sandbox
* [CB-4752](https://issues.apache.org/jira/browse/CB-4752) Incremented plugin version on dev branch.
### 0.2.1 (Sept 5, 2013)
* [CB-4656](https://issues.apache.org/jira/browse/CB-4656) Don't add newlines in data urls within readAsDataUrl.
* [CB-4514](https://issues.apache.org/jira/browse/CB-4514) Making DirectoryCopy Recursive
* [iOS] Simplify the code in resolveLocalFileSystemURI

View File

@@ -0,0 +1,335 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-file
[![Build Status](https://travis-ci.org/apache/cordova-plugin-file.svg)](https://travis-ci.org/apache/cordova-plugin-file)
Dieses Plugin implementiert eine File-API, die Lese-/Schreibzugriff Zugriff auf Dateien, die auf dem Gerät befinden.
Dieses Plugin basiert auf mehrere Angaben, einschließlich: die HTML5-File-API <http://www.w3.org/TR/FileAPI/>
Die (heute nicht mehr existierenden) Verzeichnisse und System neuesten Erweiterungen: <http://www.w3.org/TR/2012/WD-file-system-api-20120417/> , obwohl die meisten von den Plugin-Code wurde geschrieben, als eine frühere Spec aktuell waren: <http://www.w3.org/TR/2011/WD-file-system-api-20110419/>
Es implementiert auch die FileWriter Spec: <http://dev.w3.org/2009/dap/file-system/file-writer.html>
Verwendung finden Sie in HTML5 Rocks ausgezeichnete [Dateisystem Artikel.](http://www.html5rocks.com/en/tutorials/file/filesystem/)
Finden Sie einen Überblick über andere Speicheroptionen Cordovas [Speicher-Führer](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html).
Dieses Plugin wird global `cordova.file`-Objekt definiert.
Obwohl im globalen Gültigkeitsbereich, steht es nicht bis nach dem `deviceready`-Ereignis.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(cordova.file);
}
## Installation
cordova plugin add cordova-plugin-file
## Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows Phone 7 und 8 *
* Windows 8 *
* Windows*
* Browser
\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.*
## Wo Dateien gespeichert
Stand: V1 werden URLs auf wichtige Datei-System-Verzeichnisse zur Verfügung gestellt. Jede URL in der Form *file:///path/to/spot/* ist, und ein `DirectoryEntry` mit `window.resolveLocalFileSystemURL()` konvertiert werden können.
* `cordova.file.applicationDirectory`-Die schreibgeschützten Verzeichnis, in dem die Anwendung installiert ist. (*iOS*, *Android*, *BlackBerry 10*)
* `cordova.file.applicationStorageDirectory`-Root-Verzeichnis der Anwendungs-Sandbox; auf iOS ist schreibgeschützt (aber bestimmte Unterverzeichnisse [wie `/Documents` ] sind Lese-und Schreibzugriff). Alle enthaltene Daten ist für die app privat. ( *iOS*, *Android*, *BlackBerry 10*)
* `cordova.file.dataDirectory`-Beständige und private Datenspeicherung innerhalb der Anwendungs-Sandbox, die mit internen Speicher (auf Android, externen Speicher verwenden, verwenden Sie `.externalDataDirectory` ). Auf iOS, ist dieses Verzeichnis nicht mit iCloud synchronisiert (verwenden Sie `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
* `cordova.file.cacheDirectory`-Verzeichnis der zwischengespeicherten Daten-Dateien oder Dateien, die Ihre app einfach neu erstellen können. Das Betriebssystem kann diese Dateien löschen, wenn das Gerät auf Speicher knapp wird, dennoch sollten die apps vom Betriebssystem zum Löschen von Dateien hier nicht verlassen. (*iOS*, *Android*, *BlackBerry 10*)
* `cordova.file.externalApplicationStorageDirectory`-Anwendungsraum auf externen Speicher. (*Android*)
* `cordova.file.externalDataDirectory`-Wo, app-spezifische Datendateien auf externen Speicher setzen. (*Android*)
* `cordova.file.externalCacheDirectory`-Anwendungscache auf externen Speicher. (*Android*)
* `cordova.file.externalRootDirectory`-Externer Speicher (SD-Karte) Stamm. (*Android*, *BlackBerry 10*)
* `cordova.file.tempDirectory`-Temp-Verzeichnis, dem das OS auf deaktivieren können wird. Verlassen Sie sich nicht auf das Betriebssystem, um dieses Verzeichnis zu löschen; Ihre Anwendung sollte immer Dateien gegebenenfalls entfernen. (*iOS*)
* `cordova.file.syncedDataDirectory`-Hält app-spezifische Dateien, die (z. B. auf iCloud) synchronisiert werden sollten. (*iOS*)
* `cordova.file.documentsDirectory`-Dateien für die app, aber privat sind sinnvoll, andere Anwendungen (z.B. Office-Dateien). (*iOS*)
* `cordova.file.sharedDirectory`-Dateien für alle Anwendungen (*BlackBerry 10* weltweit verfügbar)
## Dateisystemlayouts
Obwohl technisch ein Implementierungsdetail, kann es sehr hilfreich zu wissen, wie die `cordova.file.*`-Eigenschaften physikalische Pfade auf einem echten Gerät zugeordnet sein.
### iOS-Datei-System-Layout
| Gerätepfad | `Cordova.file.*` | `iosExtraFileSystems` | R/w? | persistent? | OS löscht | Sync | Private |
|:---------------------------------------------- |:--------------------------- |:--------------------- |:----:|:-----------:|:------------:|:----:|:-------:|
| `/ Var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Ja |
| &nbsp;&nbsp;&nbsp;`appname.app/` | applicationDirectory | Bundle | r | N/A | N/A | N/A | Ja |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`www/` | - | - | r | N/A | N/A | N/A | Ja |
| &nbsp;&nbsp;&nbsp;`Documents/` | documentsDirectory | Dokumente | R/w | Ja | Nein | Ja | Ja |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`NoCloud/` | - | Dokumente-nosync | R/w | Ja | Nein | Nein | Ja |
| &nbsp;&nbsp;&nbsp;`Library` | - | Bibliothek | R/w | Ja | Nein | Ja? | Ja |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`NoCloud/` | dataDirectory | Bibliothek-nosync | R/w | Ja | Nein | Nein | Ja |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Cloud/` | syncedDataDirectory | - | R/w | Ja | Nein | Ja | Ja |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Caches/` | cacheDirectory | Cache | R/w | Ja * | Ja**\* | Nein | Ja |
| &nbsp;&nbsp;&nbsp;`tmp/` | tempDirectory | - | R/w | Nein** | Ja**\* | Nein | Ja |
\ * Dateien über app-Neustarts und Upgrades beibehalten, aber dieses Verzeichnis kann gelöscht werden, wenn das OS begehrt. Ihre Anwendung sollte in der Lage, alle Inhalte neu zu erstellen, die gelöscht werden können.
** -Dateien kann über app-Neustarts beizubehalten, aber verlasse dich nicht auf dieses Verhalten. Dateien sind nicht unbedingt Aktuelles beibehalten. Ihre Anwendung sollte Dateien aus diesem Verzeichnis entfernen, wenn es gilt, diese Dateien werden entfernt, da das OS nicht wann (oder auch wenn) garantiert.
**\ * The OS kann den Inhalt dieses Verzeichnisses löschen, wann immer es sich anfühlt, ist es erforderlich, aber verlassen Sie sich nicht dazu. Sie sollten dieses Verzeichnis entsprechend Ihrer Anwendung deaktivieren.
### Android File System-Layout
| Gerätepfad | `Cordova.file.*` | `AndroidExtraFileSystems` | R/w? | persistent? | OS löscht | Private |
|:------------------------------------------------ |:----------------------------------- |:------------------------- |:----:|:-----------:|:----------:|:-------:|
| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | Ja |
| `/ Data/Data/< app-Id > /` | applicationStorageDirectory | - | R/w | N/A | N/A | Ja |
| &nbsp;&nbsp;&nbsp;`cache` | cacheDirectory | Cache | R/w | Ja | Ja\* | Ja |
| &nbsp;&nbsp;&nbsp;`files` | dataDirectory | Dateien | R/w | Ja | Nein | Ja |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Documents` | | Dokumente | R/w | Ja | Nein | Ja |
| `< Sdcard > /` | externalRootDirectory | sdcard | R/w | Ja | Nein | Nein |
| &nbsp;&nbsp;&nbsp;`Android/data/<app-id>/` | externalApplicationStorageDirectory | - | R/w | Ja | Nein | Nein |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`cache` | externalCacheDirectry | Cache-extern | R/w | Ja | Nein** | Nein |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`files` | externalDataDirectory | Dateien-extern | R/w | Ja | Nein | Nein |
\ * OS kann regelmäßig dieses Verzeichnis zu löschen, aber verlasse dich nicht auf dieses Verhalten. Deaktivieren Sie den Inhalt dieses Verzeichnisses für Ihre Anwendung geeigneten. Ein Benutzer den Cache manuell löschen sollte, werden die Inhalte dieses Verzeichnisses entfernt.
** Der OS nicht klar dieses Verzeichnis automatisch; Sie sind verantwortlich für die Inhalte selbst verwalten. Der Benutzer den Cache manuell löschen sollte, werden der Inhalt des Verzeichnisses entfernt.
**Hinweis**: Wenn externe Speichergeräte nicht bereitgestellt werden kann, sind die `cordova.file.external*` Eigenschaften `null`.
### BlackBerry 10-File-System-Layout
| Gerätepfad | `Cordova.file.*` | R/w? | persistent? | OS löscht | Private |
|:----------------------------------------------------------- |:--------------------------- |:----:|:-----------:|:---------:|:-------:|
| `file:///Accounts/1000/APPDATA/ < app Id > /` | applicationStorageDirectory | r | N/A | N/A | Ja |
| &nbsp;&nbsp;&nbsp;`app/native` | applicationDirectory | r | N/A | N/A | Ja |
| &nbsp;&nbsp;&nbsp;`data/webviews/webfs/temporary/local__0` | cacheDirectory | R/w | Nein | Ja | Ja |
| &nbsp;&nbsp;&nbsp;`data/webviews/webfs/persistent/local__0` | dataDirectory | R/w | Ja | Nein | Ja |
| `file:///Accounts/1000/Removable/sdcard` | externalRemovableDirectory | R/w | Ja | Nein | Nein |
| `file:///Accounts/1000/Shared` | sharedDirectory | R/w | Ja | Nein | Nein |
*Hinweis*: Wenn die Anwendung bereitgestellt wird, um Perimeter zu arbeiten, alle Pfade sind relativ /accounts/1000-enterprise.
## Android Eigenarten
### Android permanenten Speicherort
Es gibt mehrere gültige Speicherorte, persistente Dateien auf einem Android-Gerät zu speichern. Finden Sie auf [dieser Seite](http://developer.android.com/guide/topics/data/data-storage.html) eine ausführliche Diskussion über die verschiedenen Möglichkeiten.
Frühere Versionen des Plugins wählen würde, den Speicherort der temporären und permanenten Dateien beim Start, basierend auf, ob das Gerät behauptete, dass die SD-Karte (oder gleichwertige Speicherpartition) bereitgestellt wurde. Wenn die SD-Karte eingelegt wurde, oder wenn eine große interne Speicherpartition verfügbar war (wie auf Nexus-Geräten) und dann in die Wurzel dieses Raumes, die persistenten Dateien gespeichert werden. Dies bedeutete, dass alle Cordova apps aller verfügbaren Dateien auf der Karte sehen konnte.
Wenn die SD-Karte nicht verfügbar war, dann Vorgängerversionen Daten unter speichern würde `/data/data/<packageId>`, die isoliert Anwendungen voneinander, aber möglicherweise noch Ursache Daten zwischen Benutzern freigegeben werden.
Es ist jetzt möglich, ob Sie Dateien der internen Datei-Speicherort oder unter Verwendung der bisherigen Logik, mit einer Präferenz in der Anwendung-`config.xml`-Datei speichern möchten. Hierzu fügen Sie eine dieser zwei Zeilen zu `"config.xml"`:
<preference name="AndroidPersistentFileLocation" value="Internal" />
<preference name="AndroidPersistentFileLocation" value="Compatibility" />
Ohne diese Zeile wird das Datei Plugin `Compatibility` als Standard verwenden. Wenn ein Präferenz-Tag vorhanden ist, und nicht einen der folgenden Werte, wird die Anwendung nicht gestartet.
Wenn Ihre Anwendung für Benutzer zuvor versandt wird, mithilfe eines älteren (Pre-1.0) Version dieses Plugins und gespeicherte Dateien im permanenten Dateisystem hat, dann sollten Sie die Einstellung zur `Compatibility` einstellen. Wechseln die Location auf "Internal" würde bedeuten, dass Benutzer, die aktualisieren Sie ihre Anwendung, möglicherweise nicht auf ihre zuvor gespeicherte Dateien, abhängig von ihrem Gerät zugreifen.
Wenn Ihre Anwendung neu ist, oder nie zuvor Dateien im Dateisystem persistent gespeichert hat, wird die `Internal` Einstellung in der Regel empfohlen.
### Langsame rekursive Operationen für /android_asset
Auflisten von Verzeichnissen Vermögenswert ist wirklich langsam auf Android. Sie können beschleunigen, es oben aber durch `src/android/build-extras.gradle` in das Stammverzeichnis von Ihrem android Projekt hinzufügen (erfordert auch cordova-android@4.0.0 oder größer).
## iOS Macken
* `cordova.file.applicationStorageDirectory`ist schreibgeschützt; zum Speichern von Dateien im Stammverzeichnis der Versuch schlägt fehl. Verwenden Sie eine der anderen `cordova.file.*` für iOS definierten Eigenschaften (nur `applicationDirectory` und `applicationStorageDirectory` sind schreibgeschützt).
* `FileReader.readAsText(blob, encoding)`
* Die `encoding` Parameter wird nicht unterstützt und UTF-8-Kodierung ist immer wirksam.
### iOS permanenten Speicherort
Es gibt zwei gültige Speicherorte persistente Dateien auf ein iOS-Gerät speichern: das Dokumenten-Verzeichnis und das Verzeichnis Library. Frühere Versionen des Plugins gespeichert immer nur persistente Dateien im Verzeichnis Dokumente. Dies hatte den Nebeneffekt einer Anwendung Dateien in iTunes, die oft unbeabsichtigte, speziell für Anwendungen, die viele kleine Dateien behandeln war, sichtbar zu machen, anstatt komplette Dokumente für den Export, die den beabsichtigten Zweck des Verzeichnisses ist zu produzieren.
Es ist jetzt möglich, ob Sie Dateien in Dokumente oder Verzeichnis Library mit einer Präferenz in der Anwendung-`config.xml`-Datei speichern möchten. Hierzu fügen Sie eine dieser zwei Zeilen zu `"config.xml"`:
<preference name="iosPersistentFileLocation" value="Library" />
<preference name="iosPersistentFileLocation" value="Compatibility" />
Ohne diese Zeile wird das Datei Plugin `Compatibility` als Standard verwenden. Wenn ein Präferenz-Tag vorhanden ist, und nicht einen der folgenden Werte, wird die Anwendung nicht gestartet.
Wenn Ihre Anwendung für Benutzer zuvor versandt wird, mithilfe eines älteren (Pre-1.0) Version dieses Plugins und gespeicherte Dateien im permanenten Dateisystem hat, dann sollten Sie die Einstellung zur `Compatibility` einstellen. Standort zur `Library` wechseln würde bedeuten, dass Benutzer, die ihre Anwendung aktualisieren nicht in der Lage wäre, ihre zuvor gespeicherte Dateien zugreifen.
Wenn die Anwendung neu, oder nie zuvor Dateien im Dateisystem persistent gespeichert hat, wird die Einstellung der `Library` allgemein empfohlen.
## Firefox OS Macken
Der Datei-System-API wird von Firefox-OS nicht nativ unterstützt und wird als ein Shim auf IndexedDB implementiert.
* Schlägt nicht fehl, wenn Sie nicht leere Verzeichnisse entfernen
* Metadaten wird für Verzeichnisse nicht unterstützt.
* Methoden `copyTo` und `moveTo` unterstützen keine Verzeichnisse
Die folgenden Datenpfade werden unterstützt: * `applicationDirectory` - `xhr` verwendet, um lokale Dateien erhalten, die mit der app verpackt sind. *`dataDirectory` - für persistente app-spezifische Daten-Dateien. *`cacheDirectory` - Cache-Dateien, die app startet überleben sollte (Apps sollten nicht vom Betriebssystem zum Löschen von Dateien hier verlassen).
## Browser-Eigenheiten
### Gemeinsamen Macken und Bemerkungen
* Jeder Browser verwendet ein eigene Sandbox Dateisystem. IE und Firefox verwenden IndexedDB als Basis. Alle Browser verwenden Schrägstrich als Verzeichnistrennzeichen in einem Pfad.
* Directory-Einträge müssen nacheinander erstellt werden. Z. B. der Aufruf `fs.root.getDirectory ("dir1/Ordner2 ', {create:true}, SuccessCallback, ErrorCallback)` schlägt fehl, wenn dir1 nicht existierte.
* Das Plugin fordert Benutzer die Berechtigung zum permanenten Speicher beim ersten Start Anwendung verwenden.
* Plugin unterstützt `Cdvfile://localhost` (lokale Ressourcen) nur. D.h. externe Ressourcen nicht über `Cdvfile` unterstützt.
* Das Plugin folgt nicht ["File System API 8.3 Naming Einschränkungen"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions).
* BLOB und Datei "`close`-Funktion wird nicht unterstützt.
* `FileSaver` und `BlobBuilder` werden von diesem Plugin nicht unterstützt und müssen nicht geboren.
* Das Plugin unterstützt keine `RequestAllFileSystems`. Diese Funktion fehlt auch in den Spezifikationen.
* Einträge im Verzeichnis werden nicht entfernt werden, wenn Sie verwenden `create: true` Flag für vorhandenes Verzeichnis.
* Über Konstruktor erstellte Dateien werden nicht unterstützt. Sie sollten stattdessen die entry.file-Methode verwenden.
* Jeder Browser verwendet eine eigene Form für Blob-URL-Verweise.
* `readAsDataURL`-Funktion wird unterstützt, aber die Mediatype in Chrom hängt von der Eintrag Namenerweiterung, Mediatype im IE immer leer ist (das ist dasselbe wie `Text-Plain` gemäß der Spezifikation), Mediatype in Firefox ist immer `Application/Octet-Stream`. Beispielsweise, wenn der Inhalt `Abcdefg` gibt dann Firefox `Daten: Anwendung / Octet-Stream; base64, YWJjZGVmZw ==`, IE gibt `Daten:; base64, YWJjZGVmZw ==`, Chrom gibt `Daten: < Mediatype je nach Erweiterung des Eintragsnamens >; base64, YWJjZGVmZw ==`.
* `ToInternalURL` gibt den Pfad zurück, in der Form `file:///persistent/path/to/entry` (Firefox, IE). Chrom gibt den Pfad zurück, in der Form `cdvfile://localhost/persistent/file`.
### Chrom-Macken
* Chrom-Dateisystem ist nicht sofort nach Gerät bereit. Als Workaround können Sie `FilePluginIsReady`-Ereignis abonnieren. Beispiel:
```javascript
window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
```
`Window.isFilePluginReadyRaised`-Funktion können Sie überprüfen, ob Ereignis bereits ausgelöst wurde. -window.requestFileSystem temporär und PERSISTENTE Dateisystem-Quoten sind nicht begrenzt, in Chrom. -Um die dauerhafte Speicherung in Chrom zu erhöhen benötigen Sie `window.initPersistentFileSystem`-Methode aufrufen. Permanenter Speicherkontingent beträgt 5 MB standardmäßig. -Chrome erforderlich `--erlauben-Datei-Zugriff-aus-Files` Argument an den Support API via `file:///` Protokoll führen. -`Datei`-Objekt wird nicht geändert werden, wenn Sie Flag verwenden `{create:true}` als einen vorhandenen `Eintrag` zu erhalten. -Veranstaltungen `cancelable`-Eigenschaft festgelegt ist in Chrom wahr. Dies widerspricht der [Spezifikation](http://dev.w3.org/2009/dap/file-system/file-writer.html). -`toURL`-Funktion in Chrome zurück `Dateisystem:`-Pfad je nach Anwendungshost vorangestellt. Z. B. `filesystem:file:///persistent/somefile.txt`, `Filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` Funktionsergebnis enthält keine nachgestellten Schrägstrich bei Verzeichniseintrag. Chrom löst Verzeichnisse mit Schrägstrich-gezogene Urls aber korrekt. -`ResolveLocalFileSystemURL`-Methode erfordert die eingehenden `Url` `Dateisystem` Präfix haben. Beispielsweise sollte die `Url`-Parameter für `ResolveLocalFileSystemURL` in der Form `filesystem:file:///persistent/somefile.txt` im Gegensatz zu der Form `file:///persistent/somefile.txt` in Android. -Veraltete `ToNativeURL`-Funktion wird nicht unterstützt und muss keinen Stub. -`SetMetadata`-Funktion ist nicht in den Spezifikationen angegeben und nicht unterstützt. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, statt SYNTAX_ERR(code: 8) auf anfordern des Dateisystems nicht existent. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt PATH_EXISTS_ERR(code: 12) zu versuchen, die ausschließlich eine Datei oder ein Verzeichnis zu erstellen, die bereits vorhanden ist. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt NO_MODIFICATION_ALLOWED_ERR(code: 6) zu versuchen, rufen Sie RemoveRecursively auf das Root-Dateisystem. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt NOT_FOUND_ERR(code: 1) zu versuchen, MoveTo-Verzeichnis, das nicht vorhanden ist.
### Auf der Grundlage von IndexedDB Impl Macken (Firefox und IE)
* `.` und `.` werden nicht unterstützt.
* IE unterstützt keine `file:///`-Modus; nur der Modus für gehostete ist unterstützten (Http://localhost:xxxx).
* Firefox Dateisystem Größe ist nicht begrenzt, aber jede 50MB-Erweiterung wird eine Benutzer die Berechtigung anzufordern. IE10 können bis zu 10mb kombinierte AppCache und IndexedDB in Implementierung des Dateisystems verwendet, ohne Aufforderung, sobald Sie dieses Niveau, werden, das Sie aufgefordert werden schlagen, wenn Sie es bis Max 250 mb pro Standort erhöht werden sollen. `Size`-Parameter für `RequestFileSystem` Funktion wirkt also nicht Dateisystem in Firefox und IE.
* `ReadAsBinaryString` Funktion heißt es nicht in die Angaben und in IE nicht unterstützt und muss keinen Stub.
* `file.Type` ist immer null.
* Sie sollten nicht erstellen Eintrag mit DirectoryEntry Instanz Rückrufergebnis, die gelöscht wurde. Andernfalls erhalten Sie einen "hängende Eintrag".
* Bevor Sie eine Datei lesen können, die gerade geschrieben wurde, müssen Sie eine neue Instanz dieser Datei erhalten.
* `SetMetadata`-Funktion, die nicht in den Specs genannt unterstützt Feldänderung nur `ModificationTime`.
* `CopyTo` und `MoveTo`-Funktionen unterstützen keine Verzeichnisse.
* Verzeichnisse-Metadaten werden nicht unterstützt.
* Beide Entry.remove und directoryEntry.removeRecursively nicht scheitern, wenn nicht leere Verzeichnisse entfernen - Verzeichnisse entfernt werden stattdessen zusammen mit Inhalt gereinigt.
* `abort` und `truncate`-Funktionen werden nicht unterstützt.
* Progress-Ereignisse werden nicht ausgelöst. Beispielsweise wird dieser Handler nicht ausgeführt werden:
```javascript
writer.onprogress = function() { /*commands*/ };
```
## Upgrade Notes
In v1.0.0 dieses Plugins haben die `FileEntry` und `DirectoryEntry` Strukturen geändert, um mehr im Einklang mit der veröffentlichten Spezifikation sein.
Vorgängerversionen (Pre-1.0.0) des Plugins den Gerät-Absolute-Dateispeicherort in der Eigenschaft `fullPath` `Entry` Objekte gespeichert. Diese Pfade würde in der Regel aussehen
/var/mobile/Applications/<application UUID>/Documents/path/to/file (iOS)
/storage/emulated/0/path/to/file (Android)
Diese Pfade wurden auch von der `toURL()`-Methode der `Entry` Objekte zurückgegeben.
Mit v1.0.0 ist das `fullPath`-Attribut den Pfad zu der Datei, *relativ zum Stammverzeichnis des Dateisystems HTML*. Also, würde die oben genannten Wege jetzt beide durch ein `FileEntry`-Objekt mit einem `fullPath` von dargestellt werden
/path/to/file
Wenn Ihre Anwendung mit absoluter Gerätepfade arbeitet und Sie zuvor diese Pfade durch die Eigenschaft `fullPath` `Entry` Objekte abgerufen, sollten dann Sie den Code, um stattdessen `entry.toURL()` verwenden aktualisieren.
Für rückwärts Kompatibilität, die `resolveLocalFileSystemURL()`-Methode wird einen Absolute-Gerätepfad zu akzeptieren und kehrt ein `Entry`-Objekt entspricht, solange diese Datei in den `TEMPORARY` oder `PERSISTENT` Dateisysteme existiert.
Dies wurde vor allem ein Problem mit dem File-Transfer-Plugin, die zuvor-Absolute-Gerätepfade verwendet (und kann damit noch einverstanden). Es wurde überarbeitet, um mit Dateisystem-URLs korrekt zu arbeiten, damit ersetzen `entry.fullPath` mit `entry.toURL()` immer das Plugin zum Arbeiten mit Dateien auf dem Gerät Probleme lösen sollte.
In v1.1.0 wurde der Rückgabewert von `toURL()` (siehe \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) geändert, um eine absolute "file://" URL zurückgeben. wo immer möglich. Sicherstellung einer ' Cdvfile:'-URL können Sie an `toInternalURL()`. Diese Methode gibt jetzt Dateisystem URLs der Form zurück.
cdvfile://localhost/persistent/path/to/file
die benutzt werden können, um die Datei eindeutig zu identifizieren.
## Liste der Fehlercodes und Bedeutungen
Wenn ein Fehler ausgelöst wird, wird eines der folgenden Codes verwendet werden.
| Code | Konstante |
| ----:|:----------------------------- |
| 1 | `NOT_FOUND_ERR` |
| 2 | `SECURITY_ERR` |
| 3 | `ABORT_ERR` |
| 4 | `NOT_READABLE_ERR` |
| 5 | `ENCODING_ERR` |
| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
| 7 | `INVALID_STATE_ERR` |
| 8 | `SYNTAX_ERR` |
| 9 | `INVALID_MODIFICATION_ERR` |
| 10 | `QUOTA_EXCEEDED_ERR` |
| 11 | `TYPE_MISMATCH_ERR` |
| 12 | `PATH_EXISTS_ERR` |
## Konfigurieren das Plugin (Optional)
Die Menge der verfügbaren Dateisysteme kann pro Plattform konfiguriert sein. Erkennen von iOS und Android ein <preference> Tag in `"config.xml"` die Namen der Dateisysteme installiert werden. Standardmäßig sind alle Datei-System-Roots aktiviert.
<preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" />
<preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,root" />
### Android
* `files`: interne Datei-Speicher-Verzeichnis der Anwendung
* `files-external`: Verzeichnis der Anwendung externe Datei Speicher
* `sdcard`: das externe Globaldatei-Speicherverzeichnis (Dies ist die Wurzel der SD-Karte, sofern installiert). Sie benötigen die Berechtigung zur Verwendung dieses `android.permission.WRITE_EXTERNAL_STORAGE`.
* `cache`: internen Cache-Verzeichnis der Anwendung
* `cache-external`: externer Cache-Verzeichnis der Anwendung
* `root`: das gesamte Gerät-Dateisystem
Android unterstützt auch eine spezielle Dateisystem mit dem Namen "documents", die ein Unterverzeichnis "/Documents/" die "files" Dateisystem darstellt.
### iOS
* `library`: Bibliothek-Verzeichnis der Anwendung
* `documents`: Dokumente-Verzeichnis der Anwendung
* `cache`: Cache-Verzeichnis der Anwendung
* `bundle`: die Anwendung Bündel; den Speicherort der die app selbst auf dem Datenträger (schreibgeschützt)
* `root`: das gesamte Gerät-Dateisystem
Standardmäßig können die Bibliothek und Dokumenten-Verzeichnisse mit iCloud synchronisiert werden. Sie können auch verlangen, zwei zusätzliche Dateisysteme, `library-nosync` und `documents-nosync`, die einem speziellen nicht synchronisierten Verzeichnis innerhalb darstellen der `/Library` oder `/Documents`-Dateisystem.

View File

@@ -0,0 +1,338 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-file
Dieses Plugin implementiert eine File-API, die Lese-/Schreibzugriff Zugriff auf Dateien, die auf dem Gerät befinden.
Dieses Plugin basiert auf mehrere Angaben, einschließlich: die HTML5-File-API <http://www.w3.org/TR/FileAPI/>
Die (heute nicht mehr existierenden) Verzeichnisse und System neuesten Erweiterungen: <http://www.w3.org/TR/2012/WD-file-system-api-20120417/> , obwohl die meisten von den Plugin-Code wurde geschrieben, als eine frühere Spec aktuell waren: <http://www.w3.org/TR/2011/WD-file-system-api-20110419/>
Es implementiert auch die FileWriter Spec: <http://dev.w3.org/2009/dap/file-system/file-writer.html>
Verwendung finden Sie in HTML5 Rocks ausgezeichnete [Dateisystem Artikel.][1]
[1]: http://www.html5rocks.com/en/tutorials/file/filesystem/
Finden Sie einen Überblick über andere Speicheroptionen Cordovas [Speicher-Führer][2].
[2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html
Dieses Plugin wird global `cordova.file`-Objekt definiert.
Obwohl im globalen Gültigkeitsbereich, steht es nicht bis nach dem `deviceready`-Ereignis.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(cordova.file);
}
## Installation
cordova plugin add cordova-plugin-file
## Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Windows Phone 7 und 8 *
* Windows 8 *
* Browser
* *Diese Plattformen unterstützen nicht `FileReader.readAsArrayBuffer` noch `FileWriter.write(blob)`.*
## Wo Dateien gespeichert
Stand: V1 werden URLs auf wichtige Datei-System-Verzeichnisse zur Verfügung gestellt. Jede URL in der Form *file:///path/to/spot/* ist, und ein `DirectoryEntry` mit `window.resolveLocalFileSystemURL()` konvertiert werden können.
* `cordova.file.applicationDirectory`-Die schreibgeschützten Verzeichnis, in dem die Anwendung installiert ist. (*iOS*, *Android*, *BlackBerry 10*)
* `cordova.file.applicationStorageDirectory`-Root-Verzeichnis der Anwendungs-Sandbox; auf iOS ist schreibgeschützt (aber bestimmte Unterverzeichnisse [wie `/Documents` ] sind Lese-und Schreibzugriff). Alle enthaltene Daten ist für die app privat. ( *iOS*, *Android*, *BlackBerry 10*)
* `cordova.file.dataDirectory`-Beständige und private Datenspeicherung innerhalb der Anwendungs-Sandbox, die mit internen Speicher (auf Android, externen Speicher verwenden, verwenden Sie `.externalDataDirectory` ). Auf iOS, ist dieses Verzeichnis nicht mit iCloud synchronisiert (verwenden Sie `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
* `cordova.file.cacheDirectory`-Verzeichnis der zwischengespeicherten Daten-Dateien oder Dateien, die Ihre app einfach neu erstellen können. Das Betriebssystem kann diese Dateien löschen, wenn das Gerät auf Speicher knapp wird, dennoch sollten die apps vom Betriebssystem zum Löschen von Dateien hier nicht verlassen. (*iOS*, *Android*, *BlackBerry 10*)
* `cordova.file.externalApplicationStorageDirectory`-Anwendungsraum auf externen Speicher. (*Android*)
* `cordova.file.externalDataDirectory`-Wo, app-spezifische Datendateien auf externen Speicher setzen. (*Android*)
* `cordova.file.externalCacheDirectory`-Anwendungscache auf externen Speicher. (*Android*)
* `cordova.file.externalRootDirectory`-Externer Speicher (SD-Karte) Stamm. (*Android*, *BlackBerry 10*)
* `cordova.file.tempDirectory`-Temp-Verzeichnis, dem das OS auf deaktivieren können wird. Verlassen Sie sich nicht auf das Betriebssystem, um dieses Verzeichnis zu löschen; Ihre Anwendung sollte immer Dateien gegebenenfalls entfernen. (*iOS*)
* `cordova.file.syncedDataDirectory`-Hält app-spezifische Dateien, die (z. B. auf iCloud) synchronisiert werden sollten. (*iOS*)
* `cordova.file.documentsDirectory`-Dateien für die app, aber privat sind sinnvoll, andere Anwendungen (z.B. Office-Dateien). (*iOS*)
* `cordova.file.sharedDirectory`-Dateien für alle Anwendungen (*BlackBerry 10* weltweit verfügbar)
## Dateisystemlayouts
Obwohl technisch ein Implementierungsdetail, kann es sehr hilfreich zu wissen, wie die `cordova.file.*`-Eigenschaften physikalische Pfade auf einem echten Gerät zugeordnet sein.
### iOS-Datei-System-Layout
| Gerätepfad | `Cordova.file.*` | `iosExtraFileSystems` | R/w? | persistent? | OS löscht | Sync | Private |
|:-------------------------------------------- |:--------------------------- |:--------------------- |:----:|:-----------:|:----------:|:----:|:-------:|
| `/ Var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Ja |
|    `appname.app/` | applicationDirectory | Bundle | r | N/A | N/A | N/A | Ja |
|       `www/` | - | - | r | N/A | N/A | N/A | Ja |
|    `Documents/` | documentsDirectory | Dokumente | R/w | Ja | Nein | Ja | Ja |
|       `NoCloud/` | - | Dokumente-nosync | R/w | Ja | Nein | Nein | Ja |
|    `Library` | - | Bibliothek | R/w | Ja | Nein | Ja? | Ja |
|       `NoCloud/` | dataDirectory | Bibliothek-nosync | R/w | Ja | Nein | Nein | Ja |
|       `Cloud/` | syncedDataDirectory | - | R/w | Ja | Nein | Ja | Ja |
|       `Caches/` | cacheDirectory | Cache | R/w | Ja * | Ja * * *| | Nein | Ja |
|    `tmp/` | tempDirectory | - | R/w | Nicht * * | Ja * * *| | Nein | Ja |
* Dateien werden hinweg app Neustarts und Upgrades beibehalten, aber dieses Verzeichnis kann gelöscht werden, wenn das OS begehrt. Ihre Anwendung sollte in der Lage, Inhalte zu erschaffen, die möglicherweise gelöscht werden.
* *-Dateien kann über app-Neustarts beizubehalten, aber verlasse dich nicht auf dieses Verhalten. Dateien sind nicht unbedingt Aktuelles beibehalten. Ihre Anwendung sollte Dateien aus diesem Verzeichnis entfernen, wenn es gilt, diese Dateien werden entfernt, da das OS nicht wann (oder auch wenn) garantiert.
* * *| The OS kann den Inhalt dieses Verzeichnisses löschen, wenn es sich anfühlt, ist es erforderlich, aber verlassen Sie sich nicht dazu. Sie sollten dieses Verzeichnis entsprechend Ihrer Anwendung deaktivieren.
### Android File System-Layout
| Gerätepfad | `Cordova.file.*` | `AndroidExtraFileSystems` | R/w? | persistent? | OS löscht | Private |
|:--------------------------------- |:----------------------------------- |:------------------------- |:----:|:-----------:|:---------:|:-------:|
| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | Ja |
| `/ Data/Data/< app-Id > /` | applicationStorageDirectory | - | R/w | N/A | N/A | Ja |
|    `cache` | cacheDirectory | Cache | R/w | Ja | Ja * | Ja |
|    `files` | dataDirectory | Dateien | R/w | Ja | Nein | Ja |
|       `Documents` | | Dokumente | R/w | Ja | Nein | Ja |
| `< Sdcard > /` | externalRootDirectory | sdcard | R/w | Ja | Nein | Nein |
|    `Android/data/<app-id>/` | externalApplicationStorageDirectory | - | R/w | Ja | Nein | Nein |
|       `cache` | externalCacheDirectry | Cache-extern | R/w | Ja | Nicht * * | Nein |
|       `files` | externalDataDirectory | Dateien-extern | R/w | Ja | Nein | Nein |
* Das Betriebssystem kann regelmäßig dieses Verzeichnis zu löschen, aber verlasse dich nicht auf dieses Verhalten. Deaktivieren Sie den Inhalt dieses Verzeichnisses für Ihre Anwendung geeigneten. Ein Benutzer den Cache manuell löschen sollte, werden die Inhalte dieses Verzeichnisses entfernt.
* * The OS nicht klar dieses Verzeichnis automatisch; Sie sind verantwortlich für die Inhalte selbst verwalten. Der Benutzer den Cache manuell löschen sollte, werden der Inhalt des Verzeichnisses entfernt.
**Hinweis**: Wenn externe Speichergeräte nicht bereitgestellt werden kann, sind die `cordova.file.external*` Eigenschaften `null`.
### BlackBerry 10-File-System-Layout
| Gerätepfad | `Cordova.file.*` | R/w? | persistent? | OS löscht | Private |
|:--------------------------------------------------- |:--------------------------- |:----:|:-----------:|:---------:|:-------:|
| `file:///Accounts/1000/APPDATA/ < app Id > /` | applicationStorageDirectory | r | N/A | N/A | Ja |
|    `app/native` | applicationDirectory | r | N/A | N/A | Ja |
|    `data/webviews/webfs/temporary/local__0` | cacheDirectory | R/w | Nein | Ja | Ja |
|    `data/webviews/webfs/persistent/local__0` | dataDirectory | R/w | Ja | Nein | Ja |
| `file:///Accounts/1000/Removable/sdcard` | externalRemovableDirectory | R/w | Ja | Nein | Nein |
| `file:///Accounts/1000/Shared` | sharedDirectory | R/w | Ja | Nein | Nein |
*Hinweis*: Wenn die Anwendung bereitgestellt wird, um Perimeter zu arbeiten, alle Pfade sind relativ /accounts/1000-enterprise.
## Android Eigenarten
### Android permanenten Speicherort
Es gibt mehrere gültige Speicherorte, persistente Dateien auf einem Android-Gerät zu speichern. Finden Sie auf [dieser Seite][3] eine ausführliche Diskussion über die verschiedenen Möglichkeiten.
[3]: http://developer.android.com/guide/topics/data/data-storage.html
Frühere Versionen des Plugins wählen würde, den Speicherort der temporären und permanenten Dateien beim Start, basierend auf, ob das Gerät behauptete, dass die SD-Karte (oder gleichwertige Speicherpartition) bereitgestellt wurde. Wenn die SD-Karte eingelegt wurde, oder wenn eine große interne Speicherpartition verfügbar war (wie auf Nexus-Geräten) und dann in die Wurzel dieses Raumes, die persistenten Dateien gespeichert werden. Dies bedeutete, dass alle Cordova apps aller verfügbaren Dateien auf der Karte sehen konnte.
Wenn die SD-Karte nicht verfügbar war, dann Vorgängerversionen Daten unter speichern würde `/data/data/<packageId>`, die isoliert Anwendungen voneinander, aber möglicherweise noch Ursache Daten zwischen Benutzern freigegeben werden.
Es ist jetzt möglich, ob Sie Dateien der internen Datei-Speicherort oder unter Verwendung der bisherigen Logik, mit einer Präferenz in der Anwendung-`config.xml`-Datei speichern möchten. Hierzu fügen Sie eine dieser zwei Zeilen zu `"config.xml"`:
<preference name="AndroidPersistentFileLocation" value="Internal" />
<preference name="AndroidPersistentFileLocation" value="Compatibility" />
Ohne diese Zeile wird das Datei Plugin `Compatibility` als Standard verwenden. Wenn ein Präferenz-Tag vorhanden ist, und nicht einen der folgenden Werte, wird die Anwendung nicht gestartet.
Wenn Ihre Anwendung für Benutzer zuvor versandt wird, mithilfe eines älteren (Pre-1.0) Version dieses Plugins und gespeicherte Dateien im permanenten Dateisystem hat, dann sollten Sie die Einstellung zur `Compatibility` einstellen. Wechseln die Location auf "Internal" würde bedeuten, dass Benutzer, die aktualisieren Sie ihre Anwendung, möglicherweise nicht auf ihre zuvor gespeicherte Dateien, abhängig von ihrem Gerät zugreifen.
Wenn Ihre Anwendung neu ist, oder nie zuvor Dateien im Dateisystem persistent gespeichert hat, wird die `Internal` Einstellung in der Regel empfohlen.
## iOS Macken
* `cordova.file.applicationStorageDirectory`ist schreibgeschützt; zum Speichern von Dateien im Stammverzeichnis der Versuch schlägt fehl. Verwenden Sie eine der anderen `cordova.file.*` für iOS definierten Eigenschaften (nur `applicationDirectory` und `applicationStorageDirectory` sind schreibgeschützt).
* `FileReader.readAsText(blob, encoding)`
* Die `encoding` Parameter wird nicht unterstützt und UTF-8-Kodierung ist immer wirksam.
### iOS permanenten Speicherort
Es gibt zwei gültige Speicherorte persistente Dateien auf ein iOS-Gerät speichern: das Dokumenten-Verzeichnis und das Verzeichnis Library. Frühere Versionen des Plugins gespeichert immer nur persistente Dateien im Verzeichnis Dokumente. Dies hatte den Nebeneffekt einer Anwendung Dateien in iTunes, die oft unbeabsichtigte, speziell für Anwendungen, die viele kleine Dateien behandeln war, sichtbar zu machen, anstatt komplette Dokumente für den Export, die den beabsichtigten Zweck des Verzeichnisses ist zu produzieren.
Es ist jetzt möglich, ob Sie Dateien in Dokumente oder Verzeichnis Library mit einer Präferenz in der Anwendung-`config.xml`-Datei speichern möchten. Hierzu fügen Sie eine dieser zwei Zeilen zu `"config.xml"`:
<preference name="iosPersistentFileLocation" value="Library" />
<preference name="iosPersistentFileLocation" value="Compatibility" />
Ohne diese Zeile wird das Datei Plugin `Compatibility` als Standard verwenden. Wenn ein Präferenz-Tag vorhanden ist, und nicht einen der folgenden Werte, wird die Anwendung nicht gestartet.
Wenn Ihre Anwendung für Benutzer zuvor versandt wird, mithilfe eines älteren (Pre-1.0) Version dieses Plugins und gespeicherte Dateien im permanenten Dateisystem hat, dann sollten Sie die Einstellung zur `Compatibility` einstellen. Standort zur `Library` wechseln würde bedeuten, dass Benutzer, die ihre Anwendung aktualisieren nicht in der Lage wäre, ihre zuvor gespeicherte Dateien zugreifen.
Wenn die Anwendung neu, oder nie zuvor Dateien im Dateisystem persistent gespeichert hat, wird die Einstellung der `Library` allgemein empfohlen.
## Firefox OS Macken
Der Datei-System-API wird von Firefox-OS nicht nativ unterstützt und wird als ein Shim auf IndexedDB implementiert.
* Schlägt nicht fehl, wenn Sie nicht leere Verzeichnisse entfernen
* Metadaten wird für Verzeichnisse nicht unterstützt.
* Methoden `copyTo` und `moveTo` unterstützen keine Verzeichnisse
Die folgenden Datenpfade werden unterstützt: * `applicationDirectory` - `xhr` verwendet, um lokale Dateien erhalten, die mit der app verpackt sind. *`dataDirectory` - für persistente app-spezifische Daten-Dateien. *`cacheDirectory` - Cache-Dateien, die app startet überleben sollte (Apps sollten nicht vom Betriebssystem zum Löschen von Dateien hier verlassen).
## Browser-Eigenheiten
### Gemeinsamen Macken und Bemerkungen
* Jeder Browser verwendet ein eigene Sandbox Dateisystem. IE und Firefox verwenden IndexedDB als Basis. Alle Browser verwenden Schrägstrich als Verzeichnistrennzeichen in einem Pfad.
* Directory-Einträge müssen nacheinander erstellt werden. Z. B. der Aufruf `fs.root.getDirectory ("dir1/Ordner2 ', {create:true}, SuccessCallback, ErrorCallback)` schlägt fehl, wenn dir1 nicht existierte.
* Das Plugin fordert Benutzer die Berechtigung zum permanenten Speicher beim ersten Start Anwendung verwenden.
* Plugin unterstützt `Cdvfile://localhost` (lokale Ressourcen) nur. D.h. externe Ressourcen nicht über `Cdvfile` unterstützt.
* Das Plugin folgt nicht ["File System API 8.3 Naming Einschränkungen"][4].
* BLOB und Datei "`close`-Funktion wird nicht unterstützt.
* `FileSaver` und `BlobBuilder` werden von diesem Plugin nicht unterstützt und müssen nicht geboren.
* Das Plugin unterstützt keine `RequestAllFileSystems`. Diese Funktion fehlt auch in den Spezifikationen.
* Einträge im Verzeichnis werden nicht entfernt werden, wenn Sie verwenden `create: true` Flag für vorhandenes Verzeichnis.
* Über Konstruktor erstellte Dateien werden nicht unterstützt. Sie sollten stattdessen die entry.file-Methode verwenden.
* Jeder Browser verwendet eine eigene Form für Blob-URL-Verweise.
* `readAsDataURL`-Funktion wird unterstützt, aber die Mediatype in Chrom hängt von der Eintrag Namenerweiterung, Mediatype im IE immer leer ist (das ist dasselbe wie `Text-Plain` gemäß der Spezifikation), Mediatype in Firefox ist immer `Application/Octet-Stream`. Beispielsweise, wenn der Inhalt `Abcdefg` gibt dann Firefox `Daten: Anwendung / Octet-Stream; base64, YWJjZGVmZw ==`, IE gibt `Daten:; base64, YWJjZGVmZw ==`, Chrom gibt `Daten: < Mediatype je nach Erweiterung des Eintragsnamens >; base64, YWJjZGVmZw ==`.
* `ToInternalURL` gibt den Pfad zurück, in der Form `file:///persistent/path/to/entry` (Firefox, IE). Chrom gibt den Pfad zurück, in der Form `cdvfile://localhost/persistent/file`.
[4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions
### Chrom-Macken
* Chrom-Dateisystem ist nicht sofort nach Gerät bereit. Als Workaround können Sie `FilePluginIsReady`-Ereignis abonnieren. Beispiel:
javascript
window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
`Window.isFilePluginReadyRaised`-Funktion können Sie überprüfen, ob Ereignis bereits ausgelöst wurde. -window.requestFileSystem temporär und PERSISTENTE Dateisystem-Quoten sind nicht begrenzt, in Chrom. -Um die dauerhafte Speicherung in Chrom zu erhöhen benötigen Sie `window.initPersistentFileSystem`-Methode aufrufen. Permanenter Speicherkontingent beträgt 5 MB standardmäßig. -Chrome erforderlich `--erlauben-Datei-Zugriff-aus-Files` Argument an den Support API via `file:///` Protokoll führen. -`Datei`-Objekt wird nicht geändert werden, wenn Sie Flag verwenden `{create:true}` als einen vorhandenen `Eintrag` zu erhalten. -Veranstaltungen `cancelable`-Eigenschaft festgelegt ist in Chrom wahr. Dies widerspricht der [Spezifikation][5]. -`toURL`-Funktion in Chrome zurück `Dateisystem:`-Pfad je nach Anwendungshost vorangestellt. Z. B. `filesystem:file:///persistent/somefile.txt`, `Filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` Funktionsergebnis enthält keine nachgestellten Schrägstrich bei Verzeichniseintrag. Chrom löst Verzeichnisse mit Schrägstrich-gezogene Urls aber korrekt. -`ResolveLocalFileSystemURL`-Methode erfordert die eingehenden `Url` `Dateisystem` Präfix haben. Beispielsweise sollte die `Url`-Parameter für `ResolveLocalFileSystemURL` in der Form `filesystem:file:///persistent/somefile.txt` im Gegensatz zu der Form `file:///persistent/somefile.txt` in Android. -Veraltete `ToNativeURL`-Funktion wird nicht unterstützt und muss keinen Stub. -`SetMetadata`-Funktion ist nicht in den Spezifikationen angegeben und nicht unterstützt. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, statt SYNTAX_ERR(code: 8) auf anfordern des Dateisystems nicht existent. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt PATH_EXISTS_ERR(code: 12) zu versuchen, die ausschließlich eine Datei oder ein Verzeichnis zu erstellen, die bereits vorhanden ist. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt NO_MODIFICATION_ALLOWED_ERR(code: 6) zu versuchen, rufen Sie RemoveRecursively auf das Root-Dateisystem. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt NOT_FOUND_ERR(code: 1) zu versuchen, MoveTo-Verzeichnis, das nicht vorhanden ist.
[5]: http://dev.w3.org/2009/dap/file-system/file-writer.html
### Auf der Grundlage von IndexedDB Impl Macken (Firefox und IE)
* `.` und `.` werden nicht unterstützt.
* IE unterstützt keine `file:///`-Modus; nur der Modus für gehostete ist unterstützten (Http://localhost:xxxx).
* Firefox Dateisystem Größe ist nicht begrenzt, aber jede 50MB-Erweiterung wird eine Benutzer die Berechtigung anzufordern. IE10 können bis zu 10mb kombinierte AppCache und IndexedDB in Implementierung des Dateisystems verwendet, ohne Aufforderung, sobald Sie dieses Niveau, werden, das Sie aufgefordert werden schlagen, wenn Sie es bis Max 250 mb pro Standort erhöht werden sollen. `Size`-Parameter für `RequestFileSystem` Funktion wirkt also nicht Dateisystem in Firefox und IE.
* `ReadAsBinaryString` Funktion heißt es nicht in die Angaben und in IE nicht unterstützt und muss keinen Stub.
* `file.Type` ist immer null.
* Sie sollten nicht erstellen Eintrag mit DirectoryEntry Instanz Rückrufergebnis, die gelöscht wurde. Andernfalls erhalten Sie einen "hängende Eintrag".
* Bevor Sie eine Datei lesen können, die gerade geschrieben wurde, müssen Sie eine neue Instanz dieser Datei erhalten.
* `SetMetadata`-Funktion, die nicht in den Specs genannt unterstützt Feldänderung nur `ModificationTime`.
* `CopyTo` und `MoveTo`-Funktionen unterstützen keine Verzeichnisse.
* Verzeichnisse-Metadaten werden nicht unterstützt.
* Beide Entry.remove und directoryEntry.removeRecursively nicht scheitern, wenn nicht leere Verzeichnisse entfernen - Verzeichnisse entfernt werden stattdessen zusammen mit Inhalt gereinigt.
* `abort` und `truncate`-Funktionen werden nicht unterstützt.
* Progress-Ereignisse werden nicht ausgelöst. Beispielsweise wird dieser Handler nicht ausgeführt werden:
javascript
writer.onprogress = function() { /*commands*/ };
## Upgrade Notes
In v1.0.0 dieses Plugins haben die `FileEntry` und `DirectoryEntry` Strukturen geändert, um mehr im Einklang mit der veröffentlichten Spezifikation sein.
Vorgängerversionen (Pre-1.0.0) des Plugins den Gerät-Absolute-Dateispeicherort in der Eigenschaft `fullPath` `Entry` Objekte gespeichert. Diese Pfade würde in der Regel aussehen
/var/mobile/Applications/<application UUID>/Documents/path/to/file (iOS)
/storage/emulated/0/path/to/file (Android)
Diese Pfade wurden auch von der `toURL()`-Methode der `Entry` Objekte zurückgegeben.
Mit v1.0.0 ist das `fullPath`-Attribut den Pfad zu der Datei, *relativ zum Stammverzeichnis des Dateisystems HTML*. Also, würde die oben genannten Wege jetzt beide durch ein `FileEntry`-Objekt mit einem `fullPath` von dargestellt werden
/path/to/file
Wenn Ihre Anwendung mit absoluter Gerätepfade arbeitet und Sie zuvor diese Pfade durch die Eigenschaft `fullPath` `Entry` Objekte abgerufen, sollten dann Sie den Code, um stattdessen `entry.toURL()` verwenden aktualisieren.
Für rückwärts Kompatibilität, die `resolveLocalFileSystemURL()`-Methode wird einen Absolute-Gerätepfad zu akzeptieren und kehrt ein `Entry`-Objekt entspricht, solange diese Datei in den `TEMPORARY` oder `PERSISTENT` Dateisysteme existiert.
Dies wurde vor allem ein Problem mit dem File-Transfer-Plugin, die zuvor-Absolute-Gerätepfade verwendet (und kann damit noch einverstanden). Es wurde überarbeitet, um mit Dateisystem-URLs korrekt zu arbeiten, damit ersetzen `entry.fullPath` mit `entry.toURL()` immer das Plugin zum Arbeiten mit Dateien auf dem Gerät Probleme lösen sollte.
In v1.1.0 wurde der Rückgabewert von `toURL()` (siehe \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) geändert, um eine absolute "file://" URL zurückgeben. wo immer möglich. Sicherstellung einer ' Cdvfile:'-URL können Sie an `toInternalURL()`. Diese Methode gibt jetzt Dateisystem URLs der Form zurück.
cdvfile://localhost/persistent/path/to/file
die benutzt werden können, um die Datei eindeutig zu identifizieren.
## Liste der Fehlercodes und Bedeutungen
Wenn ein Fehler ausgelöst wird, wird eines der folgenden Codes verwendet werden.
| Code | Konstante |
| ----:|:----------------------------- |
| 1 | `NOT_FOUND_ERR` |
| 2 | `SECURITY_ERR` |
| 3 | `ABORT_ERR` |
| 4 | `NOT_READABLE_ERR` |
| 5 | `ENCODING_ERR` |
| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
| 7 | `INVALID_STATE_ERR` |
| 8 | `SYNTAX_ERR` |
| 9 | `INVALID_MODIFICATION_ERR` |
| 10 | `QUOTA_EXCEEDED_ERR` |
| 11 | `TYPE_MISMATCH_ERR` |
| 12 | `PATH_EXISTS_ERR` |
## Konfigurieren das Plugin (Optional)
Die Menge der verfügbaren Dateisysteme kann pro Plattform konfiguriert sein. Erkennen von iOS und Android ein <preference> Tag in `"config.xml"` die Namen der Dateisysteme installiert werden. Standardmäßig sind alle Datei-System-Roots aktiviert.
<preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" />
<preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,root" />
### Android
* `files`: interne Datei-Speicher-Verzeichnis der Anwendung
* `files-external`: Verzeichnis der Anwendung externe Datei Speicher
* `sdcard`: das externe Globaldatei-Speicherverzeichnis (Dies ist die Wurzel der SD-Karte, sofern installiert). Sie benötigen die Berechtigung zur Verwendung dieses `android.permission.WRITE_EXTERNAL_STORAGE`.
* `cache`: internen Cache-Verzeichnis der Anwendung
* `cache-external`: externer Cache-Verzeichnis der Anwendung
* `root`: das gesamte Gerät-Dateisystem
Android unterstützt auch eine spezielle Dateisystem mit dem Namen "documents", die ein Unterverzeichnis "/Documents/" die "files" Dateisystem darstellt.
### iOS
* `library`: Bibliothek-Verzeichnis der Anwendung
* `documents`: Dokumente-Verzeichnis der Anwendung
* `cache`: Cache-Verzeichnis der Anwendung
* `bundle`: die Anwendung Bündel; den Speicherort der die app selbst auf dem Datenträger (schreibgeschützt)
* `root`: das gesamte Gerät-Dateisystem
Standardmäßig können die Bibliothek und Dokumenten-Verzeichnisse mit iCloud synchronisiert werden. Sie können auch verlangen, zwei zusätzliche Dateisysteme, `library-nosync` und `documents-nosync`, die einem speziellen nicht synchronisierten Verzeichnis innerhalb darstellen der `/Library` oder `/Documents`-Dateisystem.

Some files were not shown because too many files have changed in this diff Show More