React Native Background Location Tracking not working on Samsung Devices with Android 14

So the issue is that this code works fine on everyother device and fetches the results but when using Samsung devices with android 14 it doesn’t. It will still provide locations when in foreground but as soon as it gets moved to background it stops providing location updates.

CODE

import React, { useState } from 'react';
import {
    SafeAreaView,
    Text,
    StyleSheet,
    TouchableOpacity,
    PermissionsAndroid,
    Platform,
    Alert,
} from 'react-native';
import BackgroundService from 'react-native-background-actions';
import Geolocation from 'react-native-geolocation-service';

export default function App() {
    const [location, setLocation] = useState({});

    const sleep = (time) => new Promise((resolve) => setTimeout(resolve, time));

    const requestLocationPermission = async () => {
        if (Platform.OS === 'android') {
            try {
                const fineLocationGranted = await PermissionsAndroid.request(
                    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                    {
                        title: 'Fine Location Permission',
                        message: 'This app needs access to your precise location.',
                        buttonNeutral: 'Ask Me Later',
                        buttonNegative: 'Cancel',
                        buttonPositive: 'OK',
                    }
                );

                if (fineLocationGranted !== PermissionsAndroid.RESULTS.GRANTED) {
                    Alert.alert('Permission Denied', 'Fine location permission is required.');
                    return false;
                }

                const coarseLocationGranted = await PermissionsAndroid.request(
                    PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
                    {
                        title: 'Coarse Location Permission',
                        message: 'This app needs access to your approximate location.',
                        buttonNeutral: 'Ask Me Later',
                        buttonNegative: 'Cancel',
                        buttonPositive: 'OK',
                    }
                );

                if (coarseLocationGranted !== PermissionsAndroid.RESULTS.GRANTED) {
                    Alert.alert('Permission Denied', 'Coarse location permission is required.');
                    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) {
                    Alert.alert('Permission Denied', 'Background location permission is required.');
                    return false;
                }

                return true;

            } catch (err) {
                console.warn(err);
                return false;
            }
        }
        return true;
    };

    const sendLocationToServer = async (location) => {
        try {
            console.log('Sending location to server:', location);
            const response = await fetch('https://dummy.com/location', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(location),
            });
            const data = await response.text();
            console.log('Server response:', data);
        } catch (error) {
            console.error('Error sending location to server:', error);
        }
    };

    const veryIntensiveTask = async (taskDataArguments) => {
        const { delay } = taskDataArguments;

        await new Promise(async (resolve) => {
            for (let i = 0; BackgroundService.isRunning(); i++) {
                Geolocation.getCurrentPosition(
                    async (position) => {
                        console.log('Location received:', position);
                        const newLocation = {
                            latitude: position.coords.latitude,
                            longitude: position.coords.longitude,
                            timestamp: new Date().toLocaleTimeString(),
                        };
                        setLocation(newLocation);
                        await sendLocationToServer(newLocation);
                        console.log('Location dispatched to server:', newLocation);
                    },
                    (error) => {
                        console.error('Error receiving location:', error);
                    },
                    {
                        enableHighAccuracy: true,
                        distanceFilter: 0,
                        interval: 30000,
                        fastestInterval: 15000,
                        forceRequestLocation: true,
                        showLocationDialog: true,
                    }
                );

                await BackgroundService.updateNotification({
                    taskDesc: `Location tracking ${i}`,
                });

                await sleep(delay);
            }
        });
    };

    const options = {
        taskName: 'Location',
        taskTitle: 'Tracking Location',
        taskDesc: 'Tracking your location in the background',
        taskIcon: {
            name: 'ic_launcher',
            type: 'mipmap',
        },
        color: '#ff00ff',
        linkingURI: 'yourapp://location', // Adjust this to match your app's URI scheme
        parameters: {
            delay: 30000, // Set the delay to 30 seconds
        },
        foreground: true,
    };

    const startBackgroundService = async () => {
        const hasLocationPermission = await requestLocationPermission();
        if (!hasLocationPermission) {
            return;
        }

        // Check for battery optimization settings
        if (Platform.OS === 'android') {
            try {
                const isIgnoringOptimization = await BackgroundService.isIgnoringBatteryOptimizations();
                if (!isIgnoringOptimization) {
                    await BackgroundService.requestIgnoreBatteryOptimizations();
                }
            } catch (err) {
                console.warn(err);
            }
        }

        await BackgroundService.start(veryIntensiveTask, options);
        await BackgroundService.updateNotification({ taskDesc: 'Location tracking started' });
        console.log('Background service started');
    };

    const stopBackgroundService = async () => {
        await BackgroundService.stop();
        console.log('Background service stopped');
    };

    return (
        <SafeAreaView style={styles.container}>
            <Text style={styles.text}>Location Tracker</Text>
            <TouchableOpacity style={styles.button} onPress={startBackgroundService}>
                <Text style={styles.buttonText}>Start Background Service</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.button} onPress={stopBackgroundService}>
                <Text style={styles.buttonText}>Stop Background Service</Text>
            </TouchableOpacity>
            {location.latitude && (
                <Text style={styles.locationText}>
                    Latitude: {location.latitude}, Longitude: {location.longitude}, Time: {location.timestamp}
                </Text>
            )}
        </SafeAreaView>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#282C34',
        padding: 20,
    },
    text: {
        fontSize: 28,
        color: '#61DAFB',
        fontWeight: 'bold',
        marginBottom: 20,
    },
    button: {
        marginTop: 20,
        paddingVertical: 12,
        paddingHorizontal: 32,
        backgroundColor: '#61DAFB',
        borderRadius: 8,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.8,
        shadowRadius: 2,
        elevation: 5,
    },
    buttonText: {
        color: '#282C34',
        fontSize: 18,
        fontWeight: '600',
    },
    locationText: {
        fontSize: 18,
        color: 'white',
        marginTop: 20,
    },
});

ANDROID MANIFEST FILE

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
      <uses-permission android:name="android.permission.WAKE_LOCK" />
        <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />


    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
    </application>
</manifest>

Honestly I dont even know how to solve this because it is working fine for every other device like other devices with android 14 like pixel 8 or even samsung devices with android version < 14.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật