Device Information for React Native.
Using npm:
npm install --save react-native-device-info
or using yarn:
yarn add react-native-device-info
⚠️ As of version 2.1.1 the package can be loaded async to improve start up time on Android Refer to this PR for more information
@Override
public List<ReactPackage> createAdditionalReactPackages() {
return Arrays.<ReactPackage>asList(
new RNDeviceInfo(true), // Pass true to load the constants asynchronously on start up, default is false
);
}
⚠️ If you are on React Native > 0.47, you must use version 0.11.0 of this library or higher
AndroidX is supported in a non-breaking / backwards-compatible way by using overrides in your android/build.gradle
file's "ext" block
Android
...
ext {
// dependency versions
googlePlayServicesVersion = "17.0.0" // default: "16.1.0" - pre-AndroidX, override for AndroidX
compileSdkVersion = "28" // default: 28 (28 is required for AndroidX)
targetSdkVersion = "28" // default: 28 (28 is required for AndroidX)
supportLibVersion = '1.0.2' // Use '28.0.0' or don't specify for old libraries, '1.0.2' or similar for AndroidX
mediaCompatVersion = '1.0.1' // Do not specify if using old libraries, specify '1.0.1' or similar for androidx.media:media dependency
supportV4Version = '1.0.0' // Do not specify if using old libraries, specify '1.0.0' or similar for androidx.legacy:legacy-support-v4 dependency
}
...
react-native link react-native-device-info
(or using rnpm
for versions of React Native < 0.27)
rnpm link react-native-device-info
For iOS users using Pods
You still need to run pod install
after running the above link command inside your IOS
folder.
iOS (via CocoaPods)
Add the following lines to your build targets in your Podfile
pod 'React', :path => '../node_modules/react-native'
# Explicitly include Yoga if you are using RN >= 0.42.0
pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
pod 'RNDeviceInfo', :path => '../node_modules/react-native-device-info'
# React-Native is not great about React double-including from the Podfile
post_install do |installer|
installer.pods_project.targets.each do |target|
if target.name == "React"
target.remove_from_project
end
# It removes React & Yoga from the Pods project, as it is already included in the main project.
targets_to_ignore = %w(React yoga)
if targets_to_ignore.include? target.name
target.remove_from_project
end
end
end
Then run pod install
iOS (without CocoaPods)
In XCode, in the project navigator:
- Right click Libraries
- Add Files to [your project's name]
- Go to
node_modules/react-native-device-info/ios
- Add the file
RNDeviceInfo.xcodeproj
In XCode, in the project navigator, select your project.
- Add the
libRNDeviceInfo.a
from the deviceinfo project to your project's Build Phases ➜ Link Binary With Libraries - Click
.xcodeproj
file you added before in the project navigator and go the Build Settings tab. Make sure All is toggled on (instead of Basic). - Look for Header Search Paths and make sure it contains both
$(SRCROOT)/../react-native/React
and$(SRCROOT)/../../React
- Mark both as recursive (should be OK by default).
Run your project (Cmd+R)
(Thanks to @brysgo for writing the instructions)
Android
- optional in
android/build.gradle
:
...
ext {
// dependency versions
googlePlayServicesVersion = "<Your play services version>" // default: "16.1.0" - pre-AndroidX, override for AndroidX
compileSdkVersion = "<Your compile SDK version>" // default: 28
targetSdkVersion = "<Your target SDK version>" // default: 28
}
...
- in
android/app/build.gradle
:
dependencies {
...
implementation "com.facebook.react:react-native:+" // From node_modules
+ implementation project(':react-native-device-info')
}
- in
android/settings.gradle
:
...
include ':app'
+ include ':react-native-device-info'
+ project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')
- in
MainApplication.java
:
+ import com.learnium.RNDeviceInfo.RNDeviceInfo;
public class MainApplication extends Application implements ReactApplication {
//......
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
+ new RNDeviceInfo(),
new MainReactPackage()
);
}
......
}
- in
MainActivity.java
:
+ import com.learnium.RNDeviceInfo.RNDeviceInfo;
public class MainActivity extends ReactActivity {
......
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
+ new RNDeviceInfo(),
new MainReactPackage()
);
}
}
NOTE: If you faced with this error: Could not resolve all files for configuration ':react-native-device-info:debugCompileClasspath'.
, in build.gradle
put google()
in the first line (according to https://stackoverflow.com/a/50748249)
- in
android/build.gradle
:
allprojects {
repositories {
+ google()
...
}
}
(Thanks to @chirag04 for writing the instructions)
Windows
- Open the solution in Visual Studio for your Windows apps
- right click your in the Explorer and click Add > Existing Project...
- Navigate to
./<app-name>/node_modules/react-native-device-info/windows/RNDeviceInfo
and addRNDeviceInfo.csproj
- this time right click on your React Native Windows app under your solutions directory and click Add > Reference...
- check the
RNDeviceInfo
you just added and press ok - open up
MainReactNativeHost.cs
for your app and edit the file like so:
+ using RNDeviceInfo;
......
protected override List<IReactPackage> Packages => new List<IReactPackage>
{
new MainReactPackage(),
+ new RNDeviceInfoPackage(),
};
(Thanks to @josephan for writing the instructions)
import DeviceInfo from 'react-native-device-info';
Method | Return Type | iOS | Android | Windows | Since |
---|---|---|---|---|---|
getAPILevel() | number |
❌ | ✅ | ❌ | 0.12.0 |
getApplicationName() | string |
✅ | ✅ | ✅ | 0.14.0 |
getBaseOS() | string |
❌ | ✅ | ❌ | ? |
getBatteryLevel() | Promise<number> |
✅ | ✅ | ✅ | 0.18.0 |
getBootloader() | string |
❌ | ✅ | ❌ | ? |
getBrand() | string |
✅ | ✅ | ✅ | 0.9.3 |
getBuildNumber() | string |
✅ | ✅ | ✅ | ? |
getBundleId() | string |
✅ | ✅ | ✅ | ? |
getCameraPresence() | Promise<boolean> |
❌ | ✅ | ✅ | ? |
getCarrier() | string |
✅ | ✅ | ❌ | 0.13.0 |
getCodename() | string |
❌ | ✅ | ❌ | ? |
getDevice() | string |
❌ | ✅ | ❌ | ? |
getDeviceCountry() | string |
✅ | ✅ | ✅ | 0.9.0 |
getDeviceId() | string |
✅ | ✅ | ✅ | 0.5.0 |
getDeviceLocale() | string |
✅ | ✅ | ✅ | 0.7.0 |
getDisplay() | string |
❌ | ✅ | ❌ | ? |
getPreferredLocales() | Array<string> |
✅ | ✅ | ❌ | ? |
getDeviceName() | string |
✅ | ✅ | ✅ | ? |
getFirstInstallTime() | number |
❌ | ✅ | ✅ | 0.12.0 |
getFingerprint() | string |
❌ | ✅ | ❌ | ? |
getFontScale() | number |
✅ | ✅ | ❌ | 0.15.0 |
getFreeDiskStorage() | number |
✅ | ✅ | ❌ | 0.15.0 |
getHardware() | string |
❌ | ✅ | ❌ | ? |
getHost() | string |
❌ | ✅ | ❌ | ? |
getIPAddress() | Promise<string> |
✅ | ✅ | ✅ | 0.12.0 |
getIncremental() | string |
❌ | ✅ | ❌ | ? |
getInstallReferrer() | string |
❌ | ✅ | ❌ | 0.19.0 |
getInstanceID() | string |
❌ | ✅ | ❌ | ? |
getLastUpdateTime() | number |
❌ | ✅ | ❌ | 0.12.0 |
getMACAddress() | Promise<string> |
✅ | ✅ | ❌ | 0.12.0 |
getManufacturer() | string |
✅ | ✅ | ✅ | ? |
getMaxMemory() | number |
❌ | ✅ | ✅ | 0.14.0 |
getModel() | string |
✅ | ✅ | ✅ | ? |
getPhoneNumber() | string |
❌ | ✅ | ❌ | 0.12.0 |
getPowerState() | Promise<object> |
✅ | ❌ | ❌ | |
getProduct() | string |
❌ | ✅ | ❌ | ? |
getPreviewSdkInt() | number |
❌ | ✅ | ❌ | ? |
getReadableVersion() | string |
✅ | ✅ | ✅ | ? |
getSerialNumber() | string |
❌ | ✅ | ❌ | 0.12.0 |
getSecurityPatch() | string |
❌ | ✅ | ❌ | ? |
getSystemName() | string |
✅ | ✅ | ✅ | ? |
getSystemVersion() | string |
✅ | ✅ | ✅ | ? |
getBuildId() | string |
✅ | ✅ | ❌ | ? |
getTags() | string |
❌ | ✅ | ❌ | ? |
getType() | string |
❌ | ✅ | ❌ | ? |
getTimezone() | string |
✅ | ✅ | ✅ | ? |
getTotalDiskCapacity() | number |
✅ | ✅ | ❌ | 0.15.0 |
getTotalMemory() | number |
✅ | ✅ | ❌ | 0.14.0 |
getUniqueID() | string |
✅ | ✅ | ✅ | ? |
getUserAgent() | string |
✅ | ✅ | ❌ | 0.7.0 |
getVersion() | string |
✅ | ✅ | ✅ | ? |
is24Hour() | boolean |
✅ | ✅ | ✅ | 0.13.0 |
isAirPlaneMode() | Promise<boolean> |
❌ | ✅ | ❌ | 0.25.0 |
isBatteryCharging() | Promise<boolean> |
✅ | ✅ | ❌ | 0.27.0 |
isEmulator() | boolean |
✅ | ✅ | ✅ | ? |
isPinOrFingerprintSet() | (callback)boolean |
✅ | ✅ | ✅ | 0.10.1 |
isTablet() | boolean |
✅ | ✅ | ✅ | ? |
hasNotch() | boolean |
✅ | ✅ | ✅ | 0.23.0 |
isLandscape() | boolean |
✅ | ✅ | ✅ | 0.24.0 |
getDeviceType() | string |
✅ | ✅ | ❌ | ? |
isAutoDateAndTime() | Promise<boolean> |
❌ | ✅ | ❌ | 0.29.0 |
isAutoTimeZone() | Promise<boolean> |
❌ | ✅ | ❌ | 0.29.0 |
supported32BitAbis() | string[] |
❌ | ✅ | ❌ | ? |
[supported64BitAbis()](#supported64BitAbis | string[] |
❌ | ✅ | ❌ | ? |
supportedABIs() | string[] |
✅ | ✅ | ❌ | 1.1.0 |
hasSystemFeature() | Promise<boolean> |
❌ | ✅ | ❌ | ? |
getSystemAvailableFeatures() | Promise<string[]> |
❌ | ✅ | ❌ | ? |
isLocationEnabled() | Promise<boolean> |
✅ | ✅ | ❌ | ? |
getAvailableLocationProviders() | Promise<Object> |
✅ | ✅ | ❌ | ? |
Gets the API level.
Examples
const apiLevel = DeviceInfo.getAPILevel();
// iOS: ?
// Android: 25
// Windows: ?
Notes
See API Levels
Gets the application name.
Examples
const appName = DeviceInfo.getApplicationName(); // "Learnium Mobile"
The base OS build the product is based on.
Examples
const baseOS = DeviceInfo.getBaseOS();
Gets the battery level of the device as a float comprised between 0 and 1.
Examples
DeviceInfo.getBatteryLevel().then(batteryLevel => {
// 0.759999
});
Notes
To be able to get actual battery level enable battery monitoring mode for application. Add this code:
[UIDevice currentDevice].batteryMonitoringEnabled = true;
to AppDelegate.m application:didFinishLaunchingWithOptions:
Returns -1 on the iOS Simulator
The system bootloader version number.
Examples
const bootloader = DeviceInfo.getBootloader();
// "mw8998-002.0069.00"
Gets the device brand.
Examples
const brand = DeviceInfo.getBrand();
// iOS: "Apple"
// Android: "xiaomi"
// Windows: ?
Gets the application build number.
Examples
const buildNumber = DeviceInfo.getBuildNumber();
// iOS: "89"
// Android: 4
// Windows: ?
Notes
There is a type inconsistency: Android return an integer instead of the documented string.
Gets the application bundle identifier.
Examples
const bundleId = DeviceInfo.getBundleId(); // "com.learnium.mobile"
Tells if the device have any camera now.
Examples
DeviceInfo.getCameraPresence()
.then(isCameraPresent => {
// true or false
})
.catch(cameraAccessException => {
// is thrown if a camera device could not be queried or opened by the CameraManager on Android
});
Notes
- Hot add/remove of camera is supported.
- Returns the status of the physical presence of the camera. If camera present but your app don't have permissions to use it, getCameraPresence will still return the true
Gets the carrier name (network operator).
Examples
const carrier = DeviceInfo.getCarrier(); // "SOFTBANK"
The current development codename, or the string "REL" if this is a release build.
Examples
const codename = DeviceInfo.getCodename();
// "REL"
The name of the industrial design.
Examples
const device = DeviceInfo.getDevice();
// "walleye"
Gets the device country based on the locale information.
Examples
const deviceCountry = DeviceInfo.getDeviceCountry(); // "US"
Gets the device ID.
Examples
const deviceId = DeviceInfo.getDeviceId();
// iOS: "iPhone7,2"
// Android: "goldfish"
// Windows: ?
Gets the device locale.
Examples
const deviceLocale = DeviceInfo.getDeviceLocale();
// iOS: "en"
// Android: "en-US"
// Windows: ?
A build ID string meant for displaying to the user.
Examples
const display = DeviceInfo.getDisplay();
// "OPM2.171026.006.G1"
Gets the preferred locales defined by the user.
Examples
const preferredLocales = DeviceInfo.getPreferredLocales();
// iOS: "[es-ES, en-US]"
// Android: "[es-ES, en-US]"
// Windows: ?
Gets the device name.
Examples
const deviceName = DeviceInfo.getDeviceName();
// iOS: "Becca's iPhone 6"
// Android: ?
// Windows: ?
Android Permissions
Gets the time at which the app was first installed, in milliseconds.
Examples
const firstInstallTime = DeviceInfo.getFirstInstallTime();
// Android: 1517681764528
A string that uniquely identifies this build.
Examples
const fingerprint = DeviceInfo.getFingerprint();
// "google/walleye/walleye:8.1.0/OPM2.171026.006.G1/4820017:user/release-keys"
Gets the device font scale. The font scale is the ratio of the current system font to the "normal" font size, so if normal text is 10pt and the system font is currently 15pt, the font scale would be 1.5 This can be used to determine if accessability settings has been changed for the device; you may want to re-layout certain views if the font scale is significantly larger ( > 2.0 )
In iOS App Extensions this call always returns 1.0, see #625.
Examples
const fontScale = DeviceInfo.getFontScale(); // 1.2
Gets available storage size, in bytes.
Examples
const freeDiskStorage = DeviceInfo.getFreeDiskStorage();
// Android: 17179869184
// iOS: 17179869184
Notes
From developer.android.com:
Return the primary shared/external storage directory.
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
The name of the hardware (from the kernel command line or /proc).
Examples
const hardware = DeviceInfo.getHardware();
// "walleye"
Hostname
Examples
const host = DeviceInfo.getHost();
// "wprd10.hot.corp.google.com"
Gets the device current IP address.
Examples
DeviceInfo.getIPAddress().then(ip => {
// "92.168.32.44"
});
Android Permissions
Notes
Support for iOS was added in 0.22.0
The internal value used by the underlying source control to represent this build.
Examples
const incremental = DeviceInfo.getIncremental();
// "4820017"
Gets the referrer string upon application installation.
Examples
const referrer = DeviceInfo.getInstallReferrer();
// If the app was installed from https://play.google.com/store/apps/details?id=com.myapp&referrer=my_install_referrer
// the result will be "my_install_referrer"
Gets the application instance ID.
Examples
const instanceId = DeviceInfo.getInstanceID();
// Android: ?
Notes
Gets the time at which the app was last updated, in milliseconds.
Examples
const lastUpdateTime = DeviceInfo.getLastUpdateTime();
// Android: 1517681764992
Gets the network adapter MAC address.
Examples
DeviceInfo.getMACAddress().then(mac => {
// "E5:12:D8:E5:69:97"
});
Android Permissions
Notes
iOS: This method always return "02:00:00:00:00:00" as retrieving the MAC address is disabled since iOS 7
Gets the device manufacturer.
Examples
const manufacturer = DeviceInfo.getManufacturer();
// iOS: "Apple"
// Android: "Google"
// Windows: ?
Returns the maximum amount of memory that the VM will attempt to use, in bytes.
Examples
const maxMemory = DeviceInfo.getMaxMemory(); // 402653183
Gets the device model.
iOS warning: The list with device names is maintained by the community and could lag new devices. It is recommended to use getDeviceId()
since it's more reliable and always up-to-date with new iOS devices. We do accept pull requests that add new iOS devices to the list with device names.
Examples
const model = DeviceInfo.getModel();
// iOS: ?
// Android: ?
// Windows: ?
Gets the device phone number.
Examples
const phoneNumber = DeviceInfo.getPhoneNumber();
// Android: null return: no permission, empty string: unprogrammed or empty SIM1, e.g. "+15555215558": normal return value
Android Permissions
Notes
This can return
undefined
in certain cases and should not be relied on. SO entry on the subject.
Gets the power state of the device including the battery level, whether it is plugged in, and if the system is currently operating in low power mode. Displays a warning on iOS if battery monitoring not enabled, or if attempted on an emulator (where monitoring is not possible)
Examples
DeviceInfo.getPowerState().then(state => {
// {
// batteryLevel: 0.759999,
// batteryState: 'unplugged',
// lowPowerMode: false,
// }
});
The name of the overall product.
Examples
const product = DeviceInfo.getProduct();
// "walleye"
The developer preview revision of a prerelease SDK.
Examples
const previewSdkInt = DeviceInfo.getPreviewSdkInt();
// 0
Gets the application human readable version.
Examples
const readableVersion = DeviceInfo.getReadableVersion();
// iOS: 1.0.1
// Android: 1.0.1
// Windows: ?
Gets the device serial number.
Examples
const serialNumber = DeviceInfo.getSerialNumber();
// iOS: undefined
// Android: ?
// Windows: ?
The user-visible security patch level.
Examples
const securityPatch = DeviceInfo.getSecurityPatch();
// "2018-07-05"
Gets the device OS name.
Examples
const systemName = DeviceInfo.getSystemName();
// iOS: "iOS" on newer iOS devices "iPhone OS" on older devices, including older iPad's.
// Android: "Android"
// Windows: ?
Gets the device OS version.
Examples
const systemVersion = DeviceInfo.getSystemVersion();
// iOS: "11.0"
// Android: "7.1.1"
// Windows: ?
Gets build number of the operating system.
Examples
const osBuildId = DeviceInfo.getBuildId();
// iOS: "12A269"
// tvOS: not available
// Android: "13D15"
// Windows: not available
Comma-separated tags describing the build.
Examples
const tags = DeviceInfo.getTags();
// "release-keys, unsigned, debug",
The type of build.
Examples
const type = DeviceInfo.getType();
// "user", "eng"
Gets the device default timezone.
Examples
const timezone = DeviceInfo.getTimezone(); // "Africa/Tunis"
Gets full disk storage size, in bytes.
Examples
const storageSize = DeviceInfo.getTotalDiskCapacity();
// Android: 17179869184
// iOS: 17179869184
Gets the device total memory, in bytes.
Examples
const totalMemory = DeviceInfo.getTotalMemory(); // 1995018240
Gets the device unique ID.
Examples
const uniqueId = DeviceInfo.getUniqueID();
// iOS: "FCDBD8EF-62FC-4ECB-B2F5-92C9E79AC7F9"
// Android: "dd96dec43fb81c97"
// Windows: ?
Notes
- iOS: This is
IDFV
or a random string if IDFV is unavaliable. Once UID is generated it is stored in iOS Keychain and NSUserDefaults. So it would stay the same even if you delete the app or reset IDFV. You can carefully consider it a persistent, cross-install unique ID. It can be changed only in case someone manually override values in Keychain/NSUserDefaults or if Apple would change Keychain and NSUserDefaults implementations- android: Prior to Oreo, this id (ANDROID_ID) will always be the same once you set up your phone.
Gets the device User Agent.
Examples
const userAgent = DeviceInfo.getUserAgent();
// iOS: "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143"
// tvOS: not available
// Android: ?
// Windows: ?
Gets the application version.
Examples
const version = DeviceInfo.getVersion();
// iOS: "1.0"
// Android: "1.0"
// Windows: ?
Tells if the user preference is set to 24-hour format.
Examples
const is24Hour = DeviceInfo.is24Hour(); // true
Tells if the device is in AirPlaneMode.
Examples
DeviceInfo.isAirPlaneMode().then(airPlaneModeOn => {
// false
});
Notes
- This only works if the remote debugger is disabled.
Tells if the battery is currently charging.
Examples
DeviceInfo.isBatteryCharging().then(isCharging => {
// true or false
});
Tells if the application is running in an emulator.
Examples
const isEmulator = DeviceInfo.isEmulator(); // false
Tells if a PIN number or a fingerprint was set for the device.
Examples
DeviceInfo.isPinOrFingerprintSet()(isPinOrFingerprintSet => {
if (!isPinOrFingerprintSet) {
// ...
}
});
Notes
- Since the device setting for PIN/Fingerprint can be modified while the app is still open, this is available via callback instead of as a constant.
- iOS: Not supported for iOS < 9
Tells if the device is a tablet.
Examples
const isTablet = DeviceInfo.isTablet(); // true
Tells if the device is currently in landscape mode.
Examples
const isLandscape = DeviceInfo.isLandscape(); // true
Tells if the device has a notch.
Examples
const hasNotch = DeviceInfo.hasNotch(); // true
Returns the device's type as a string, which will be one of:
Handset
Tablet
Tv
Unknown
Examples
const deviceType = DeviceInfo.getDeviceType(); // 'Handset'
Tells if the automatic date & time setting is enabled on the phone.
Examples
DeviceInfo.isAutoDateAndTime().then(isAutoDateAndTime => {
// true or false
});
Tells if the automatic time zone setting is enabled on the phone.
Examples
DeviceInfo.isAutoTimeZone().then(isAutoTimeZone => {
// true or false
});
An ordered list of 32 bit ABIs supported by this device.
Examples
const supported32BitAbis = DeviceInfo.supported32BitAbis();
// ["armeabi-v7a", "armeabi"]
An ordered list of 64 bit ABIs supported by this device.
Examples
const supported64BitAbis = DeviceInfo.supported64BitAbis();
// ["arm64-v8a"]
Returns a list of supported processor architecture version
Examples
DeviceInfo.supportedABIs(); // [ "arm64 v8", "Intel x86-64h Haswell", "arm64-v8a", "armeabi-v7a", "armeabi" ]
Tells if the device has a specific system feature.
Examples
DeviceInfo.hasSystemFeature('amazon.hardware.fire_tv').then(hasFeature => {
// true or false
});
Returns a list of available system features on Android.
Examples
DeviceInfo.getSystemAvailableFeatures().then(features => {
// ["android.software.backup", "android.hardware.screen.landscape", "android.hardware.wifi", ...]
});
Tells if the device has location services turned off at the device-level (NOT related to app-specific permissions)
Examples
DeviceInfo.isLocationEnabled().then(enabled => {
// true or false
});
Returns an object of platform-specfic location providers/servcies, with boolean
value whether or not they are currently available.
NOTE: This function requires access to the Location permission on Android
DeviceInfo.getAvailableLocationProviders().then(providers => {
// {
// gps: true
// network: true
// passive: true
// }
});
DeviceInfo.getAvailableLocationProviders().then(providers => {
// {
// headingAvailable: false
// isRangingAvailable: false
// locationServicesEnabled: true
// significantLocationChangeMonitoringAvailable: true
// }
});
Currently iOS-only.
Fired when the battery level changes; sent no more frequently than once per minute.
Examples
import { NativeEventEmitter, NativeModules } from 'react-native'
const deviceInfoEmitter = new NativeEventEmitter(NativeModules.RNDeviceInfo)
deviceInfoEmitter.addListener('batteryLevelDidChange', level => {
// 0.759999
});
Fired when the battery drops below 20%.
Examples
import { NativeEventEmitter, NativeModules } from 'react-native'
const deviceInfoEmitter = new NativeEventEmitter(NativeModules.RNDeviceInfo)
deviceInfoEmitter.addListener('batteryLevelIsLow', level => {
// 0.19
});
Fired when the battery state changes, for example when the device enters charging mode or is unplugged.
Examples
import { NativeEventEmitter, NativeModules } from 'react-native'
const deviceInfoEmitter = new NativeEventEmitter(NativeModules.RNDeviceInfo)
deviceInfoEmitter.addListener('powerStateDidChange', { batteryState } => {
// 'charging'
});
When installing or using react-native-device-info
, you may encounter the following problems:
[android] - Unable to merge dex / Multiple dex files / Problems with `com.google.android.gms`
react-native-device-info
uses com.google.android.gms:play-services-gcm
to provide [getInstance()][#getinstance].
This can lead to conflicts when building the Android application.
If you're using a different version of com.google.android.gms:play-services-gcm
in your app, you can define the
googlePlayServicesVersion
gradle variable in your build.gradle
file to tell react-native-device-info
what version
it should require. See the example project included here for a sample.
If you're using a different library that conflicts with com.google.android.gms:play-services-gcm
, and you are certain you know what you are doing such that you will avoid version conflicts, you can simply
ignore this dependency in your gradle file:
compile(project(':react-native-device-info')) {
exclude group: 'com.google.android.gms'
}
[ios] - ld: library not found for -lRNDeviceInfo-tvOS
Seems to be a bug caused by react-native link
. You can manually delete libRNDeviceInfo-tvOS.a
in Xcode -> [Your iOS build target] -> Build Phrases -> Link Binary with Libraries
.
[ios] - [NetworkInfo] Descriptors query returned error: Error Domain=NSCocoaErrorDomain Code=4099 “The connection to service named com.apple.commcenter.coretelephony.xpc was invalidated.”
This is a system level log that may be turned off by executing:
xcrun simctl spawn booted log config --mode "level:off" --subsystem com.apple.CoreTelephony
.
To undo the command, you can execute:
xcrun simctl spawn booted log config --mode "level:info" --subsystem com.apple.CoreTelephony
[ios] - Multiple versions of React when using CocoaPods "tries to require 'react-native' but there are several files providing this module"
You may need to adjust your Podfile like this if you use Cocoapods and have undefined symbols or duplicate React definitions
target 'yourTargetName' do
# See http://facebook.github.io/react-native/docs/integration-with-existing-apps.html#configuring-cocoapods-dependencies
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'Core',
'CxxBridge', # Include this for RN >= 0.47
'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43
'RCTText',
'RCTNetwork',
'RCTWebSocket', # Needed for debugging
'RCTAnimation', # Needed for FlatList and animations running on native UI thread
# Add any other subspecs you want to use in your project
]
# Explicitly include Yoga if you are using RN >= 0.42.0
pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
# Third party deps podspec link - you may have multiple pods here, just an example
pod 'RNDeviceInfo', path: '../node_modules/react-native-device-info'
end
# if you see errors about React duplicate definitions, this fixes it. The same works for yoga.
post_install do |installer|
installer.pods_project.targets.each do |target|
if target.name == "React"
target.remove_from_project
end
end
end
[tests] - Cannot run my test suite when using this library
react-native-device-info
contains native code, and needs to be mocked. Jest Snapshot support may work though.
Here's how to do it with jest for example:
// in your package.json:
"jest": {
"setupFiles": [
"./testenv.js"
],
// testenv.js:
jest.mock('react-native-device-info', () => {
return {
getModel: jest.fn(),
};
});
[warnings] - I get too many warnings (battery state, etc)
Some of the APIs (like getBatteryState) will throw warnings in certain conditions like on tvOS or the iOS emulator. This won't be visible in production but even in development it may be irritating. It is useful to have the warnings because these devices return no state, and that can be surprising, leading to github support issues. The warnings is intended to educate you as a developer. If the warnings are troublesome you may try this in your code to suppress them:
import { YellowBox } from 'react-native';
YellowBox.ignoreWarnings(['Battery state']);
See the CHANGELOG.md.
Please see the contributing guide
.
As a courtesy to developers, this library was made compatible in v0.21.6 with react-native-dom and react-native-web by providing an empty polyfill in order to avoid breaking builds.
Only getUserAgent() will return a correct value. All other API methods will return an "empty" value of its documented return type: 0
for numbers, ''
for strings, false
for booleans.