Closed Naveenkumar-1411 closed 1 month ago
stopTimeout: 0,
Do you know what that does?
it not sending the data in the regular interval
What does it look like on a map? For example:
here is my image it is taking starting and end point
see wiki “Debugging”. Learn to fetch logs from the plug-in via .emailLog
stopTimeout: 0,
Do you know what that does? i think so it will stop tracking on the if the person waiting in the same place
Sorry,Shall i know what is the reason that data not sending when the device is off or the app is in background
Do you know what that does? i think so it will stop tracking on the if the person waiting in the same place
You don’t think a stopTimeout: 0 is a little to eager ? (eg stopped at a traffic light).
background-geolocation.log.gz here is my log
What particular range(s) of timestamps are you interested in from your logs? There are ~27 hours of logs there, spanning:
09-02 10:55:20.74
.
.
.
09-03 13:50:31.698
when device is in sleep but app is on it sending the data if the device is in sleep and app is in background it sending like below can you help me on this
i'm struggling in this location-tracking more than 1 1/2 months
Device manufacturer / model: Iqoo Z7
I just travelled across France this summer for over two weeks with my Android device stuffed in my suitcase (I never use this device). It was running in the background for days at a time.
https://www.transistorsoft.com/lab/france
your problem is likely related to your device manufacturer. See https://dontkillmyapp.com
I’ve been field-testing almost daily for over 10 years. The plug-in does not have a problem running for any length of time in the background.
Sorry i didn't complaint your plugin ,wheter need any addition of my code to run on the background even my device gets sleep import React, { useEffect, useState, useMemo, useRef } from "react"; import { SafeAreaView, Text, View, TouchableOpacity, Modal, StyleSheet, TextInput, Pressable, FlatList, Platform, Image, Linking, } from "react-native"; import styles from "../../../../../../css/Styles"; import FontAwesomeIcon from "react-native-vector-icons/FontAwesome"; import Entypo from "react-native-vector-icons/Entypo"; import { useNavigation } from "@react-navigation/native"; import BASE_URL from "../../../../../../utils/Api"; import RecordCollectionStyle from "../../../../../collection/collections/recordcollection/RecordCollectionStyle"; import RecordDepositStyle from "../../../../../collection/deosit/RecordDeposit/RecordDepositStyle"; import UserProfileStyle from "../../../profile/UserProfileStyle"; import axios from "axios"; import tw from "tailwind-react-native-classnames"; import { ScrollView } from "react-native-gesture-handler"; import as ImagePicker from "expo-image-picker"; import { CheckBox } from "react-native-elements"; import Buttons from "../../../../../../components/Buttons"; import FormData from "form-data"; import Header3 from "../../../../../../components/Header3"; import AttendanceStyle from "../AttendanceStyle"; import DealerAddStyle from "../../../../../sales/dealer/dealer_add/DealerAddStyle"; import { Octicons, Ionicons } from "@expo/vector-icons"; import { setBeat } from "../../../../../../redux/beat/BeatSlice"; import { Alert } from "react-native"; import Constants from "expo-constants"; import as Application from "expo-application"; import { setUser } from "../../../../../../redux/user/UserSlice"; import { useDispatch, useSelector } from "react-redux"; // import as Location from "expo-location"; // import as Battery from 'expo-battery'; //import { startLocationTracking } from "../../backgroundtask"; import BackgroundGeolocation from "react-native-background-geolocation";
// BackgroundGeolocation.registerHeadlessTask(async (event) => { // switch (event.name) { // case "location": // console.log("[BackgroundGeolocation HeadlessTask] - location: ", event.params); // // Handle the location event // break; // case "heartbeat": // console.log("[BackgroundGeolocation HeadlessTask] - heartbeat: ", event.params); // // Handle the heartbeat event // break; // // Add more cases for other events you want to handle // } // });
const AttendanceStart = () => { const dispatch = useDispatch(); const navigation = useNavigation(); const loginUser = useSelector((state) => state.user.user); const [kilometer, setKiloMeter] = useState(""); const [startDt, setStartDt] = useState(""); const userBeat = useSelector((state) => state.beat.beat); const [selectedImage, setSelectedImage] = useState(null); const [areaName, setAreaName] = useState(""); const [beatId, setBeatId] = useState(0); const [beatStatus, setBeatStatus] = useState(""); const userData = useSelector((state) => state.user.user); const [loading, setLoading] = useState(false); const [beatData, setBeatData] = useState(null); const [beatLength, setBeatLength] = useState(0); const [location, setLocation] = useState(null); const [errorMsg, setErrorMsg] = useState(null); const [locationSubscription, setLocationSubscription] = useState(null); const getCurrentDate = () => { const currentDate = new Date();
const date = currentDate.getDate();
const month = currentDate.getMonth() + 1;
const year = currentDate.getFullYear();
let currentHour = currentDate.getHours();
const currentMinutes = currentDate.getMinutes();
const currentSeconds = currentDate.getSeconds();
const ampm = currentHour >= 12 ? "PM" : "AM";
currentHour = currentHour % 12;
currentHour = currentHour ? currentHour : 12; // the hour '0' should be '12'
const paddedHour = currentHour < 10 ? `0${currentHour}` : currentHour;
const paddedMinutes =
currentMinutes < 10 ? `0${currentMinutes}` : currentMinutes;
const paddedSeconds =
currentSeconds < 10 ? `0${currentSeconds}` : currentSeconds;
const submitStartAt = `${year}/${month}/${date} ${paddedHour}:${paddedMinutes}:${paddedSeconds}`;
return {
date,
month,
year,
submitStartAt,
hour: paddedHour,
minutes: paddedMinutes,
seconds: paddedSeconds,
ampm,
};
};
const updateLoginUser = async () => {
try {
const response = await axios.post(${BASE_URL}/user/authorise
, {
auth_key: ${loginUser.auth_key}
,
unique_id: Constants.platform.android
? Application.getAndroidId()
: Application.installationId,
});
dispatch(setUser(response.data));
if (response.data) {
if (beatLength > 0) {
navigation.navigate("MyBeatDealerList", {
areaname: areaName,
beatid: beatId,
});
} else {
navigation.navigate("Dashboard");
}
}
} catch (error) {
console.log("error in updateLoginUser : " + error);
}
};
const fetchData = async () => {
try {
setLoading(true);
const endpoint = ${BASE_URL}/mybeats?action=today-beat&expand=mybeatDealers,areagroup,mybeatDealers.mybeatLists,mybeatDealers.dealer
;
const headers = {
Authorization: Bearer ${userData?.auth_key}
,
Cookie: "_csrf=AEkKVq4-6Virf2Se2PRCsxP0RP2YYTWr",
};
const response = await axios.get(endpoint, { headers });
if (response.data) {
setBeat(response.data);
setLoading(false);
setBeatData(response.data);
const areaName = response.data?.areagroup?.name || "-";
setBeatId(response.data?.id || 0);
setAreaName(areaName);
setBeatStatus(response.data?.status || "");
setBeatLength(response?.data?.mybeatDealers?.length || 0);
} else {
setAreaName("-");
}
// console.log(response.data,"Mybeat");
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
useEffect(() => { const result = getCurrentDate(); setStartDt(result.submitStartAt); }, []);
const startDay = async () => {
if (!selectedImage) {
Alert.alert("Image Required", "Please select or capture an image.");
return false;
}
//await startLocationTracking();
const payload = {
location: "",
start_dt: startDt,
AttendanceValue: [
{
name: "Start Km",
value: kilometer,
},
{
name: "Start Fuel",
value: "",
},
],
AttendanceTime: [
{
event: "DAYSTART",
geo: "",
source: "MOBILE",
},
],
};
console.log(JSON.stringify(payload) + " = payload in attendance ");
try {
const response = await axios.post(${BASE_URL}/attendances
, payload, {
headers: {
Authorization: Bearer ${loginUser.auth_key}
,
},
});
if (response.data) {
uploadMedia(response.data.id);
startLocationTracking();
} else {
alert("Error occurred");
}
} catch (error) {
console.error("Error starting day:", error);
alert("Error occurred while starting the day");
}
};
const startLocationTracking = () => {
BackgroundGeolocation.ready({
reset: true,
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
distanceFilter: 10,
stopTimeout: 5,
desiredOdometerAccuracy: 10,
stationaryRadius: 25,
debug: false, // Enable during testing
logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
stopOnTerminate: false,
startOnBoot: true,
heartbeatInterval: 30, // More frequent check-ins
locationUpdateInterval: 5000,
fastestLocationUpdateInterval: 5000,
allowIdenticalLocations: false,
locationAuthorizationRequest: 'Always',
maxBatchSize: 10,
maxDaysToPersist: 2,
foregroundService: true,
url: ${BASE_URL}/location/track
,
autoSync: true,
autoSyncThreshold: 0,
batchSync: true,
maxBatchSize: 10,
headers: {
Authorization: Bearer ${loginUser.auth_key}
,
},
params: {
device_uuid: Constants.platform.android
? Application.getAndroidId()
: Application.installationId,
employee_id: loginUser.profile.id,
},
})
.then((state) => {
if (!state.enabled) {
BackgroundGeolocation.start();
console.log("BackgroundGeolocation started successfully");
}
})
.catch((error) => {
console.error("BackgroundGeolocation error: ", error);
});
};
const uploadMedia = async (id) => { try { if (!selectedImage) { console.warn("No image selected"); return; }
const formData = new FormData();
const fileName = `StartAttendance_${id}_${Date.now()}.jpeg`;
formData.append("path", {
// uri: selectedImage,
uri:
Platform.OS === "android"
? selectedImage
: selectedImage.replace("file://", ""),
type: "image/jpeg",
name: selectedImage.split("/").pop(),
// name: "selectedImage3.jpeg",
});
// console.log(selectedImage, "Hello");
formData.append("module", "attendance");
formData.append("module_id", id);
formData.append("title", "Start Attendance");
// console.log("formData =", JSON.stringify(formData));
const response = await axios.post(`${BASE_URL}/media`, formData, {
headers: {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${loginUser.auth_key}`,
},
transformRequest: () => {
return formData;
},
});
if (response.data) {
// navigation.navigate("MyBeatDealerList", {
// areaname: userBeat?.areag0roup?.name,
// beatid: userBeat?.id,
// });
updateLoginUser();
// if(beatLength>0){
// navigation.navigate("MyBeatDealerList", {
// areaname: areaName,
// beatid: beatId,
// });
// }else{
// navigation.navigate("Dashboard");
// }
} else {
alert("Error occurred");
}
} catch (error) {
if (axios.isAxiosError(error) && error.response) {
console.error(
"Server responded with status code:",
error.response.status
);
console.log("Error response data:", error.response.data);
alert("An error occurred. Please check server logs for details.");
} else {
console.error("Error in uploadMedia:", error);
alert("An error occurred. Please try again.");
}
}
};
useEffect(() => { // Request permission to access the camera and gallery (async () => { const { status } = await ImagePicker.requestCameraPermissionsAsync(); if (status !== "granted") { Alert.alert( "Permission denied", "Sorry, we need camera and gallery permissions to make this work!" ); } })(); }, []); const pickImage = async (fromCamera) => { let result;
if (fromCamera) {
result = await ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [10, 9],
quality: 0.5,
});
} else {
result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: false,
aspect: [10, 9],
quality: 1,
});
}
if (!result.canceled) {
// Access selected assets through the "assets" array
const selectedAsset = result.assets[0];
// console.log(selectedAsset.uri);
setSelectedImage(selectedAsset.uri);
}
}; return ( <SafeAreaView style={[ Platform.OS === "android" && [AttendanceStyle.androidPlatform], styles.bgPrimary, ]}
<Header3 title="Attendance" onBackPress={() => navigation.navigate("Attendance")} onSubmit={() => startDay()} buttons={["StartDay"]} /> <View style={[styles.itemsCenter, styles.marginVerticalTen]}>
Hi {loginUser.user && loginUser.user.name}, Have a Nice Day! <View style={[ AttendanceStyle.roundedContainer, AttendanceStyle.marginHorizontal, ]}
<Text style={[styles.textSecondary, styles.textXl, styles.fontWeightBold]}
{getCurrentDate().hour}:{getCurrentDate().minutes}{" "} {getCurrentDate().ampm}
Dubai, {getCurrentDate().date}/{getCurrentDate().month}/ {getCurrentDate().year}
<View style={[ styles.bgTertiry, styles.paddingVerticalFour, styles.paddingHorizontal,
DealerAddStyle.mainBox,
]}
>
<View style={[styles.flexColumn]}>
<Text
style={[
styles.h4,
styles.textSecondary,
styles.paddingVertical,
styles.fontWeightSemiBold,
]}
>
Document Information
</Text>
<View style={[styles.flexRow, styles.justifyAround]}>
<TouchableOpacity
style={[
styles.flexRow,
styles.borderColorSecondary,
styles.paddingVerticalFour,
RecordDepositStyle.button,
]}
onPress={() => pickImage(true)}
>
<FontAwesomeIcon
name="camera"
size={30}
color="#7A6CE7"
style={[styles.marginHorizontalAuto]}
/>
<Text
style={[
styles.h4,
styles.textSecondary,
styles.marginHorizontalAuto,
styles.marginVerticalAuto,
styles.paddingLeftTwo,
styles.checkCenter,
]}
>
Camera
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[
styles.flexRow,
styles.borderColorSecondary,
styles.paddingVerticalFour,
RecordDepositStyle.button,
]}
onPress={() => pickImage(false)}
>
<FontAwesomeIcon
name="photo"
size={30}
color="#7A6CE7"
style={[styles.marginHorizontalAuto]}
/>
<Text
style={[
styles.h4,
styles.textSecondary,
styles.marginHorizontalAuto,
styles.marginVerticalAuto,
styles.paddingLeftTwo,
styles.checkCenter,
]}
>
Gallery
</Text>
</TouchableOpacity>
</View>
<Text
style={[styles.textCenter, styles.paddingVertical, styles.textGray]}
>
Upload file size less than 2MB.. ***
</Text>
{selectedImage && (
<Image source={{ uri: selectedImage }} style={sample.image} />
)}
</View>
</View>
</SafeAreaView>
); }; const sample = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center", }, title: { fontSize: 24, marginBottom: 20, }, image: { width: 275, height: 250, resizeMode: "cover", marginBottom: 20, }, button: { backgroundColor: "blue", padding: 10, margin: 10, borderRadius: 5, }, buttonText: { color: "white", fontSize: 16, }, });
export default AttendanceStart; here is my full code
Please learn to syntax highlight “fenced code blocks”, it’s easy.
wheter i need to use the background fetch
Please learn to syntax highlight “fenced code blocks”, it’s easy.
This issue is stale because it has been open for 30 days with no activity.
This issue was closed because it has been inactive for 14 days since being marked as stale.
Your Environment
react-native -v
):"0.74.1"