├── .editorconfig
├── .gitattributes
├── .gitignore
├── .watchmanconfig
├── .yarnrc
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── android
├── build.gradle
├── gradle.properties
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── reactnativebatteryoptimizationcheck
│ ├── BatteryOptimizationCheckModule.java
│ └── BatteryOptimizationCheckPackage.java
├── babel.config.js
├── example
├── .bundle
│ └── config
├── .ruby-version
├── Gemfile
├── Gemfile.lock
├── android
│ ├── app
│ │ ├── build.gradle
│ │ ├── debug.keystore
│ │ ├── proguard-rules.pro
│ │ └── src
│ │ │ ├── debug
│ │ │ ├── AndroidManifest.xml
│ │ │ └── java
│ │ │ │ └── com
│ │ │ │ └── example
│ │ │ │ └── reactnativebateryoptimizationcheck
│ │ │ │ └── ReactNativeFlipper.java
│ │ │ └── main
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── java
│ │ │ └── com
│ │ │ │ └── example
│ │ │ │ └── reactnativebateryoptimizationcheck
│ │ │ │ ├── MainActivity.java
│ │ │ │ ├── MainApplication.java
│ │ │ │ └── newarchitecture
│ │ │ │ ├── MainApplicationReactNativeHost.java
│ │ │ │ ├── components
│ │ │ │ └── MainComponentsRegistry.java
│ │ │ │ └── modules
│ │ │ │ └── MainApplicationTurboModuleManagerDelegate.java
│ │ │ ├── jni
│ │ │ ├── Android.mk
│ │ │ ├── MainApplicationModuleProvider.cpp
│ │ │ ├── MainApplicationModuleProvider.h
│ │ │ ├── MainApplicationTurboModuleManagerDelegate.cpp
│ │ │ ├── MainApplicationTurboModuleManagerDelegate.h
│ │ │ ├── MainComponentsRegistry.cpp
│ │ │ ├── MainComponentsRegistry.h
│ │ │ └── OnLoad.cpp
│ │ │ └── res
│ │ │ ├── drawable
│ │ │ └── rn_edit_text_material.xml
│ │ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ └── values
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ ├── build.gradle
│ ├── gradle.properties
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ └── settings.gradle
├── babel.config.js
├── index.js
├── ios
│ ├── BateryOptimizationCheckExample-Bridging-Header.h
│ ├── BateryOptimizationCheckExample.xcodeproj
│ │ ├── project.pbxproj
│ │ └── xcshareddata
│ │ │ └── xcschemes
│ │ │ └── BateryOptimizationCheckExample.xcscheme
│ ├── BateryOptimizationCheckExample.xcworkspace
│ │ ├── contents.xcworkspacedata
│ │ └── xcshareddata
│ │ │ └── IDEWorkspaceChecks.plist
│ ├── BateryOptimizationCheckExample
│ │ ├── AppDelegate.h
│ │ ├── AppDelegate.mm
│ │ ├── Images.xcassets
│ │ │ ├── AppIcon.appiconset
│ │ │ │ └── Contents.json
│ │ │ └── Contents.json
│ │ ├── Info.plist
│ │ ├── LaunchScreen.storyboard
│ │ └── main.m
│ ├── File.swift
│ ├── Podfile
│ └── Podfile.lock
├── metro.config.js
├── package.json
├── react-native.config.js
├── src
│ └── App.js
└── yarn.lock
├── package.json
├── scripts
└── bootstrap.js
├── src
├── __tests__
│ └── index.test.tsx
├── img
│ └── doze.png
└── index.js
├── tsconfig.build.json
└── tsconfig.json
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig helps developers define and maintain consistent
2 | # coding styles between different editors and IDEs
3 | # editorconfig.org
4 |
5 | root = true
6 |
7 | [*]
8 |
9 | indent_style = space
10 | indent_size = 2
11 |
12 | end_of_line = lf
13 | charset = utf-8
14 | trim_trailing_whitespace = true
15 | insert_final_newline = true
16 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pbxproj -text
2 | # specific for windows script files
3 | *.bat text eol=crlf
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # XDE
6 | .expo/
7 |
8 | # VSCode
9 | .vscode/
10 | jsconfig.json
11 |
12 | # Xcode
13 | #
14 | build/
15 | *.pbxuser
16 | !default.pbxuser
17 | *.mode1v3
18 | !default.mode1v3
19 | *.mode2v3
20 | !default.mode2v3
21 | *.perspectivev3
22 | !default.perspectivev3
23 | xcuserdata
24 | *.xccheckout
25 | *.moved-aside
26 | DerivedData
27 | *.hmap
28 | *.ipa
29 | *.xcuserstate
30 | project.xcworkspace
31 |
32 | # Android/IJ
33 | #
34 | .classpath
35 | .cxx
36 | .gradle
37 | .idea
38 | .project
39 | .settings
40 | local.properties
41 | android.iml
42 |
43 | # Cocoapods
44 | #
45 | example/ios/Pods
46 |
47 | # Ruby
48 | example/vendor/
49 |
50 | # node.js
51 | #
52 | node_modules/
53 | npm-debug.log
54 | yarn-debug.log
55 | yarn-error.log
56 |
57 | # BUCK
58 | buck-out/
59 | \.buckd/
60 | android/app/libs
61 | android/keystores/debug.keystore
62 |
63 | # Expo
64 | .expo/*
65 |
66 | # generated by bob
67 | lib/
68 | yarn.lock
69 |
--------------------------------------------------------------------------------
/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/.yarnrc:
--------------------------------------------------------------------------------
1 | # Override Yarn command so we can automatically setup the repo on running `yarn`
2 |
3 | yarn-path "scripts/bootstrap.js"
4 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project.
4 |
5 | ## Development workflow
6 |
7 | To get started with the project, run `yarn` in the root directory to install the required dependencies for each package:
8 |
9 | ```sh
10 | yarn
11 | ```
12 |
13 | > While it's possible to use [`npm`](https://github.com/npm/cli), the tooling is built around [`yarn`](https://classic.yarnpkg.com/), so you'll have an easier time if you use `yarn` for development.
14 |
15 | While developing, you can run the [example app](/example/) to test your changes. Any changes you make in your library's JavaScript code will be reflected in the example app without a rebuild. If you change any native code, then you'll need to rebuild the example app.
16 |
17 | To start the packager:
18 |
19 | ```sh
20 | yarn example start
21 | ```
22 |
23 | To run the example app on Android:
24 |
25 | ```sh
26 | yarn example android
27 | ```
28 |
29 | Make sure your code passes TypeScript and ESLint. Run the following to verify:
30 |
31 | ```sh
32 | yarn typescript
33 | yarn lint
34 | ```
35 |
36 | To fix formatting errors, run the following:
37 |
38 | ```sh
39 | yarn lint --fix
40 | ```
41 |
42 | Remember to add tests for your change if possible. Run the unit tests by:
43 |
44 | ```sh
45 | yarn test
46 | ```
47 | To edit the Kotlin files, open `example/android` in Android studio and find the source files at `reactnativebatteryoptimizationcheck` under `Android`.
48 | ### Commit message convention
49 |
50 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
51 |
52 | - `fix`: bug fixes, e.g. fix crash due to deprecated method.
53 | - `feat`: new features, e.g. add new method to the module.
54 | - `refactor`: code refactor, e.g. migrate from class components to hooks.
55 | - `docs`: changes into documentation, e.g. add usage example for the module..
56 | - `test`: adding or updating tests, e.g. add integration tests using detox.
57 | - `chore`: tooling changes, e.g. change CI config.
58 |
59 | Our pre-commit hooks verify that your commit message matches this format when committing.
60 |
61 | ### Linting and tests
62 |
63 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
64 |
65 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing.
66 |
67 | Our pre-commit hooks verify that the linter and tests pass when committing.
68 |
69 | ### Publishing to npm
70 |
71 | We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc.
72 |
73 | To publish new versions, run the following:
74 |
75 | ```sh
76 | yarn release
77 | ```
78 |
79 | ### Scripts
80 |
81 | The `package.json` file contains various scripts for common tasks:
82 |
83 | - `yarn bootstrap`: setup project by installing all dependencies and pods.
84 | - `yarn typescript`: type-check files with TypeScript.
85 | - `yarn lint`: lint files with ESLint.
86 | - `yarn test`: run unit tests with Jest.
87 | - `yarn example start`: start the Metro server for the example app.
88 | - `yarn example android`: run the example app on Android.
89 | - `yarn example ios`: run the example app on iOS.
90 |
91 | ### Sending a pull request
92 |
93 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github).
94 |
95 | When you're sending a pull request:
96 |
97 | - Prefer small pull requests focused on one change.
98 | - Verify that linters and tests are passing.
99 | - Review the documentation to make sure it looks good.
100 | - Follow the pull request template when opening a pull request.
101 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
102 |
103 | ## Code of Conduct
104 |
105 | ### Our Pledge
106 |
107 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
108 |
109 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
110 |
111 | ### Our Standards
112 |
113 | Examples of behavior that contributes to a positive environment for our community include:
114 |
115 | - Demonstrating empathy and kindness toward other people
116 | - Being respectful of differing opinions, viewpoints, and experiences
117 | - Giving and gracefully accepting constructive feedback
118 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
119 | - Focusing on what is best not just for us as individuals, but for the overall community
120 |
121 | Examples of unacceptable behavior include:
122 |
123 | - The use of sexualized language or imagery, and sexual attention or
124 | advances of any kind
125 | - Trolling, insulting or derogatory comments, and personal or political attacks
126 | - Public or private harassment
127 | - Publishing others' private information, such as a physical or email
128 | address, without their explicit permission
129 | - Other conduct which could reasonably be considered inappropriate in a
130 | professional setting
131 |
132 | ### Enforcement Responsibilities
133 |
134 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
135 |
136 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
137 |
138 | ### Scope
139 |
140 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
141 |
142 | ### Enforcement
143 |
144 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly.
145 |
146 | All community leaders are obligated to respect the privacy and security of the reporter of any incident.
147 |
148 | ### Enforcement Guidelines
149 |
150 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
151 |
152 | #### 1. Correction
153 |
154 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
155 |
156 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
157 |
158 | #### 2. Warning
159 |
160 | **Community Impact**: A violation through a single incident or series of actions.
161 |
162 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
163 |
164 | #### 3. Temporary Ban
165 |
166 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
167 |
168 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
169 |
170 | #### 4. Permanent Ban
171 |
172 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
173 |
174 | **Consequence**: A permanent ban from any sort of public interaction within the community.
175 |
176 | ### Attribution
177 |
178 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
179 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
180 |
181 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
182 |
183 | [homepage]: https://www.contributor-covenant.org
184 |
185 | For answers to common questions about this code of conduct, see the FAQ at
186 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
187 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 losthakkun
4 | Permission is hereby granted, free of charge, to any person obtaining a copy
5 | of this software and associated documentation files (the "Software"), to deal
6 | in the Software without restriction, including without limitation the rights
7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | copies of the Software, and to permit persons to whom the Software is
9 | furnished to do so, subject to the following conditions:
10 |
11 | The above copyright notice and this permission notice shall be included in all
12 | copies or substantial portions of the Software.
13 |
14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 | SOFTWARE.
21 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-native-battery-optimization-check
2 | A react-native solution to check if your app runs under battery optimization on Android devices and makes it easy for the user to disable it.
3 |
4 | Base on [@rasheedk/react-native-disable-battery-optimizations-android](https://github.com/rasheedk/react-native-disable-battery-optimizations-android) which is no longer supported in react-native >= 0.63.0
5 |
6 | ## Why?
7 |
8 | Android devices with API level greater than 23 (Android 6 — Marshmallow) comes with a battery optimization feature in an attempt to reduce battery consumption.
9 |
10 | This feature implements a Doze mode which prevents the continuous use of resources by applications while the device is on Standby.
11 |
12 | ## Doze mode and App Standby
13 |
14 | If a user leaves a device unplugged and stationary for a period of time, with the screen off, the device enters Doze mode. In Doze mode, the system attempts to conserve battery by restricting apps’ access to network and CPU-intensive services.
15 |
16 |
17 |
18 |
19 |
20 | ##### Photo from Android developer website
21 |
22 |
23 |
24 | At the conclusion of each maintenance window, the system again enters Doze, suspending network access and deferring jobs, syncs, and alarms. Over time, the system schedules maintenance windows less and less frequently, helping to reduce battery consumption in cases of longer-term inactivity when the device is not connected to a charger.
25 |
26 | As soon as the user wakes the device by moving it, turning on the screen, or connecting a charger, the system exits Doze and all apps return to normal activity.
27 |
28 | Here is the list of main restrictions that apply to your application in doze mode:
29 |
30 | - The system ignores wake locks;
31 | - A network connection is not available;
32 | - The system doesn’t perform WiFi, WiFi RTT, and BLE scans;
33 | - Standard AlarmManager alarms will be rescheduled;
34 | - The system doesn’t allow JobScheduler and WorkManager.
35 |
36 | Read more about [Optimize for Doze and App Standby](https://developer.android.com/training/monitoring-device-state/doze-standby).
37 |
38 | ## Battery optimization
39 |
40 | Battery optimization allows you to put your app into the whitelist. By default, it is turned off. Apps available in the whitelist are partially exempt from Doze and App Standby optimizations. This doesn’t mean they have full access to and could perform tasks during the doze mode. An app that is whitelisted can use the network and hold partial wake locks during Doze and App Standby. However, other restrictions like jobs being differed, standard alarm triggers are still imposed.
41 |
42 |
43 |
44 | # Installation
45 |
46 | ```sh
47 | $ yarn add react-native-battery-optimization-check
48 | ```
49 |
50 | Link is automatic on react native >= 0.60
51 |
52 | ### For manual linking :
53 |
54 | ```sh
55 | $ react-native link react-native-battery-optimization-check
56 | ```
57 |
58 | # Usage
59 |
60 | There are 3 functions on this library:
61 |
62 | ## BatteryOptEnabled()
63 |
64 | - Returns ***true*** if battery optimization is enabled for your app.
65 | - Returns ***false*** if battery optimization is disabled for your app.
66 | - Returns ***false*** if battery optimization is not available on the device or if the app is not running on Android.
67 |
68 |
69 |
70 | Example:
71 | ```js
72 | import { BatteryOptEnabled } from "react-native-battery-optimization-check";
73 |
74 | BatteryOptEnabled().then((isEnabled)=>{
75 | // returns promise
76 | const result = isEnabled ? "enabled" : "disabled";
77 | // ...
78 | });
79 | ```
80 |
81 | ## OpenOptimizationSettings()
82 |
83 | - This function is only available on Android devices with API level greater than 23 (Android 6 — Marshmallow).
84 | - Opens the battery optimization settings page with a list of all apps that are available in the whitelist. You can also add or remove apps from the whitelist.
85 | - This method uses an intent with ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS which is allowed to publish your app in Playstore without restrictions in this regard.
86 |
87 |
88 |
89 | Example:
90 | ```js
91 | import { OpenOptimizationSettings, BatteryOptEnabled } from "react-native-battery-optimization-check";
92 |
93 | BatteryOptEnabled().then((isEnabled)=>{
94 | // returns promise
95 | if (isEnabled) {
96 | // if battery optimization is enabled, request to disable it.
97 | OpenOptimizationSettings();
98 | // ...
99 | }
100 | });
101 | ```
102 |
103 | ## RequestDisableOptimization()
104 |
105 | **CAUTION!** Google Play policies prohibit apps from requesting direct exemption from Power Management features in Android 6.0+ (Doze and App Standby) unless the core function of the app is adversely affected.
106 |
107 | Read more about [Acceptable use cases for exemption](https://developer.android.com/training/monitoring-device-state/doze-standby#exemption-cases).
108 |
109 | - This function is only available on Android devices with API level greater than 23 (Android 6 — Marshmallow).
110 | - This function will request the user to disable battery optimization for your app.
111 | - A system dialog will be shown to the user to disable battery optimization directly from the app.
112 |
113 |
114 |
115 | Example:
116 | ```js
117 | import { RequestDisableOptimization, BatteryOptEnabled } from "react-native-battery-optimization-check";
118 |
119 | BatteryOptEnabled().then((isEnabled)=>{
120 | // returns promise
121 | if (isEnabled) {
122 | // if battery optimization is enabled, request to disable it.
123 | RequestDisableOptimization();
124 | // ...
125 | }
126 | });
127 | ```
128 |
129 | # Example App
130 |
131 | In order to run the example app, you need to install the library and then go to the /example folder and run the following commands:
132 |
133 | 1. instal and link node_modules
134 | ```sh
135 | $ yarn
136 | ```
137 |
138 | 2. run the app
139 | ```sh
140 | $ react-native run-android
141 | ```
142 |
143 | ## Contributing
144 |
145 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
146 |
147 | ## License
148 |
149 | MIT
150 |
151 | ---
152 |
153 | Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
154 |
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | }
6 |
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:3.5.3'
9 | }
10 | }
11 |
12 | def isNewArchitectureEnabled() {
13 | return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true"
14 | }
15 |
16 | apply plugin: 'com.android.library'
17 |
18 | if (isNewArchitectureEnabled()) {
19 | apply plugin: 'com.facebook.react'
20 | }
21 |
22 | def getExtOrDefault(name) {
23 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['BatteryOptimizationCheck_' + name]
24 | }
25 |
26 | def getExtOrIntegerDefault(name) {
27 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties['BatteryOptimizationCheck_' + name]).toInteger()
28 | }
29 |
30 | android {
31 | namespace "com.reactnativebatteryoptimizationcheck"
32 | compileSdkVersion getExtOrIntegerDefault('compileSdkVersion')
33 |
34 | defaultConfig {
35 | minSdkVersion getExtOrIntegerDefault('minSdkVersion')
36 | targetSdkVersion getExtOrIntegerDefault('targetSdkVersion')
37 | buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
38 | }
39 | buildTypes {
40 | release {
41 | minifyEnabled false
42 | }
43 | }
44 |
45 | lintOptions {
46 | disable 'GradleCompatible'
47 | }
48 |
49 | compileOptions {
50 | sourceCompatibility JavaVersion.VERSION_1_8
51 | targetCompatibility JavaVersion.VERSION_1_8
52 | }
53 | }
54 |
55 | repositories {
56 | mavenCentral()
57 | google()
58 |
59 | def found = false
60 | def defaultDir = null
61 | def androidSourcesName = 'React Native sources'
62 |
63 | if (rootProject.ext.has('reactNativeAndroidRoot')) {
64 | defaultDir = rootProject.ext.get('reactNativeAndroidRoot')
65 | } else {
66 | defaultDir = new File(
67 | projectDir,
68 | '/../../../node_modules/react-native/android'
69 | )
70 | }
71 |
72 | if (defaultDir.exists()) {
73 | maven {
74 | url defaultDir.toString()
75 | name androidSourcesName
76 | }
77 |
78 | logger.info(":${project.name}:reactNativeAndroidRoot ${defaultDir.canonicalPath}")
79 | found = true
80 | } else {
81 | def parentDir = rootProject.projectDir
82 |
83 | 1.upto(5, {
84 | if (found) return true
85 | parentDir = parentDir.parentFile
86 |
87 | def androidSourcesDir = new File(
88 | parentDir,
89 | 'node_modules/react-native'
90 | )
91 |
92 | def androidPrebuiltBinaryDir = new File(
93 | parentDir,
94 | 'node_modules/react-native/android'
95 | )
96 |
97 | if (androidPrebuiltBinaryDir.exists()) {
98 | maven {
99 | url androidPrebuiltBinaryDir.toString()
100 | name androidSourcesName
101 | }
102 |
103 | logger.info(":${project.name}:reactNativeAndroidRoot ${androidPrebuiltBinaryDir.canonicalPath}")
104 | found = true
105 | } else if (androidSourcesDir.exists()) {
106 | maven {
107 | url androidSourcesDir.toString()
108 | name androidSourcesName
109 | }
110 |
111 | logger.info(":${project.name}:reactNativeAndroidRoot ${androidSourcesDir.canonicalPath}")
112 | found = true
113 | }
114 | })
115 | }
116 |
117 | if (!found) {
118 | throw new GradleException(
119 | "${project.name}: unable to locate React Native android sources. " +
120 | "Ensure you have you installed React Native as a dependency in your project and try again."
121 | )
122 | }
123 | }
124 |
125 |
126 | dependencies {
127 | //noinspection GradleDynamicVersion
128 | implementation "com.facebook.react:react-native:+"
129 | // From node_modules
130 | }
131 |
132 | if (isNewArchitectureEnabled()) {
133 | react {
134 | jsRootDir = file("../src/")
135 | libraryName = "BatteryOptimizationCheck"
136 | codegenJavaPackageName = "com.reactnativebatteryoptimizationcheck"
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/android/gradle.properties:
--------------------------------------------------------------------------------
1 | BatteryOptimizationCheck_kotlinVersion=1.7.0
2 | BatteryOptimizationCheck_minSdkVersion=21
3 | BatteryOptimizationCheck_targetSdkVersion=31
4 | BatteryOptimizationCheck_compileSdkVersion=31
5 | BatteryOptimizationCheck_ndkversion=21.4.7075529
6 |
--------------------------------------------------------------------------------
/android/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/android/src/main/java/com/reactnativebatteryoptimizationcheck/BatteryOptimizationCheckModule.java:
--------------------------------------------------------------------------------
1 | package com.reactnativebatteryoptimizationcheck;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | import com.facebook.react.bridge.Promise;
6 | import com.facebook.react.bridge.ReactApplicationContext;
7 | import com.facebook.react.bridge.ReactContextBaseJavaModule;
8 | import com.facebook.react.bridge.ReactMethod;
9 | import com.facebook.react.module.annotations.ReactModule;
10 |
11 | import android.annotation.SuppressLint;
12 | import android.content.Context;
13 | import android.net.Uri;
14 | import android.os.Build;
15 | import android.content.Intent;
16 | import android.os.PowerManager;
17 | import android.provider.Settings;
18 |
19 | @ReactModule(name = BatteryOptimizationCheckModule.NAME)
20 | public class BatteryOptimizationCheckModule extends ReactContextBaseJavaModule {
21 | public static final String NAME = "BatteryOptimizationCheck";
22 |
23 | private final ReactApplicationContext reactContext;
24 |
25 | public BatteryOptimizationCheckModule(ReactApplicationContext reactContext) {
26 | super(reactContext);
27 | this.reactContext = reactContext;
28 | }
29 |
30 | @Override
31 | @NonNull
32 | public String getName() {
33 | return NAME;
34 | }
35 |
36 | @ReactMethod
37 | public void isBatteryOptEnabled(Promise promise) {
38 | if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
39 | String packageName = reactContext.getPackageName();
40 | PowerManager pm = (PowerManager) reactContext.getSystemService(Context.POWER_SERVICE);
41 | if (!pm.isIgnoringBatteryOptimizations(packageName)) {
42 | promise.resolve(true);
43 | return;
44 | }
45 | }
46 | promise.resolve(false);
47 | }
48 |
49 | @SuppressLint("BatteryLife")
50 | @ReactMethod
51 | public void openRequestDisableOptimization() {
52 | if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
53 | String packageName = reactContext.getPackageName();
54 | Intent intent = new Intent();
55 | intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
56 | intent.setData(Uri.parse("package:" + packageName));
57 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
58 | reactContext.startActivity(intent);
59 | }
60 | }
61 |
62 | @ReactMethod
63 | public void openOptimizationSettings() {
64 | if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
65 | Intent intent = new Intent();
66 | intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
67 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
68 | reactContext.startActivity(intent);
69 | }
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/android/src/main/java/com/reactnativebatteryoptimizationcheck/BatteryOptimizationCheckPackage.java:
--------------------------------------------------------------------------------
1 | package com.reactnativebatteryoptimizationcheck;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | import com.facebook.react.ReactPackage;
6 | import com.facebook.react.bridge.NativeModule;
7 | import com.facebook.react.bridge.ReactApplicationContext;
8 | import com.facebook.react.uimanager.ViewManager;
9 |
10 | import java.util.ArrayList;
11 | import java.util.Collections;
12 | import java.util.List;
13 |
14 | public class BatteryOptimizationCheckPackage implements ReactPackage {
15 | @NonNull
16 | @Override
17 | public List createNativeModules(@NonNull ReactApplicationContext reactContext) {
18 | List modules = new ArrayList<>();
19 | modules.add(new BatteryOptimizationCheckModule(reactContext));
20 | return modules;
21 | }
22 |
23 | @NonNull
24 | @Override
25 | public List createViewManagers(@NonNull ReactApplicationContext reactContext) {
26 | return Collections.emptyList();
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:metro-react-native-babel-preset'],
3 | };
4 |
--------------------------------------------------------------------------------
/example/.bundle/config:
--------------------------------------------------------------------------------
1 | BUNDLE_PATH: "vendor/bundle"
2 | BUNDLE_FORCE_RUBY_PLATFORM: 1
3 |
--------------------------------------------------------------------------------
/example/.ruby-version:
--------------------------------------------------------------------------------
1 | 2.7.4
2 |
--------------------------------------------------------------------------------
/example/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
4 | ruby '2.7.4'
5 |
6 | gem 'cocoapods', '~> 1.11', '>= 1.11.2'
7 |
--------------------------------------------------------------------------------
/example/Gemfile.lock:
--------------------------------------------------------------------------------
1 | GEM
2 | remote: https://rubygems.org/
3 | specs:
4 | CFPropertyList (3.0.5)
5 | rexml
6 | activesupport (6.1.5.1)
7 | concurrent-ruby (~> 1.0, >= 1.0.2)
8 | i18n (>= 1.6, < 2)
9 | minitest (>= 5.1)
10 | tzinfo (~> 2.0)
11 | zeitwerk (~> 2.3)
12 | addressable (2.8.0)
13 | public_suffix (>= 2.0.2, < 5.0)
14 | algoliasearch (1.27.5)
15 | httpclient (~> 2.8, >= 2.8.3)
16 | json (>= 1.5.1)
17 | atomos (0.1.3)
18 | claide (1.1.0)
19 | cocoapods (1.11.3)
20 | addressable (~> 2.8)
21 | claide (>= 1.0.2, < 2.0)
22 | cocoapods-core (= 1.11.3)
23 | cocoapods-deintegrate (>= 1.0.3, < 2.0)
24 | cocoapods-downloader (>= 1.4.0, < 2.0)
25 | cocoapods-plugins (>= 1.0.0, < 2.0)
26 | cocoapods-search (>= 1.0.0, < 2.0)
27 | cocoapods-trunk (>= 1.4.0, < 2.0)
28 | cocoapods-try (>= 1.1.0, < 2.0)
29 | colored2 (~> 3.1)
30 | escape (~> 0.0.4)
31 | fourflusher (>= 2.3.0, < 3.0)
32 | gh_inspector (~> 1.0)
33 | molinillo (~> 0.8.0)
34 | nap (~> 1.0)
35 | ruby-macho (>= 1.0, < 3.0)
36 | xcodeproj (>= 1.21.0, < 2.0)
37 | cocoapods-core (1.11.3)
38 | activesupport (>= 5.0, < 7)
39 | addressable (~> 2.8)
40 | algoliasearch (~> 1.0)
41 | concurrent-ruby (~> 1.1)
42 | fuzzy_match (~> 2.0.4)
43 | nap (~> 1.0)
44 | netrc (~> 0.11)
45 | public_suffix (~> 4.0)
46 | typhoeus (~> 1.0)
47 | cocoapods-deintegrate (1.0.5)
48 | cocoapods-downloader (1.6.3)
49 | cocoapods-plugins (1.0.0)
50 | nap
51 | cocoapods-search (1.0.1)
52 | cocoapods-trunk (1.6.0)
53 | nap (>= 0.8, < 2.0)
54 | netrc (~> 0.11)
55 | cocoapods-try (1.2.0)
56 | colored2 (3.1.2)
57 | concurrent-ruby (1.1.10)
58 | escape (0.0.4)
59 | ethon (0.15.0)
60 | ffi (>= 1.15.0)
61 | ffi (1.15.5)
62 | fourflusher (2.3.1)
63 | fuzzy_match (2.0.4)
64 | gh_inspector (1.1.3)
65 | httpclient (2.8.3)
66 | i18n (1.10.0)
67 | concurrent-ruby (~> 1.0)
68 | json (2.6.1)
69 | minitest (5.15.0)
70 | molinillo (0.8.0)
71 | nanaimo (0.3.0)
72 | nap (1.1.0)
73 | netrc (0.11.0)
74 | public_suffix (4.0.7)
75 | rexml (3.2.5)
76 | ruby-macho (2.5.1)
77 | typhoeus (1.4.0)
78 | ethon (>= 0.9.0)
79 | tzinfo (2.0.4)
80 | concurrent-ruby (~> 1.0)
81 | xcodeproj (1.21.0)
82 | CFPropertyList (>= 2.3.3, < 4.0)
83 | atomos (~> 0.1.3)
84 | claide (>= 1.0.2, < 2.0)
85 | colored2 (~> 3.1)
86 | nanaimo (~> 0.3.0)
87 | rexml (~> 3.2.4)
88 | zeitwerk (2.5.4)
89 |
90 | PLATFORMS
91 | ruby
92 |
93 | DEPENDENCIES
94 | cocoapods (~> 1.11, >= 1.11.2)
95 |
96 | RUBY VERSION
97 | ruby 2.7.4p191
98 |
99 | BUNDLED WITH
100 | 2.2.27
101 |
--------------------------------------------------------------------------------
/example/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 |
3 | import com.android.build.OutputFile
4 | import org.apache.tools.ant.taskdefs.condition.Os
5 |
6 | /**
7 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
8 | * and bundleReleaseJsAndAssets).
9 | * These basically call `react-native bundle` with the correct arguments during the Android build
10 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
11 | * bundle directly from the development server. Below you can see all the possible configurations
12 | * and their defaults. If you decide to add a configuration block, make sure to add it before the
13 | * `apply from: "../../node_modules/react-native/react.gradle"` line.
14 | *
15 | * project.ext.react = [
16 | * // the name of the generated asset file containing your JS bundle
17 | * bundleAssetName: "index.android.bundle",
18 | *
19 | * // the entry file for bundle generation. If none specified and
20 | * // "index.android.js" exists, it will be used. Otherwise "index.js" is
21 | * // default. Can be overridden with ENTRY_FILE environment variable.
22 | * entryFile: "index.android.js",
23 | *
24 | * // https://reactnative.dev/docs/performance#enable-the-ram-format
25 | * bundleCommand: "ram-bundle",
26 | *
27 | * // whether to bundle JS and assets in debug mode
28 | * bundleInDebug: false,
29 | *
30 | * // whether to bundle JS and assets in release mode
31 | * bundleInRelease: true,
32 | *
33 | * // whether to bundle JS and assets in another build variant (if configured).
34 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
35 | * // The configuration property can be in the following formats
36 | * // 'bundleIn${productFlavor}${buildType}'
37 | * // 'bundleIn${buildType}'
38 | * // bundleInFreeDebug: true,
39 | * // bundleInPaidRelease: true,
40 | * // bundleInBeta: true,
41 | *
42 | * // whether to disable dev mode in custom build variants (by default only disabled in release)
43 | * // for example: to disable dev mode in the staging build type (if configured)
44 | * devDisabledInStaging: true,
45 | * // The configuration property can be in the following formats
46 | * // 'devDisabledIn${productFlavor}${buildType}'
47 | * // 'devDisabledIn${buildType}'
48 | *
49 | * // the root of your project, i.e. where "package.json" lives
50 | * root: "../../",
51 | *
52 | * // where to put the JS bundle asset in debug mode
53 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
54 | *
55 | * // where to put the JS bundle asset in release mode
56 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release",
57 | *
58 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
59 | * // require('./image.png')), in debug mode
60 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
61 | *
62 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
63 | * // require('./image.png')), in release mode
64 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
65 | *
66 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means
67 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
68 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle
69 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
70 | * // for example, you might want to remove it from here.
71 | * inputExcludes: ["android/**", "ios/**"],
72 | *
73 | * // override which node gets called and with what additional arguments
74 | * nodeExecutableAndArgs: ["node"],
75 | *
76 | * // supply additional arguments to the packager
77 | * extraPackagerArgs: []
78 | * ]
79 | */
80 |
81 | project.ext.react = [
82 | enableHermes: true, // clean and rebuild if changing
83 | ]
84 |
85 | apply from: "../../node_modules/react-native/react.gradle"
86 |
87 | /**
88 | * Set this to true to create two separate APKs instead of one:
89 | * - An APK that only works on ARM devices
90 | * - An APK that only works on x86 devices
91 | * The advantage is the size of the APK is reduced by about 4MB.
92 | * Upload all the APKs to the Play Store and people will download
93 | * the correct one based on the CPU architecture of their device.
94 | */
95 | def enableSeparateBuildPerCPUArchitecture = false
96 |
97 | /**
98 | * Run Proguard to shrink the Java bytecode in release builds.
99 | */
100 | def enableProguardInReleaseBuilds = false
101 |
102 | /**
103 | * The preferred build flavor of JavaScriptCore.
104 | *
105 | * For example, to use the international variant, you can use:
106 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
107 | *
108 | * The international variant includes ICU i18n library and necessary data
109 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
110 | * give correct results when using with locales other than en-US. Note that
111 | * this variant is about 6MiB larger per architecture than default.
112 | */
113 | def jscFlavor = 'org.webkit:android-jsc:+'
114 |
115 | /**
116 | * Whether to enable the Hermes VM.
117 | *
118 | * This should be set on project.ext.react and that value will be read here. If it is not set
119 | * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
120 | * and the benefits of using Hermes will therefore be sharply reduced.
121 | */
122 | def enableHermes = project.ext.react.get("enableHermes", false);
123 |
124 | /**
125 | * Architectures to build native code for.
126 | */
127 | def reactNativeArchitectures() {
128 | def value = project.getProperties().get("reactNativeArchitectures")
129 | return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
130 | }
131 |
132 | android {
133 | ndkVersion rootProject.ext.ndkVersion
134 |
135 | compileSdkVersion rootProject.ext.compileSdkVersion
136 |
137 | defaultConfig {
138 | applicationId "com.example.reactnativebatteryoptimizationcheck"
139 | minSdkVersion rootProject.ext.minSdkVersion
140 | targetSdkVersion rootProject.ext.targetSdkVersion
141 | versionCode 1
142 | versionName "1.0"
143 | buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
144 |
145 | if (isNewArchitectureEnabled()) {
146 | // We configure the NDK build only if you decide to opt-in for the New Architecture.
147 | externalNativeBuild {
148 | ndkBuild {
149 | arguments "APP_PLATFORM=android-21",
150 | "APP_STL=c++_shared",
151 | "NDK_TOOLCHAIN_VERSION=clang",
152 | "GENERATED_SRC_DIR=$buildDir/generated/source",
153 | "PROJECT_BUILD_DIR=$buildDir",
154 | "REACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
155 | "REACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build"
156 | cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1"
157 | cppFlags "-std=c++17"
158 | // Make sure this target name is the same you specify inside the
159 | // src/main/jni/Android.mk file for the `LOCAL_MODULE` variable.
160 | targets "example_appmodules"
161 | // Fix for windows limit on number of character in file paths and in command lines
162 | if (Os.isFamily(Os.FAMILY_WINDOWS)) {
163 | arguments "NDK_APP_SHORT_COMMANDS=true"
164 | }
165 | }
166 | }
167 | if (!enableSeparateBuildPerCPUArchitecture) {
168 | ndk {
169 | abiFilters (*reactNativeArchitectures())
170 | }
171 | }
172 | }
173 | }
174 |
175 | if (isNewArchitectureEnabled()) {
176 | // We configure the NDK build only if you decide to opt-in for the New Architecture.
177 | externalNativeBuild {
178 | ndkBuild {
179 | path "$projectDir/src/main/jni/Android.mk"
180 | }
181 | }
182 | def reactAndroidProjectDir = project(':ReactAndroid').projectDir
183 | def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
184 | dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
185 | from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
186 | into("$buildDir/react-ndk/exported")
187 | }
188 | def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
189 | dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
190 | from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
191 | into("$buildDir/react-ndk/exported")
192 | }
193 | afterEvaluate {
194 | // If you wish to add a custom TurboModule or component locally,
195 | // you should uncomment this line.
196 | // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
197 | preDebugBuild.dependsOn(packageReactNdkDebugLibs)
198 | preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)
199 |
200 | // Due to a bug inside AGP, we have to explicitly set a dependency
201 | // between configureNdkBuild* tasks and the preBuild tasks.
202 | // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
203 | configureNdkBuildRelease.dependsOn(preReleaseBuild)
204 | configureNdkBuildDebug.dependsOn(preDebugBuild)
205 | reactNativeArchitectures().each { architecture ->
206 | tasks.findByName("configureNdkBuildDebug[${architecture}]")?.configure {
207 | dependsOn("preDebugBuild")
208 | }
209 | tasks.findByName("configureNdkBuildRelease[${architecture}]")?.configure {
210 | dependsOn("preReleaseBuild")
211 | }
212 | }
213 | }
214 | }
215 |
216 | splits {
217 | abi {
218 | reset()
219 | enable enableSeparateBuildPerCPUArchitecture
220 | universalApk false // If true, also generate a universal APK
221 | include (*reactNativeArchitectures())
222 | }
223 | }
224 | signingConfigs {
225 | debug {
226 | storeFile file('debug.keystore')
227 | storePassword 'android'
228 | keyAlias 'androiddebugkey'
229 | keyPassword 'android'
230 | }
231 | }
232 | buildTypes {
233 | debug {
234 | signingConfig signingConfigs.debug
235 | }
236 | release {
237 | // Caution! In production, you need to generate your own keystore file.
238 | // see https://reactnative.dev/docs/signed-apk-android.
239 | signingConfig signingConfigs.debug
240 | minifyEnabled enableProguardInReleaseBuilds
241 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
242 | }
243 | }
244 |
245 | // applicationVariants are e.g. debug, release
246 | applicationVariants.all { variant ->
247 | variant.outputs.each { output ->
248 | // For each separate APK per architecture, set a unique version code as described here:
249 | // https://developer.android.com/studio/build/configure-apk-splits.html
250 | // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
251 | def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
252 | def abi = output.getFilter(OutputFile.ABI)
253 | if (abi != null) { // null for the universal-debug, universal-release variants
254 | output.versionCodeOverride =
255 | defaultConfig.versionCode * 1000 + versionCodes.get(abi)
256 | }
257 |
258 | }
259 | }
260 | }
261 |
262 | dependencies {
263 | implementation fileTree(dir: "libs", include: ["*.jar"])
264 |
265 | //noinspection GradleDynamicVersion
266 | implementation "com.facebook.react:react-native:+" // From node_modules
267 |
268 | implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
269 |
270 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
271 | exclude group:'com.facebook.fbjni'
272 | }
273 |
274 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
275 | exclude group:'com.facebook.flipper'
276 | exclude group:'com.squareup.okhttp3', module:'okhttp'
277 | }
278 |
279 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
280 | exclude group:'com.facebook.flipper'
281 | }
282 |
283 | if (enableHermes) {
284 | def hermesPath = "../../node_modules/hermes-engine/android/";
285 | debugImplementation files(hermesPath + "hermes-debug.aar")
286 | releaseImplementation files(hermesPath + "hermes-release.aar")
287 | } else {
288 | implementation jscFlavor
289 | }
290 | }
291 |
292 | if (isNewArchitectureEnabled()) {
293 | // If new architecture is enabled, we let you build RN from source
294 | // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
295 | // This will be applied to all the imported transtitive dependency.
296 | configurations.all {
297 | resolutionStrategy.dependencySubstitution {
298 | substitute(module("com.facebook.react:react-native"))
299 | .using(project(":ReactAndroid")).because("On New Architecture we're building React Native from source")
300 | }
301 | }
302 | }
303 |
304 | // Run this once to be able to run the application with BUCK
305 | // puts all compile dependencies into folder libs for BUCK to use
306 | task copyDownloadableDepsToLibs(type: Copy) {
307 | from configurations.implementation
308 | into 'libs'
309 | }
310 |
311 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
312 |
313 | def isNewArchitectureEnabled() {
314 | // To opt-in for the New Architecture, you can either:
315 | // - Set `newArchEnabled` to true inside the `gradle.properties` file
316 | // - Invoke gradle with `-newArchEnabled=true`
317 | // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
318 | return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
319 | }
320 |
--------------------------------------------------------------------------------
/example/android/app/debug.keystore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/losthakkun/react-native-battery-optimization-check/4cd9267be3e765a679849a32b096e108e05e351a/example/android/app/debug.keystore
--------------------------------------------------------------------------------
/example/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | -keep class com.facebook.hermes.unicode.** { *; }
13 | -keep class com.facebook.jni.** { *; }
14 |
--------------------------------------------------------------------------------
/example/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/example/android/app/src/debug/java/com/example/reactnativebateryoptimizationcheck/ReactNativeFlipper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Meta Platforms, Inc. and affiliates.
3 | *
4 | *
This source code is licensed under the MIT license found in the LICENSE file in the root
5 | * directory of this source tree.
6 | */
7 | package com.example.reactnativebatteryoptimizationcheck;
8 |
9 | import android.content.Context;
10 | import com.facebook.flipper.android.AndroidFlipperClient;
11 | import com.facebook.flipper.android.utils.FlipperUtils;
12 | import com.facebook.flipper.core.FlipperClient;
13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping;
17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
20 | import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
21 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
22 | import com.facebook.react.ReactInstanceEventListener;
23 | import com.facebook.react.ReactInstanceManager;
24 | import com.facebook.react.bridge.ReactContext;
25 | import com.facebook.react.modules.network.NetworkingModule;
26 | import okhttp3.OkHttpClient;
27 |
28 | public class ReactNativeFlipper {
29 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
30 | if (FlipperUtils.shouldEnableFlipper(context)) {
31 | final FlipperClient client = AndroidFlipperClient.getInstance(context);
32 |
33 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
34 | client.addPlugin(new ReactFlipperPlugin());
35 | client.addPlugin(new DatabasesFlipperPlugin(context));
36 | client.addPlugin(new SharedPreferencesFlipperPlugin(context));
37 | client.addPlugin(CrashReporterPlugin.getInstance());
38 |
39 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
40 | NetworkingModule.setCustomClientBuilder(
41 | new NetworkingModule.CustomClientBuilder() {
42 | @Override
43 | public void apply(OkHttpClient.Builder builder) {
44 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
45 | }
46 | });
47 | client.addPlugin(networkFlipperPlugin);
48 | client.start();
49 |
50 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
51 | // Hence we run if after all native modules have been initialized
52 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
53 | if (reactContext == null) {
54 | reactInstanceManager.addReactInstanceEventListener(
55 | new ReactInstanceEventListener() {
56 | @Override
57 | public void onReactContextInitialized(ReactContext reactContext) {
58 | reactInstanceManager.removeReactInstanceEventListener(this);
59 | reactContext.runOnNativeModulesQueueThread(
60 | new Runnable() {
61 | @Override
62 | public void run() {
63 | client.addPlugin(new FrescoFlipperPlugin());
64 | }
65 | });
66 | }
67 | });
68 | } else {
69 | client.addPlugin(new FrescoFlipperPlugin());
70 | }
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/example/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
13 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/example/reactnativebateryoptimizationcheck/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.reactnativebatteryoptimizationcheck;
2 |
3 | import com.facebook.react.ReactActivity;
4 | import com.facebook.react.ReactActivityDelegate;
5 | import com.facebook.react.ReactRootView;
6 |
7 | public class MainActivity extends ReactActivity {
8 |
9 | /**
10 | * Returns the name of the main component registered from JavaScript. This is used to schedule
11 | * rendering of the component.
12 | */
13 | @Override
14 | protected String getMainComponentName() {
15 | return "main";
16 | }
17 |
18 | /**
19 | * Returns the instance of the {@link ReactActivityDelegate}. There the RootView is created and
20 | * you can specify the rendered you wish to use (Fabric or the older renderer).
21 | */
22 | @Override
23 | protected ReactActivityDelegate createReactActivityDelegate() {
24 | return new MainActivityDelegate(this, getMainComponentName());
25 | }
26 |
27 | public static class MainActivityDelegate extends ReactActivityDelegate {
28 | public MainActivityDelegate(ReactActivity activity, String mainComponentName) {
29 | super(activity, mainComponentName);
30 | }
31 |
32 | @Override
33 | protected ReactRootView createRootView() {
34 | ReactRootView reactRootView = new ReactRootView(getContext());
35 | // If you opted-in for the New Architecture, we enable the Fabric Renderer.
36 | reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED);
37 | return reactRootView;
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/example/reactnativebateryoptimizationcheck/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.example.reactnativebatteryoptimizationcheck;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 | import com.facebook.react.PackageList;
6 | import com.facebook.react.ReactApplication;
7 | import com.facebook.react.ReactInstanceManager;
8 | import com.facebook.react.ReactNativeHost;
9 | import com.facebook.react.ReactPackage;
10 | import com.facebook.react.config.ReactFeatureFlags;
11 | import com.facebook.soloader.SoLoader;
12 | import com.example.reactnativebatteryoptimizationcheck.newarchitecture.MainApplicationReactNativeHost;
13 | import java.lang.reflect.InvocationTargetException;
14 | import java.util.List;
15 |
16 | public class MainApplication extends Application implements ReactApplication {
17 |
18 | private final ReactNativeHost mReactNativeHost =
19 | new ReactNativeHost(this) {
20 | @Override
21 | public boolean getUseDeveloperSupport() {
22 | return BuildConfig.DEBUG;
23 | }
24 |
25 | @Override
26 | protected List getPackages() {
27 | @SuppressWarnings("UnnecessaryLocalVariable")
28 | List packages = new PackageList(this).getPackages();
29 | // Packages that cannot be autolinked yet can be added manually here, for example:
30 | // packages.add(new MyReactNativePackage());
31 | return packages;
32 | }
33 |
34 | @Override
35 | protected String getJSMainModuleName() {
36 | return "index";
37 | }
38 | };
39 |
40 | private final ReactNativeHost mNewArchitectureNativeHost =
41 | new MainApplicationReactNativeHost(this);
42 |
43 | @Override
44 | public ReactNativeHost getReactNativeHost() {
45 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
46 | return mNewArchitectureNativeHost;
47 | } else {
48 | return mReactNativeHost;
49 | }
50 | }
51 |
52 | @Override
53 | public void onCreate() {
54 | super.onCreate();
55 | // If you opted-in for the New Architecture, we enable the TurboModule system
56 | ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
57 | SoLoader.init(this, /* native exopackage */ false);
58 | initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
59 | }
60 |
61 | /**
62 | * Loads Flipper in React Native templates. Call this in the onCreate method with something like
63 | * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
64 | *
65 | * @param context
66 | * @param reactInstanceManager
67 | */
68 | private static void initializeFlipper(
69 | Context context, ReactInstanceManager reactInstanceManager) {
70 | if (BuildConfig.DEBUG) {
71 | try {
72 | /*
73 | We use reflection here to pick up the class that initializes Flipper,
74 | since Flipper library is not available in release mode
75 | */
76 | Class> aClass = Class.forName("com.example.reactnativebatteryoptimizationcheck.ReactNativeFlipper");
77 | aClass
78 | .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
79 | .invoke(null, context, reactInstanceManager);
80 | } catch (ClassNotFoundException e) {
81 | e.printStackTrace();
82 | } catch (NoSuchMethodException e) {
83 | e.printStackTrace();
84 | } catch (IllegalAccessException e) {
85 | e.printStackTrace();
86 | } catch (InvocationTargetException e) {
87 | e.printStackTrace();
88 | }
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/example/reactnativebateryoptimizationcheck/newarchitecture/MainApplicationReactNativeHost.java:
--------------------------------------------------------------------------------
1 | package com.example.reactnativebatteryoptimizationcheck.newarchitecture;
2 |
3 | import android.app.Application;
4 | import androidx.annotation.NonNull;
5 | import com.facebook.react.PackageList;
6 | import com.facebook.react.ReactInstanceManager;
7 | import com.facebook.react.ReactNativeHost;
8 | import com.facebook.react.ReactPackage;
9 | import com.facebook.react.ReactPackageTurboModuleManagerDelegate;
10 | import com.facebook.react.bridge.JSIModulePackage;
11 | import com.facebook.react.bridge.JSIModuleProvider;
12 | import com.facebook.react.bridge.JSIModuleSpec;
13 | import com.facebook.react.bridge.JSIModuleType;
14 | import com.facebook.react.bridge.JavaScriptContextHolder;
15 | import com.facebook.react.bridge.ReactApplicationContext;
16 | import com.facebook.react.bridge.UIManager;
17 | import com.facebook.react.fabric.ComponentFactory;
18 | import com.facebook.react.fabric.CoreComponentsRegistry;
19 | import com.facebook.react.fabric.EmptyReactNativeConfig;
20 | import com.facebook.react.fabric.FabricJSIModuleProvider;
21 | import com.facebook.react.uimanager.ViewManagerRegistry;
22 | import com.example.reactnativebatteryoptimizationcheck.BuildConfig;
23 | import com.example.reactnativebatteryoptimizationcheck.newarchitecture.components.MainComponentsRegistry;
24 | import com.example.reactnativebatteryoptimizationcheck.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate;
25 | import java.util.ArrayList;
26 | import java.util.List;
27 |
28 | /**
29 | * A {@link ReactNativeHost} that helps you load everything needed for the New Architecture, both
30 | * TurboModule delegates and the Fabric Renderer.
31 | *
32 | *
Please note that this class is used ONLY if you opt-in for the New Architecture (see the
33 | * `newArchEnabled` property). Is ignored otherwise.
34 | */
35 | public class MainApplicationReactNativeHost extends ReactNativeHost {
36 | public MainApplicationReactNativeHost(Application application) {
37 | super(application);
38 | }
39 |
40 | @Override
41 | public boolean getUseDeveloperSupport() {
42 | return BuildConfig.DEBUG;
43 | }
44 |
45 | @Override
46 | protected List getPackages() {
47 | List packages = new PackageList(this).getPackages();
48 | // Packages that cannot be autolinked yet can be added manually here, for example:
49 | // packages.add(new MyReactNativePackage());
50 | // TurboModules must also be loaded here providing a valid TurboReactPackage implementation:
51 | // packages.add(new TurboReactPackage() { ... });
52 | // If you have custom Fabric Components, their ViewManagers should also be loaded here
53 | // inside a ReactPackage.
54 | return packages;
55 | }
56 |
57 | @Override
58 | protected String getJSMainModuleName() {
59 | return "index";
60 | }
61 |
62 | @NonNull
63 | @Override
64 | protected ReactPackageTurboModuleManagerDelegate.Builder
65 | getReactPackageTurboModuleManagerDelegateBuilder() {
66 | // Here we provide the ReactPackageTurboModuleManagerDelegate Builder. This is necessary
67 | // for the new architecture and to use TurboModules correctly.
68 | return new MainApplicationTurboModuleManagerDelegate.Builder();
69 | }
70 |
71 | @Override
72 | protected JSIModulePackage getJSIModulePackage() {
73 | return new JSIModulePackage() {
74 | @Override
75 | public List getJSIModules(
76 | final ReactApplicationContext reactApplicationContext,
77 | final JavaScriptContextHolder jsContext) {
78 | final List specs = new ArrayList<>();
79 |
80 | // Here we provide a new JSIModuleSpec that will be responsible of providing the
81 | // custom Fabric Components.
82 | specs.add(
83 | new JSIModuleSpec() {
84 | @Override
85 | public JSIModuleType getJSIModuleType() {
86 | return JSIModuleType.UIManager;
87 | }
88 |
89 | @Override
90 | public JSIModuleProvider getJSIModuleProvider() {
91 | final ComponentFactory componentFactory = new ComponentFactory();
92 | CoreComponentsRegistry.register(componentFactory);
93 |
94 | // Here we register a Components Registry.
95 | // The one that is generated with the template contains no components
96 | // and just provides you the one from React Native core.
97 | MainComponentsRegistry.register(componentFactory);
98 |
99 | final ReactInstanceManager reactInstanceManager = getReactInstanceManager();
100 |
101 | ViewManagerRegistry viewManagerRegistry =
102 | new ViewManagerRegistry(
103 | reactInstanceManager.getOrCreateViewManagers(reactApplicationContext));
104 |
105 | return new FabricJSIModuleProvider(
106 | reactApplicationContext,
107 | componentFactory,
108 | new EmptyReactNativeConfig(),
109 | viewManagerRegistry);
110 | }
111 | });
112 | return specs;
113 | }
114 | };
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/example/reactnativebateryoptimizationcheck/newarchitecture/components/MainComponentsRegistry.java:
--------------------------------------------------------------------------------
1 | package com.example.reactnativebatteryoptimizationcheck.newarchitecture.components;
2 |
3 | import com.facebook.jni.HybridData;
4 | import com.facebook.proguard.annotations.DoNotStrip;
5 | import com.facebook.react.fabric.ComponentFactory;
6 | import com.facebook.soloader.SoLoader;
7 |
8 | /**
9 | * Class responsible to load the custom Fabric Components. This class has native methods and needs a
10 | * corresponding C++ implementation/header file to work correctly (already placed inside the jni/
11 | * folder for you).
12 | *
13 | *
Please note that this class is used ONLY if you opt-in for the New Architecture (see the
14 | * `newArchEnabled` property). Is ignored otherwise.
15 | */
16 | @DoNotStrip
17 | public class MainComponentsRegistry {
18 | static {
19 | SoLoader.loadLibrary("fabricjni");
20 | }
21 |
22 | @DoNotStrip private final HybridData mHybridData;
23 |
24 | @DoNotStrip
25 | private native HybridData initHybrid(ComponentFactory componentFactory);
26 |
27 | @DoNotStrip
28 | private MainComponentsRegistry(ComponentFactory componentFactory) {
29 | mHybridData = initHybrid(componentFactory);
30 | }
31 |
32 | @DoNotStrip
33 | public static MainComponentsRegistry register(ComponentFactory componentFactory) {
34 | return new MainComponentsRegistry(componentFactory);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/example/reactnativebateryoptimizationcheck/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java:
--------------------------------------------------------------------------------
1 | package com.example.reactnativebatteryoptimizationcheck.newarchitecture.modules;
2 |
3 | import com.facebook.jni.HybridData;
4 | import com.facebook.react.ReactPackage;
5 | import com.facebook.react.ReactPackageTurboModuleManagerDelegate;
6 | import com.facebook.react.bridge.ReactApplicationContext;
7 | import com.facebook.soloader.SoLoader;
8 | import java.util.List;
9 |
10 | /**
11 | * Class responsible to load the TurboModules. This class has native methods and needs a
12 | * corresponding C++ implementation/header file to work correctly (already placed inside the jni/
13 | * folder for you).
14 | *
15 | *