transistorsoft / react-native-background-fetch

Periodic callbacks in the background for both IOS and Android
MIT License
1.49k stars 194 forks source link

Stop working in background when phone lockscreen is closed on android #535

Open Devendra7409 opened 15 hours ago

Devendra7409 commented 15 hours ago

Your Environment

Expected Behavior

i want run background task as well as kill state

Actual Behavior

background task run but after sometime background services stop when lockscreen is closed .

Steps to Reproduce

import React, { useState, useEffect } from 'react'; import { View, Text, Button, PermissionsAndroid, Platform } from 'react-native'; import MapView, { Marker } from 'react-native-maps'; import BackgroundService from 'react-native-background-actions'; import Geolocation from 'react-native-geolocation-service'; import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions';

// Helper function to sleep const sleep = (time: number | undefined) => new Promise((resolve) => setTimeout(resolve, time));

// Request location permission for both Android and iOS const requestLocationPermission = async () => { if (Platform.OS === 'android') { const fineLocationGranted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { title: 'Location Permission', message: 'This app needs access to your location', buttonNeutral: 'Ask Me Later', buttonNegative: 'Cancel', buttonPositive: 'OK', }, ); if (fineLocationGranted !== PermissionsAndroid.RESULTS.GRANTED) { console.log('Fine location permission denied'); return false; }

const backgroundLocationGranted = await PermissionsAndroid.request(
  PermissionsAndroid.PERMISSIONS.ACCESS_BACKGROUND_LOCATION,
  {
    title: 'Background Location Permission',
    message: 'This app needs access to your location in the background',
    buttonNeutral: 'Ask Me Later',
    buttonNegative: 'Cancel',
    buttonPositive: 'OK',
  },
);
if (backgroundLocationGranted !== PermissionsAndroid.RESULTS.GRANTED) {
  console.log('Background location permission denied');
  return false;
}

return true;

} else { const result = await request(PERMISSIONS.IOS.LOCATION_ALWAYS); if (result === RESULTS.GRANTED) { console.log('Location permission granted (iOS)'); return true; } else { console.log('Location permission denied (iOS)'); return false; } } };

// Function to send location data via API const sendLocationData = async (latitude: number, longitude: number, userId: any, batteryStatus: any, accuracy: any) => { const params = { UserId: 764, Lat: latitude, Long: longitude, BatteryStatus: 10, accuracy: accuracy }; console.log("Payload:", params);

try { const response = await fetch('API Name', { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify(params), }); const res = await response.json(); // console.log('Response:', JSON.stringify(res)); } catch (error) { console.error('Error sending location data:', error); // Optionally retry sending data after a delay setTimeout(() => sendLocationData(latitude, longitude, userId, batteryStatus), 5000); // Retry after 2 minutes } };

// Watch position to track location updates continuously const watchLocationInBackground = async (updateLocation: (arg0: Geolocation.GeoCoordinates) => void, userId: any, batteryStatus: any, accuracy: any) => { try { Geolocation.watchPosition( (position) => { const { latitude, longitude,accuracy } = position.coords; console.log(Background Location: ${latitude}, ${longitude},${accuracy}); updateLocation(position.coords); sendLocationData(latitude, longitude, userId, batteryStatus, accuracy); }, (error) => { console.error('Error watching position:', error); }, { enableHighAccuracy: true, distanceFilter: 0, // Get updates even for small movements interval: 5000, // Polling interval fastestInterval: 2000, maximumAge: 10000, useSignificantChanges: false, }, ); } catch (error) { console.error('Location tracking error:', error); } };

// Background task to handle continuous location tracking const veryIntensiveTask = async ({ updateLocation }) => { await watchLocationInBackground(updateLocation); // Keep watching the location

while (BackgroundService.isRunning()) { await sleep(5000); // Sleep for a few seconds before checking again } };

const App = () => { const [location, setLocation] = useState({ latitude: 0, longitude: 0, });

// Function to update the state with the new location const updateLocation = (newLocation: React.SetStateAction<{ latitude: number; longitude: number; }>) => { setLocation(newLocation); };

// Start the background location tracking task const startTask = async () => { const hasPermission = await requestLocationPermission(); if (!hasPermission) { console.log('Location permission not granted'); return; }

const options = {
  taskName: 'Background Location Task',
  taskTitle: 'Location Tracking',
  taskDesc: 'Fetching location in the background',
  taskIcon: {
    name: 'ic_launcher',
    type: 'mipmap',
  },
  color: '#ff00ff',
  linkingURI: 'yourapp://chat',
  parameters: {
    updateLocation,
  },
};

BackgroundService.start(veryIntensiveTask, options)
  .then(() => console.log('Background Task started'))
  .catch((err) => console.error(err));

};

// Stop the background task const stopTask = () => { BackgroundService.stop() .then(() => console.log('Background Task stopped')) .catch((err) => console.error(err)); };

return ( <View style={{ flex: 1 }}>

Background Task with Location Tracking
  <Button title="Start Task" onPress={startTask} />
  <Button title="Stop Task" onPress={stopTask} />

  <MapView
    style={{ flex: 1, marginTop: 10 }}
    initialRegion={{
      latitude: location.latitude || 37.78825, // Default coordinates if no location yet
      longitude: location.longitude || -122.4324,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421,
    }}
    region={{
      latitude: location.latitude || 37.78825,
      longitude: location.longitude || -122.4324,
      latitudeDelta: 0.015,
      longitudeDelta: 0.0121,
    }}
    showsUserLocation={true}
  >
    <Marker coordinate={{ latitude: location.latitude, longitude: location.longitude }} />
  </MapView>
</View>

); };

export default App;

Debug logs

christocracy commented 15 hours ago

The issue template requested some important information:

IMG_2355