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
@@ -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!
@@ -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.
@@ -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/).
@@ -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
@@ -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
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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 + "%");
}
@@ -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"
}
@@ -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>
@@ -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);
}
}
}
@@ -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);
}
}
};
@@ -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);
@@ -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);
@@ -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
@@ -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
@@ -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);
@@ -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;
}
@@ -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
@@ -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);
}
@@ -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
@@ -0,0 +1,3 @@
/bin/
/obj/
*.suo
@@ -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;
};
}
}
@@ -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>
@@ -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")]
@@ -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;
}
}
}
@@ -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"
}
@@ -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>
+559
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');
};
+125
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;
}
+110
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;