Skip to content

Commit

Permalink
Fix: reduce background battery usage by ensuring GPS is turned off in…
Browse files Browse the repository at this point in the history
… background
  • Loading branch information
gmaclennan committed Jun 3, 2019
1 parent bce7328 commit ec2de6e
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/frontend/context/LocationContext.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// @flow
import * as React from "react";
import { AppState } from "react-native";
import * as Location from "expo-location";
import AsyncStorage from "@react-native-community/async-storage";
import debug from "debug";
Expand Down Expand Up @@ -53,6 +54,8 @@ export type LocationContextType = {
error: boolean
};

type AppStateType = "active" | "background" | "inactive";

type Props = {
children: React.Node,
permissions: PermissionsType
Expand Down Expand Up @@ -111,6 +114,7 @@ class LocationProvider extends React.Component<Props, LocationContextType> {

async componentDidMount() {
this.updateStatus();
AppState.addEventListener("change", this.handleAppStateChange);
try {
const savedPosition = await AsyncStorage.getItem(STORE_KEY);
if (savedPosition == null) {
Expand Down Expand Up @@ -147,7 +151,7 @@ class LocationProvider extends React.Component<Props, LocationContextType> {
if (!hasLocationPermission) return;
clearTimeout(this._timeoutId);
const provider = await Location.getProviderStatusAsync();
log("Provider status", provider);
// log("Provider status", provider);
if (provider && provider.locationServicesEnabled && !this._watch) {
this._watch = await Location.watchPositionAsync(
positionOptions,
Expand All @@ -166,6 +170,20 @@ class LocationProvider extends React.Component<Props, LocationContextType> {
};

componentWillUnmount() {
this.stopWatchingLocation();
AppState.removeEventListener("change", this.handleAppStateChange);
}

handleAppStateChange = (nextAppState: AppStateType) => {
if (nextAppState === "active") {
this.updateStatus();
} else {
this.stopWatchingLocation();
}
};

stopWatchingLocation() {
log("Stopping GPS watch");
if (this._watch) this._watch.remove();
clearTimeout(this._timeoutId);
this._watch = null;
Expand Down

0 comments on commit ec2de6e

Please sign in to comment.