@capawesome/capacitor-battery 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CapawesomeCapacitorBattery.podspec +17 -0
  2. package/LICENSE +21 -0
  3. package/Package.swift +28 -0
  4. package/README.md +366 -0
  5. package/android/build.gradle +58 -0
  6. package/android/src/main/AndroidManifest.xml +2 -0
  7. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/Battery.java +163 -0
  8. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/BatteryPlugin.java +156 -0
  9. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/classes/CustomException.java +20 -0
  10. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/classes/CustomExceptions.java +9 -0
  11. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/classes/events/BatteryLevelChangeEvent.java +22 -0
  12. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/classes/events/BatteryStateChangeEvent.java +23 -0
  13. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/classes/events/LowPowerModeChangeEvent.java +22 -0
  14. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/classes/results/GetBatteryLevelResult.java +22 -0
  15. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/classes/results/GetBatteryStateResult.java +23 -0
  16. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/classes/results/IsLowPowerModeEnabledResult.java +22 -0
  17. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/interfaces/Callback.java +5 -0
  18. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/interfaces/NonEmptyResultCallback.java +7 -0
  19. package/android/src/main/java/io/capawesome/capacitorjs/plugins/battery/interfaces/Result.java +7 -0
  20. package/android/src/main/res/.gitkeep +0 -0
  21. package/dist/docs.json +393 -0
  22. package/dist/esm/definitions.d.ts +166 -0
  23. package/dist/esm/definitions.js +2 -0
  24. package/dist/esm/definitions.js.map +1 -0
  25. package/dist/esm/index.d.ts +4 -0
  26. package/dist/esm/index.js +7 -0
  27. package/dist/esm/index.js.map +1 -0
  28. package/dist/esm/web.d.ts +13 -0
  29. package/dist/esm/web.js +58 -0
  30. package/dist/esm/web.js.map +1 -0
  31. package/dist/plugin.cjs.js +72 -0
  32. package/dist/plugin.cjs.js.map +1 -0
  33. package/dist/plugin.js +75 -0
  34. package/dist/plugin.js.map +1 -0
  35. package/ios/Plugin/Battery.swift +116 -0
  36. package/ios/Plugin/BatteryPlugin.swift +105 -0
  37. package/ios/Plugin/Classes/Events/BatteryLevelChangeEvent.swift +16 -0
  38. package/ios/Plugin/Classes/Events/BatteryStateChangeEvent.swift +16 -0
  39. package/ios/Plugin/Classes/Events/LowPowerModeChangeEvent.swift +16 -0
  40. package/ios/Plugin/Classes/Results/GetBatteryLevelResult.swift +16 -0
  41. package/ios/Plugin/Classes/Results/GetBatteryStateResult.swift +16 -0
  42. package/ios/Plugin/Classes/Results/IsLowPowerModeEnabledResult.swift +16 -0
  43. package/ios/Plugin/Enums/CustomError.swift +14 -0
  44. package/ios/Plugin/Info.plist +24 -0
  45. package/ios/Plugin/Protocols/Result.swift +5 -0
  46. package/package.json +91 -0
