ryuyoonju 07-29
1차커밋
@e432b931ed30e9a301c7c022f7bf66cf940bf2f6
android/app/src/main/assets/index.android.bundle
--- android/app/src/main/assets/index.android.bundle
+++ android/app/src/main/assets/index.android.bundle
This diff is too big to display.
src/api/ApiUtils.js
--- src/api/ApiUtils.js
+++ src/api/ApiUtils.js
@@ -52,6 +52,7 @@
   },
 
   sendTripLog: async (data, navigation) => {
+    console.log(data);
     try {
       // AsyncStorage에서 토큰 가져오기
       const tokenString = await AsyncStorage.getItem('token');
@@ -71,7 +72,7 @@
           const response = await apiInstance.post('/action/gps_update', data, {
             headers: {
               'Content-Type': 'application/json',
-              Authorization: `Bearer ${accessToken}`, // Bearer 스키마를 사용하도록 수정
+              Authorization: `${accessToken}`, // Bearer 스키마를 사용하도록 수정
             },
           });
           return response.data;
src/screen/GpsScreen.js
--- src/screen/GpsScreen.js
+++ src/screen/GpsScreen.js
@@ -1,18 +1,24 @@
 import React, { useState, useEffect } from 'react';
-import { View, Text, StyleSheet, Alert, TouchableOpacity } from 'react-native';
+import { View, Text, StyleSheet, Alert, TouchableOpacity, PermissionsAndroid } from 'react-native';
 import AsyncStorage from '@react-native-async-storage/async-storage';
 import crypto from 'crypto-js';
-import { startBackgroundTask, stopBackgroundTask, locations } from '../services/LocationService';
 import Api from '../api/ApiUtils';
 import { useNavigation } from '@react-navigation/native';
-import Icon from 'react-native-vector-icons/FontAwesome'; // FontAwesome 아이콘 사용
+import Icon from 'react-native-vector-icons/FontAwesome';
+import Geolocation from 'react-native-geolocation-service';
 
 const GpsScreen = () => {
     const [isMeasuring, setIsMeasuring] = useState(false);
-    const [elapsedTime, setElapsedTime] = useState(0); // 초 단위의 경과 시간
-    const [tripId, setTripId] = useState(''); // trip_id 상태 추가
-    const [userId, setUserId] = useState(''); // user_id 상태 추가
-    const navigation = useNavigation(); // useNavigation 훅으로 navigation 객체 가져오기
+    const [elapsedTime, setElapsedTime] = useState(0);
+    const [tripId, setTripId] = useState('');
+    const [userId, setUserId] = useState('');
+    const [locationData, setLocationData] = useState({
+        latitude: [],
+        longitude: [],
+        timestamp: []
+    }); // 위치 데이터 상태 수정
+    const [watchId, setWatchId] = useState(null);
+    const navigation = useNavigation();
 
     useEffect(() => {
         let timer;
@@ -20,7 +26,7 @@
         if (isMeasuring) {
             timer = setInterval(() => {
                 setElapsedTime(prevElapsedTime => prevElapsedTime + 1);
-            }, 1000); // 1초마다 실행
+            }, 1000);
         } else {
             clearInterval(timer);
         }
@@ -31,7 +37,6 @@
     }, [isMeasuring]);
 
     useEffect(() => {
-        // 앱이 처음 실행될 때 user_id를 AsyncStorage에서 가져옴
         const fetchUserId = async () => {
             try {
                 const storedUserId = await AsyncStorage.getItem('user_id');
@@ -47,52 +52,70 @@
     }, []);
 
     const generateTripId = () => {
-        // 해시 값을 생성
         const rand = Math.random().toString();
         const date = new Date();
         const sha256Hash = crypto.SHA256(rand + ',' + date.toString()).toString(crypto.enc.Hex);
         return sha256Hash;
     };
 
+    const requestLocationPermission = async () => {
+        try {
+            const granted = await PermissionsAndroid.request(
+                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
+            );
+            return granted === PermissionsAndroid.RESULTS.GRANTED;
+        } catch (err) {
+            console.warn(err);
+            return false;
+        }
+    };
+
     const handleStart = async () => {
+        const permissionGranted = await requestLocationPermission();
+        if (!permissionGranted) {
+            Alert.alert('위치 권한 오류', '위치 권한을 허용해야 합니다.');
+            return;
+        }
+
         try {
             const newTripId = generateTripId();
-            setTripId(newTripId); // trip_id 상태 업데이트
-            await startBackgroundTask();
+            setTripId(newTripId);
             setIsMeasuring(true);
+            startLocationTracking();
         } catch (error) {
-            console.error('Error starting background task:', error);
-            Alert.alert('백그라운드 작업 오류', '백그라운드 작업을 시작할 수 없습니다.');
+            console.error('Error starting location tracking:', error);
+            Alert.alert('오류', '위치 추적을 시작할 수 없습니다.');
             setIsMeasuring(false);
         }
     };
 
     const handleStop = async () => {
         setIsMeasuring(false);
-        setElapsedTime(0); // 시간 초기화
-        console.log('Measuring stopped.');
+        setElapsedTime(0);
+
+        if (watchId !== null) {
+            Geolocation.clearWatch(watchId);
+            setWatchId(null);
+        }
 
         try {
-            await stopBackgroundTask();
-
             const dataToSend = {
-                user_id: userId, // AsyncStorage에서 가져온 user_id 사용
-                trip_id: tripId, // 상태에서 trip_id 가져오기
-                trip_log: locations,
+                user_id: userId,
+                trip_id: tripId,
+                trip_log: locationData,
             };
 
             console.log('Data to send:', dataToSend);
 
-            // 서버로 전송
             try {
                 const response = await Api.sendTripLog(dataToSend, navigation);
-                console.log(":::::", response);
+                console.log("Response:", response);
             } catch (error) {
                 Alert.alert('로그인 실패', error.message);
             }
 
         } catch (error) {
-            console.error('Error stopping background task:', error);
+            console.error('Error stopping location tracking:', error);
         }
     };
 
@@ -107,12 +130,48 @@
         Alert.alert('히스토리', '히스토리 화면으로 이동합니다.');
     };
 
-    // 시간 형식으로 변환
+    const startLocationTracking = () => {
+        const id = Geolocation.watchPosition(
+            (position) => {
+                const { latitude, longitude } = position.coords;
+                const time = new Date().toISOString();
+                const timestamp = formatDate(time);
+                setLocationData(prevData => ({
+                    latitude: [...prevData.latitude, latitude],
+                    longitude: [...prevData.longitude, longitude],
+                    timestamp: [...prevData.timestamp, time]
+                }));
+
+                console.log('위치 업데이트:', { latitude, longitude, timestamp: time });
+            },
+            (error) => {
+                console.error('위치 감시 중 오류:', error);
+            },
+            { enableHighAccuracy: true, distanceFilter: 0, interval: 2000 }
+        );
+
+        setWatchId(id);
+    };
+
     const formatTime = (seconds) => {
         const hours = Math.floor(seconds / 3600);
         const minutes = Math.floor((seconds % 3600) / 60);
         const secs = seconds % 60;
         return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
+    };
+
+    // 한국 시간으로 변환하는 함수
+    const formatDate = (time) => {
+        const date = new Date(time);
+        const year = date.getFullYear();
+        const month = `0${date.getMonth() + 1}`.slice(-2);
+        const day = `0${date.getDate()}`.slice(-2);
+        const hours = `0${date.getHours()}`.slice(-2);
+        const minutes = `0${date.getMinutes()}`.slice(-2);
+        const seconds = `0${date.getSeconds()}`.slice(-2);
+        const milliseconds = `00${date.getMilliseconds()}`.slice(-3);
+
+        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
     };
 
     return (
@@ -126,7 +185,7 @@
                     onPress={handleStart}
                     disabled={isMeasuring}
                 >
-                    <Icon name="play" size={20} color="#FFFFFF"  />
+                    <Icon name="play" size={20} color="#FFFFFF" />
                     <Text style={styles.buttonText}>측정 시작</Text>
                 </TouchableOpacity>
                 <TouchableOpacity
@@ -224,7 +283,7 @@
 
     },
     fullWidthButtonText: {
-        color:'#007AFF',
+        color: '#007AFF',
         fontWeight: 'bold',
         fontSize: 16,
     },
src/services/LocationService.js
--- src/services/LocationService.js
+++ src/services/LocationService.js
@@ -16,9 +16,9 @@
     ios: 'best',
     android: 'mediumAccuracy',
   }[Platform.OS],
-  distanceFilter: 0, // meters
+  distanceFilter: 1, // meters
   interval: 1000, // 1 seconds
-  fastestInterval: 1000, // 5 seconds
+  fastestInterval: 5000, // 5 seconds
   forceRequestLocation: true
 
 };
@@ -58,8 +58,7 @@
           const timestamp = formatDate(time);
           locations.latitude.push(latitude);
           locations.longitude.push(longitude);
-          // locations.latitude.push(String(latitude));
-          // locations.longitude.push(String(longitude));
+         
           locations.timestamp.push(timestamp);
           console.log('Location updated:', { latitude, longitude, timestamp });
         },
Add a comment
List