HomeGuidesReferenceLearn

Reference version

ArchiveExpo SnackDiscord and ForumsNewsletter
This is documentation for the next SDK version. For up-to-date documentation, see the latest version (SDK 51).

Expo LightSensor iconExpo LightSensor

GitHub

npm

A library that provides access to the device's light sensor.

Android

LightSensor from expo-sensors provides access to the device's light sensor to respond to illuminance changes.

Installation

Terminal
npx expo install expo-sensors

If you are installing this in an existing React Native app (bare workflow), start by installing expo in your project. Then, follow the additional instructions as mentioned by library's README under "Installation in bare React Native projects" section.

Usage

Basic Light Sensor usage
import { useState, useEffect } from 'react';
import { StyleSheet, Text, TouchableOpacity, View, Platform } from 'react-native';
import { LightSensor } from 'expo-sensors';

export default function App() {
  const [{ illuminance }, setData] = useState({ illuminance: 0 });
  const [subscription, setSubscription] = useState(null);

  const toggle = () => {
    if (subscription) {
      unsubscribe();
    } else {
      subscribe();
    }
  };

  const subscribe = () => {
    setSubscription(
      LightSensor.addListener(sensorData => {
        setData(sensorData);
      })
    );
  };

  const unsubscribe = () => {
    subscription && subscription.remove();
    setSubscription(null);
  };

  useEffect(() => {
    subscribe();
    return () => unsubscribe();
  }, []);

  return (
    <View style={styles.sensor}>
      <Text>Light Sensor:</Text>
      <Text>
        Illuminance: {Platform.OS === 'android' ? `${illuminance} lx` : `Only available on Android`}
      </Text>
      <View style={styles.buttonContainer}>
        <TouchableOpacity onPress={toggle} style={styles.button}>
          <Text>Toggle</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  sensor: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 10,
  },
  buttonContainer: {
    flexDirection: 'row',
    alignItems: 'stretch',
    marginTop: 15,
  },
  button: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#eee',
    padding: 10,
  },
});

API

import { LightSensor } from 'expo-sensors';

Classes

Android

LightSensor

Type: Class extends default<LightSensorMeasurement>

LightSensor Methods

Android

getListenerCount()

Returns the registered listeners count.

Returns:

number

Android

getPermissionsAsync()

Checks user's permissions for accessing sensor.

Android

hasListeners()

Returns boolean which signifies if sensor has any listeners registered.

Returns:

boolean

Android

removeAllListeners()

Removes all registered listeners.

Returns:

void

Android

removeSubscription(subscription)

NameTypeDescription
subscriptionEventSubscription

A subscription to remove.


Removes the given subscription.

Returns:

void

Android

requestPermissionsAsync()

Asks the user to grant permissions for accessing sensor.

Android

setUpdateInterval(intervalMs)

NameTypeDescription
intervalMsnumber

Desired interval in milliseconds between sensor updates.

Starting from Android 12 (API level 31), the system has a 200ms limit for each sensor updates.

If you need an update interval less than 200ms, you should:

  • add android.permission.HIGH_SAMPLING_RATE_SENSORS to app.json permissions field
  • or if you are using bare workflow, add <uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS"/> to AndroidManifest.xml.

Set the sensor update interval.

Returns:

void

Interfaces

Android

PermissionResponse

An object obtained by permissions get and request functions.

PermissionResponse Properties

NameTypeDescription
canAskAgainboolean

Indicates if user can be asked again for specific permission. If not, one should be directed to the Settings app in order to enable/disable the permission.

expiresPermissionExpiration

Determines time when the permission expires.

grantedboolean

A convenience boolean that indicates if the permission is granted.

statusPermissionStatus

Determines the status of the permission.


Types

Android

LightSensorMeasurement

NameTypeDescription
illuminancenumber

Ambient light level registered by the device measured in lux (lx).

timestampnumber

Timestamp of the measurement in seconds.

Android

PermissionExpiration

Literal Type: multiple types

Permission expiration time. Currently, all permissions are granted permanently.

Acceptable values are: 'never' | number

Android

Subscription

A subscription object that allows to conveniently remove an event listener from the emitter.

NameTypeDescription
remove() => void

Removes an event listener for which the subscription has been created. After calling this function, the listener will no longer receive any events from the emitter.

Enums

Android

PermissionStatus

PermissionStatus Values

DENIED

PermissionStatus.DENIED = "denied"

User has denied the permission.

GRANTED

PermissionStatus.GRANTED = "granted"

User has granted the permission.

UNDETERMINED

PermissionStatus.UNDETERMINED = "undetermined"

User hasn't granted or denied the permission yet.