@@ -0,0 +1,17 @@
1
+ require 'json'
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = 'CapawesomeCapacitorBattery'
7
+ s.version = package['version']
8
+ s.summary = package['description']
9
+ s.license = package['license']
10
+ s.homepage = package['repository']['url']
11
+ s.author = package['author']
12
+ s.source = { :git => package['repository']['url'], :tag => s.version.to_s }
13
+ s.source_files = 'ios/Plugin/**/*.{swift,h,m,c,cc,mm,cpp}'
14
+ s.ios.deployment_target = '15.0'
15
+ s.dependency 'Capacitor'
16
+ s.swift_version = '5.1'
17
+ end
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Robin Genz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/Package.swift ADDED
@@ -0,0 +1,28 @@
1
+ // swift-tools-version: 5.9
2
+ import PackageDescription
3
+
4
+ let package = Package(
5
+ name: "CapawesomeCapacitorBattery",
6
+ platforms: [.iOS(.v15)],
7
+ products: [
8
+ .library(
9
+ name: "CapawesomeCapacitorBattery",
10
+ targets: ["BatteryPlugin"])
11
+ ],
12
+ dependencies: [
13
+ .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0")
14
+ ],
15
+ targets: [
16
+ .target(
17
+ name: "BatteryPlugin",
18
+ dependencies: [
19
+ .product(name: "Capacitor", package: "capacitor-swift-pm"),
20
+ .product(name: "Cordova", package: "capacitor-swift-pm")
21
+ ],
22
+ path: "ios/Plugin"),
23
+ .testTarget(
24
+ name: "BatteryPluginTests",
25
+ dependencies: ["BatteryPlugin"],
26
+ path: "ios/PluginTests")
27
+ ]
28
+ )
package/README.md ADDED
@@ -0,0 +1,366 @@
1
+ # @capawesome/capacitor-battery
2
+
3
+ Capacitor plugin to access battery information.
4
+
5
+ <div class="capawesome-z29o10a">
6
+ <a href="https://cloud.capawesome.io/" target="_blank">
7
+ <img alt="Deliver Live Updates to your Capacitor app with Capawesome Cloud" src="https://cloud.capawesome.io/assets/banners/cloud-build-and-deploy-capacitor-apps.png?t=1" />
8
+ </a>
9
+ </div>
10
+
11
+ ## Features
12
+
13
+ We are proud to offer one of the most complete and feature-rich Capacitor plugins for battery information. Here are some of the key features:
14
+
15
+ - 🔋 **Battery level**: Read the current battery level of the device.
16
+ - ⚡ **Battery state**: Read whether the device is charging, full or unplugged.
17
+ - 🪫 **Low power mode**: Read whether the low power mode is enabled.
18
+ - 👂 **Change events**: Listen for changes to the battery level, state and low power mode.
19
+ - 🌐 **Web support**: Read the battery level and state on supported browsers.
20
+ - 📦 **CocoaPods & SPM**: Supports CocoaPods and Swift Package Manager for iOS.
21
+ - 🔗 **Compatibility**: Works alongside the [Android Battery Optimization](https://capawesome.io/plugins/android-battery-optimization/) plugin.
22
+ - 🔁 **Up-to-date**: Always supports the latest Capacitor version.
23
+
24
+ Missing a feature? Just [open an issue](https://github.com/capawesome-team/capacitor-plugins/issues) and we'll take a look!
25
+
26
+ ## Newsletter
27
+
28
+ Stay up to date with the latest news and updates about the Capawesome, Capacitor, and Ionic ecosystem by subscribing to our [Capawesome Newsletter](https://cloud.capawesome.io/newsletter/).
29
+
30
+ ## Compatibility
31
+
32
+ | Plugin Version | Capacitor Version | Status |
33
+ | -------------- | ----------------- | -------------- |
34
+ | 0.x.x | >=8.x.x | Active support |
35
+
36
+ ## Installation
37
+
38
+ You can use our **AI-Assisted Setup** to install the plugin.
39
+ Add the [Capawesome Skills](https://github.com/capawesome-team/skills) to your AI tool using the following command:
40
+
41
+ ```bash
42
+ npx skills add capawesome-team/skills --skill capacitor-plugins
43
+ ```
44
+
45
+ Then use the following prompt:
46
+
47
+ ```
48
+ Use the `capacitor-plugins` skill from `capawesome-team/skills` to install the `@capawesome/capacitor-battery` plugin in my project.
49
+ ```
50
+
51
+ If you prefer **Manual Setup**, install the plugin by running the following commands and follow the platform-specific instructions below:
52
+
53
+ ```bash
54
+ npm install @capawesome/capacitor-battery
55
+ npx cap sync
56
+ ```
57
+
58
+ This plugin does not require any additional configuration or permissions on Android or iOS.
59
+
60
+ On the **Web**, the battery level and state are only available in browsers that implement the [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API) (Chromium-based browsers). The low power mode is not available on the Web.
61
+
62
+ ## Configuration
63
+
64
+ No configuration required for this plugin.
65
+
66
+ ## Usage
67
+
68
+ ```typescript
69
+ import { Battery } from '@capawesome/capacitor-battery';
70
+
71
+ const getBatteryLevel = async () => {
72
+ const { level } = await Battery.getBatteryLevel();
73
+ return level;
74
+ };
75
+
76
+ const getBatteryState = async () => {
77
+ const { state } = await Battery.getBatteryState();
78
+ return state;
79
+ };
80
+
81
+ const isLowPowerModeEnabled = async () => {
82
+ const { enabled } = await Battery.isLowPowerModeEnabled();
83
+ return enabled;
84
+ };
85
+
86
+ const addBatteryLevelChangeListener = async () => {
87
+ await Battery.addListener('batteryLevelChange', event => {
88
+ console.log('Battery level changed:', event.level);
89
+ });
90
+ };
91
+
92
+ const addBatteryStateChangeListener = async () => {
93
+ await Battery.addListener('batteryStateChange', event => {
94
+ console.log('Battery state changed:', event.state);
95
+ });
96
+ };
97
+
98
+ const addLowPowerModeChangeListener = async () => {
99
+ await Battery.addListener('lowPowerModeChange', event => {
100
+ console.log('Low power mode changed:', event.enabled);
101
+ });
102
+ };
103
+
104
+ const removeAllListeners = async () => {
105
+ await Battery.removeAllListeners();
106
+ };
107
+ ```
108
+
109
+ ## API
110
+
111
+ <docgen-index>
112
+
113
+ * [`getBatteryLevel()`](#getbatterylevel)
114
+ * [`getBatteryState()`](#getbatterystate)
115
+ * [`isLowPowerModeEnabled()`](#islowpowermodeenabled)
116
+ * [`addListener('batteryLevelChange', ...)`](#addlistenerbatterylevelchange-)
117
+ * [`addListener('batteryStateChange', ...)`](#addlistenerbatterystatechange-)
118
+ * [`addListener('lowPowerModeChange', ...)`](#addlistenerlowpowermodechange-)
119
+ * [`removeAllListeners()`](#removealllisteners)
120
+ * [Interfaces](#interfaces)
121
+ * [Type Aliases](#type-aliases)
122
+
123
+ </docgen-index>
124
+
125
+ <docgen-api>
126
+ <!--Update the source file JSDoc comments and rerun docgen to update the docs below-->
127
+
128
+ ### getBatteryLevel()
129
+
130
+ ```typescript
131
+ getBatteryLevel() => Promise<GetBatteryLevelResult>
132
+ ```
133
+
134
+ Get the current battery level of the device.
135
+
136
+ On the web, this is only supported in browsers that implement the
137
+ [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API)
138
+ (Chromium-based browsers).
139
+
140
+ Only available on Android, iOS and Web.
141
+
142
+ **Returns:** <code>Promise&lt;<a href="#getbatterylevelresult">GetBatteryLevelResult</a>&gt;</code>
143
+
144
+ **Since:** 0.1.0
145
+
146
+ --------------------
147
+
148
+
149
+ ### getBatteryState()
150
+
151
+ ```typescript
152
+ getBatteryState() => Promise<GetBatteryStateResult>
153
+ ```
154
+
155
+ Get the current battery state of the device.
156
+
157
+ On the web, this is only supported in browsers that implement the
158
+ [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API)
159
+ (Chromium-based browsers).
160
+
161
+ Only available on Android, iOS and Web.
162
+
163
+ **Returns:** <code>Promise&lt;<a href="#getbatterystateresult">GetBatteryStateResult</a>&gt;</code>
164
+
165
+ **Since:** 0.1.0
166
+
167
+ --------------------
168
+
169
+
170
+ ### isLowPowerModeEnabled()
171
+
172
+ ```typescript
173
+ isLowPowerModeEnabled() => Promise<IsLowPowerModeEnabledResult>
174
+ ```
175
+
176
+ Get whether the low power mode is currently enabled.
177
+
178
+ On Android, this refers to the power saver mode. On iOS, this refers to
179
+ the Low Power Mode.
180
+
181
+ Only available on Android and iOS.
182
+
183
+ **Returns:** <code>Promise&lt;<a href="#islowpowermodeenabledresult">IsLowPowerModeEnabledResult</a>&gt;</code>
184
+
185
+ **Since:** 0.1.0
186
+
187
+ --------------------
188
+
189
+
190
+ ### addListener('batteryLevelChange', ...)
191
+
192
+ ```typescript
193
+ addListener(eventName: 'batteryLevelChange', listenerFunc: (event: BatteryLevelChangeEvent) => void) => Promise<PluginListenerHandle>
194
+ ```
195
+
196
+ Listen for changes to the battery level of the device.
197
+
198
+ The device is only observed while at least one listener is attached.
199
+
200
+ On the web, this is only supported in browsers that implement the
201
+ [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API)
202
+ (Chromium-based browsers).
203
+
204
+ Only available on Android, iOS and Web.
205
+
206
+ | Param | Type |
207
+ | ------------------ | ----------------------------------------------------------------------------------------------- |
208
+ | **`eventName`** | <code>'batteryLevelChange'</code> |
209
+ | **`listenerFunc`** | <code>(event: <a href="#batterylevelchangeevent">BatteryLevelChangeEvent</a>) =&gt; void</code> |
210
+
211
+ **Returns:** <code>Promise&lt;<a href="#pluginlistenerhandle">PluginListenerHandle</a>&gt;</code>
212
+
213
+ **Since:** 0.1.0
214
+
215
+ --------------------
216
+
217
+
218
+ ### addListener('batteryStateChange', ...)
219
+
220
+ ```typescript
221
+ addListener(eventName: 'batteryStateChange', listenerFunc: (event: BatteryStateChangeEvent) => void) => Promise<PluginListenerHandle>
222
+ ```
223
+
224
+ Listen for changes to the battery state of the device.
225
+
226
+ The device is only observed while at least one listener is attached.
227
+
228
+ On the web, this is only supported in browsers that implement the
229
+ [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API)
230
+ (Chromium-based browsers).
231
+
232
+ Only available on Android, iOS and Web.
233
+
234
+ | Param | Type |
235
+ | ------------------ | ----------------------------------------------------------------------------------------------- |
236
+ | **`eventName`** | <code>'batteryStateChange'</code> |
237
+ | **`listenerFunc`** | <code>(event: <a href="#batterystatechangeevent">BatteryStateChangeEvent</a>) =&gt; void</code> |
238
+
239
+ **Returns:** <code>Promise&lt;<a href="#pluginlistenerhandle">PluginListenerHandle</a>&gt;</code>
240
+
241
+ **Since:** 0.1.0
242
+
243
+ --------------------
244
+
245
+
246
+ ### addListener('lowPowerModeChange', ...)
247
+
248
+ ```typescript
249
+ addListener(eventName: 'lowPowerModeChange', listenerFunc: (event: LowPowerModeChangeEvent) => void) => Promise<PluginListenerHandle>
250
+ ```
251
+
252
+ Listen for changes to the low power mode of the device.
253
+
254
+ The device is only observed while at least one listener is attached.
255
+
256
+ Only available on Android and iOS.
257
+
258
+ | Param | Type |
259
+ | ------------------ | ----------------------------------------------------------------------------------------------- |
260
+ | **`eventName`** | <code>'lowPowerModeChange'</code> |
261
+ | **`listenerFunc`** | <code>(event: <a href="#lowpowermodechangeevent">LowPowerModeChangeEvent</a>) =&gt; void</code> |
262
+
263
+ **Returns:** <code>Promise&lt;<a href="#pluginlistenerhandle">PluginListenerHandle</a>&gt;</code>
264
+
265
+ **Since:** 0.1.0
266
+
267
+ --------------------
268
+
269
+
270
+ ### removeAllListeners()
271
+
272
+ ```typescript
273
+ removeAllListeners() => Promise<void>
274
+ ```
275
+
276
+ Remove all listeners for this plugin.
277
+
278
+ **Since:** 0.1.0
279
+
280
+ --------------------
281
+
282
+
283
+ ### Interfaces
284
+
285
+
286
+ #### GetBatteryLevelResult
287
+
288
+ | Prop | Type | Description | Since |
289
+ | ----------- | ------------------- | --------------------------------------------------------------------------- | ----- |
290
+ | **`level`** | <code>number</code> | The current battery level of the device as a value between `0.0` and `1.0`. | 0.1.0 |
291
+
292
+
293
+ #### GetBatteryStateResult
294
+
295
+ | Prop | Type | Description | Since |
296
+ | ----------- | ----------------------------------------------------- | ---------------------------------------- | ----- |
297
+ | **`state`** | <code><a href="#batterystate">BatteryState</a></code> | The current battery state of the device. | 0.1.0 |
298
+
299
+
300
+ #### IsLowPowerModeEnabledResult
301
+
302
+ | Prop | Type | Description | Since |
303
+ | ------------- | -------------------- | ------------------------------------------------ | ----- |
304
+ | **`enabled`** | <code>boolean</code> | Whether the low power mode is currently enabled. | 0.1.0 |
305
+
306
+
307
+ #### PluginListenerHandle
308
+
309
+ | Prop | Type |
310
+ | ------------ | ----------------------------------------- |
311
+ | **`remove`** | <code>() =&gt; Promise&lt;void&gt;</code> |
312
+
313
+
314
+ #### BatteryLevelChangeEvent
315
+
316
+ | Prop | Type | Description | Since |
317
+ | ----------- | ------------------- | --------------------------------------------------------------------------- | ----- |
318
+ | **`level`** | <code>number</code> | The current battery level of the device as a value between `0.0` and `1.0`. | 0.1.0 |
319
+
320
+
321
+ #### BatteryStateChangeEvent
322
+
323
+ | Prop | Type | Description | Since |
324
+ | ----------- | ----------------------------------------------------- | ---------------------------------------- | ----- |
325
+ | **`state`** | <code><a href="#batterystate">BatteryState</a></code> | The current battery state of the device. | 0.1.0 |
326
+
327
+
328
+ #### LowPowerModeChangeEvent
329
+
330
+ | Prop | Type | Description | Since |
331
+ | ------------- | -------------------- | ------------------------------------------------ | ----- |
332
+ | **`enabled`** | <code>boolean</code> | Whether the low power mode is currently enabled. | 0.1.0 |
333
+
334
+
335
+ ### Type Aliases
336
+
337
+
338
+ #### BatteryState
339
+
340
+ The battery state of the device.
341
+
342
+ - `charging`: The device is plugged into power and the battery is charging.
343
+ - `full`: The device is plugged into power and the battery is fully charged.
344
+ - `unplugged`: The device is not plugged into power and the battery is
345
+ discharging.
346
+ - `unknown`: The battery state could not be determined.
347
+
348
+ <code>'charging' | 'full' | 'unplugged' | 'unknown'</code>
349
+
350
+ </docgen-api>
351
+
352
+ ## Battery Information
353
+
354
+ Keep the following platform differences in mind when accessing battery information:
355
+
356
+ - **Android**: The battery level and state are read from the sticky [`ACTION_BATTERY_CHANGED`](https://developer.android.com/reference/android/content/Intent#ACTION_BATTERY_CHANGED) broadcast. The low power mode reflects the [power saver mode](https://developer.android.com/reference/android/os/PowerManager#isPowerSaveMode()) of the device.
357
+ - **iOS**: The battery level is not available on the iOS Simulator, so `getBatteryLevel()` rejects with an error there. Use a real device to test this method. The low power mode reflects the [Low Power Mode](https://support.apple.com/en-us/101604) of the device.
358
+ - **Web**: The battery level and state are only available in browsers that implement the [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API) (Chromium-based browsers). The low power mode is not available on the Web.
359
+
360
+ ## Changelog
361
+
362
+ See [CHANGELOG.md](https://github.com/capawesome-team/capacitor-plugins/blob/main/packages/battery/CHANGELOG.md).
363
+
364
+ ## License
365
+
366
+ See [LICENSE](https://github.com/capawesome-team/capacitor-plugins/blob/main/packages/battery/LICENSE).
@@ -0,0 +1,58 @@
1
+ ext {
2
+ junitVersion = project.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'
3
+ androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.7.1'
4
+ androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.3.0'
5
+ androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.7.0'
6
+ }
7
+
8
+ buildscript {
9
+ repositories {
10
+ google()
11
+ mavenCentral()
12
+ }
13
+ dependencies {
14
+ classpath 'com.android.tools.build:gradle:8.13.0'
15
+ }
16
+ }
17
+
18
+ apply plugin: 'com.android.library'
19
+
20
+ android {
21
+ namespace = "io.capawesome.capacitorjs.plugins.battery"
22
+ compileSdk = project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36
23
+ defaultConfig {
24
+ minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 24
25
+ targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 36
26
+ versionCode 1
27
+ versionName "1.0"
28
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
29
+ }
30
+ buildTypes {
31
+ release {
32
+ minifyEnabled false
33
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
34
+ }
35
+ }
36
+ lintOptions {
37
+ abortOnError = false
38
+ }
39
+ compileOptions {
40
+ sourceCompatibility JavaVersion.VERSION_21
41
+ targetCompatibility JavaVersion.VERSION_21
42
+ }
43
+ }
44
+
45
+ repositories {
46
+ google()
47
+ mavenCentral()
48
+ }
49
+
50
+
51
+ dependencies {
52
+ implementation fileTree(dir: 'libs', include: ['*.jar'])
53
+ implementation project(':capacitor-android')
54
+ implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
55
+ testImplementation "junit:junit:$junitVersion"
56
+ androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
57
+ androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
58
+ }
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,163 @@
1
+ package io.capawesome.capacitorjs.plugins.battery;
2
+
3
+ import android.content.BroadcastReceiver;
4
+ import android.content.Context;
5
+ import android.content.Intent;
6
+ import android.content.IntentFilter;
7
+ import android.os.BatteryManager;
8
+ import android.os.PowerManager;
9
+ import androidx.annotation.NonNull;
10
+ import androidx.annotation.Nullable;
11
+ import androidx.core.content.ContextCompat;
12
+ import io.capawesome.capacitorjs.plugins.battery.classes.CustomExceptions;
13
+ import io.capawesome.capacitorjs.plugins.battery.classes.events.BatteryLevelChangeEvent;
14
+ import io.capawesome.capacitorjs.plugins.battery.classes.events.BatteryStateChangeEvent;
15
+ import io.capawesome.capacitorjs.plugins.battery.classes.events.LowPowerModeChangeEvent;
16
+ import io.capawesome.capacitorjs.plugins.battery.classes.results.GetBatteryLevelResult;
17
+ import io.capawesome.capacitorjs.plugins.battery.classes.results.GetBatteryStateResult;
18
+ import io.capawesome.capacitorjs.plugins.battery.classes.results.IsLowPowerModeEnabledResult;
19
+ import io.capawesome.capacitorjs.plugins.battery.interfaces.NonEmptyResultCallback;
20
+
21
+ public class Battery {
22
+
23
+ @NonNull
24
+ private final BatteryPlugin plugin;
25
+
26
+ @NonNull
27
+ private final PowerManager powerManager;
28
+
29
+ private boolean isObserving = false;
30
+
31
+ private float lastLevel = -1;
32
+
33
+ @NonNull
34
+ private String lastState = "unknown";
35
+
36
+ private boolean lastLowPowerModeEnabled = false;
37
+
38
+ private final BroadcastReceiver batteryChangedReceiver = new BroadcastReceiver() {
39
+ @Override
40
+ public void onReceive(Context context, Intent intent) {
41
+ handleBatteryChanged(intent);
42
+ }
43
+ };
44
+
45
+ private final BroadcastReceiver powerSaveModeChangedReceiver = new BroadcastReceiver() {
46
+ @Override
47
+ public void onReceive(Context context, Intent intent) {
48
+ handlePowerSaveModeChanged();
49
+ }
50
+ };
51
+
52
+ public Battery(@NonNull BatteryPlugin plugin) {
53
+ this.plugin = plugin;
54
+ this.powerManager = (PowerManager) plugin.getContext().getSystemService(Context.POWER_SERVICE);
55
+ }
56
+
57
+ public void getBatteryLevel(@NonNull NonEmptyResultCallback<GetBatteryLevelResult> callback) {
58
+ float level = computeBatteryLevel(getBatteryStatusIntent());
59
+ if (level < 0) {
60
+ callback.error(CustomExceptions.BATTERY_LEVEL_UNAVAILABLE);
61
+ return;
62
+ }
63
+ callback.success(new GetBatteryLevelResult(level));
64
+ }
65
+
66
+ public void getBatteryState(@NonNull NonEmptyResultCallback<GetBatteryStateResult> callback) {
67
+ callback.success(new GetBatteryStateResult(computeBatteryState(getBatteryStatusIntent())));
68
+ }
69
+
70
+ public void isLowPowerModeEnabled(@NonNull NonEmptyResultCallback<IsLowPowerModeEnabledResult> callback) {
71
+ callback.success(new IsLowPowerModeEnabledResult(powerManager.isPowerSaveMode()));
72
+ }
73
+
74
+ public void startObserving() {
75
+ if (isObserving) {
76
+ return;
77
+ }
78
+ Intent intent = getBatteryStatusIntent();
79
+ lastLevel = computeBatteryLevel(intent);
80
+ lastState = computeBatteryState(intent);
81
+ lastLowPowerModeEnabled = powerManager.isPowerSaveMode();
82
+ ContextCompat.registerReceiver(
83
+ plugin.getContext(),
84
+ batteryChangedReceiver,
85
+ new IntentFilter(Intent.ACTION_BATTERY_CHANGED),
86
+ ContextCompat.RECEIVER_NOT_EXPORTED
87
+ );
88
+ ContextCompat.registerReceiver(
89
+ plugin.getContext(),
90
+ powerSaveModeChangedReceiver,
91
+ new IntentFilter(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED),
92
+ ContextCompat.RECEIVER_NOT_EXPORTED
93
+ );
94
+ isObserving = true;
95
+ }
96
+
97
+ public void stopObserving() {
98
+ if (!isObserving) {
99
+ return;
100
+ }
101
+ plugin.getContext().unregisterReceiver(batteryChangedReceiver);
102
+ plugin.getContext().unregisterReceiver(powerSaveModeChangedReceiver);
103
+ isObserving = false;
104
+ }
105
+
106
+ private float computeBatteryLevel(@Nullable Intent intent) {
107
+ if (intent == null) {
108
+ return -1;
109
+ }
110
+ int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
111
+ int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
112
+ if (level < 0 || scale <= 0) {
113
+ return -1;
114
+ }
115
+ return level / (float) scale;
116
+ }
117
+
118
+ @NonNull
119
+ private String computeBatteryState(@Nullable Intent intent) {
120
+ if (intent == null) {
121
+ return "unknown";
122
+ }
123
+ int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
124
+ int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
125
+ if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
126
+ return "charging";
127
+ }
128
+ if (status == BatteryManager.BATTERY_STATUS_FULL) {
129
+ return "full";
130
+ }
131
+ if (plugged == 0) {
132
+ return "unplugged";
133
+ }
134
+ return "unknown";
135
+ }
136
+
137
+ @Nullable
138
+ private Intent getBatteryStatusIntent() {
139
+ return plugin.getContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
140
+ }
141
+
142
+ private void handleBatteryChanged(@Nullable Intent intent) {
143
+ float level = computeBatteryLevel(intent);
144
+ if (level >= 0 && level != lastLevel) {
145
+ lastLevel = level;
146
+ plugin.notifyBatteryLevelChangeListeners(new BatteryLevelChangeEvent(level));
147
+ }
148
+ String state = computeBatteryState(intent);
149
+ if (!state.equals(lastState)) {
150
+ lastState = state;
151
+ plugin.notifyBatteryStateChangeListeners(new BatteryStateChangeEvent(state));
152
+ }
153
+ }
154
+
155
+ private void handlePowerSaveModeChanged() {
156
+ boolean enabled = powerManager.isPowerSaveMode();
157
+ if (enabled == lastLowPowerModeEnabled) {
158
+ return;
159
+ }
160
+ lastLowPowerModeEnabled = enabled;
161
+ plugin.notifyLowPowerModeChangeListeners(new LowPowerModeChangeEvent(enabled));
162
+ }
163
+ }