-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
554 lines (493 loc) · 19.4 KB
/
App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
*/
import BackgroundService from 'react-native-background-actions';
// import Geolocation from 'react-native-geolocation-service';
import Geolocation from '@react-native-community/geolocation'
// import AsyncStorage from '@react-native-async-storage/async-storage';
import { getGeolocation, setAccessToken, setGeolocation, addGeolocation, getGeolocations } from './components/services/storage';
import { insertGeolocation } from './components/services/api';
import React, { useEffect, useState } from 'react';
// import { Linking } from 'react-native';
import { PermissionsAndroid } from 'react-native';
import { PropsWithChildren, useCallback } from 'react';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
TouchableOpacity,
Button,
Linking,
Alert,
useColorScheme,
View,
} from 'react-native';
import {
Colors,
DebugInstructions,
Header,
LearnMoreLinks,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
// import BackgroundTask from './BackgroundTask';
// import { NativeModules } from 'react-native';
// import { BackHandler, DeviceEventEmitter } from 'react-native';
// import backgroundServer from 'react-native-background-actions';
import RNAndroidLocationEnabler from 'react-native-android-location-enabler';
import GeolocationRequest from './components/templates/geolocationrequest';
import { ResponseApi } from './components/models';
type SectionProps = PropsWithChildren<{
title: string;
}>;
// BackHandler.addEventListener('hardwareBackPress', () => { //(optional) you can use it if you need it
// //do not use this method if you are using navigation."preventBackClick: false" is already doing the same thing.
// LocationServicesDialogBox.forceCloseDialog();
// });
// DeviceEventEmitter.addListener('locationProviderStatusChange', function(status) { // only trigger when "providerListener" is enabled
// console.log(status); // status => {enabled: false, status: "disabled"} or {enabled: true, status: "enabled"}
// });
// const { BackgroundTask } = NativeModules;
// Geolocation.setRNConfiguration({
// skipPermissionRequests: true
// })
// Geolocation.setRNConfiguration({
// skipPermissionRequests: false,
// authorizationLevel: 'always',
// locationProvider: 'auto'
// })
interface DisplayStatus {
string?: string
color: string
}
function Section({ children, title }: SectionProps): JSX.Element {
const [stateGeolocation, setStateGeolocation] = useState<DisplayStatus>({ string: 'Iniciando rastreamento...', color: 'gray' })
const [geoInfo, setGeoInfo] = useState<any>(null)
const [isOnline, setIsOnline] = useState<any>(BackgroundService.isRunning())
// const [requestInf, setRequestInfo] = useState('')
// const [msg, setMsg] = useState('não tocou..')
useCallback
const questionLocation = async () => {
const granted = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
return granted
// if (granted) {
// console.log( "You can use the ACCESS_FINE_LOCATION" )
// }
// else {
// console.log( "ACCESS_FINE_LOCATION permission denied" )
// }
}
const sleep = (time: number) => new Promise<void>((resolve) => setTimeout(() => resolve(), time * 1000));
const StartTask = async () => {
// await clearGeolocation()
await sleep(10);
setIsOnline(true)
const veryIntensiveTask = async (taskDataArguments: any) => {
const { delay } = taskDataArguments;
await new Promise(async (resolve) => {
for (let i = 0; BackgroundService.isRunning(); i++) {
console.log(i);
// console.log("BACKGROUND: ", BackgroundService.listeners.toString())
// Geolocation.getCurrentPosition(async(info) => {console.log(info)}, (e)=>console.log("ERROR: ",e));
// await Geolocation.getCurrentPosition(async(info) => {console.log(info); await saveDataGeoLoc(JSON.stringify(info))});
// console.log("GET DATA -> ", await getDataGeoLoc())
Geolocation.getCurrentPosition(async (info) => {
// console.log(info)
// insertGeoLoc(info, setRequestInfo)
setGeoInfo({ ...info, acturenumber: i })
await addGeolocation(info)
// let geolocations = await getGeolocations()
// send gelocations
let statusRequest: ResponseApi = await insertGeolocation()
// let statusRequest: ResponseApi = await insertGeolocation(geolocations)
// let statusRequest = { status: true, message: "tudo ok" }
if (!statusRequest.status) {
await BackgroundService.updateNotification({ taskDesc: `Falha ao enviar dados!`, color: "red" }); // Only Android, iOS will ignore this call
setStateGeolocation({ string: statusRequest.message, color: '#FE0000' })
return
} else {
await BackgroundService.updateNotification({ taskDesc: `Monitoramento GPS ativado`, color: "green" }); // Only Android, iOS will ignore this call
setStateGeolocation({ string: 'Monitoramento GPS ativado', color: 'green' })
}
}, async (e: any) => {
if (e?.message) {
console.log("OPEN QUESTION!")
// await questionLocation()
// await requestLocationPermission()
let verify = await questionLocation()
if (!verify) {
setStateGeolocation({ string: `Falha ao capturar geolocalização\n${e.message}`, color: 'red' })
await BackgroundService.updateNotification({ taskDesc: `Falha ao capturar geolocalização\n${e.message}`, color: "red" }); // Only Android, iOS will ignore this call
} else {
setStateGeolocation({ string: `${e.message}`, color: '#FE0000' })
await BackgroundService.updateNotification({ taskDesc: `${e.message}`, color: "red" }); // Only Android, iOS will ignore this call
}
// Geolocation.requestAuthorization(async()=>{console.log("SUCCESS")}, async(e)=>console.log("ERRO: ", e))
// Geolocation.requestAuthorization(async()=>{console.log("SUCCESS")}, async(e)=>console.log("ERRO: ", e))
// getPermission()
}
console.log(e)
}, { timeout: 10000, enableHighAccuracy: true });
await sleep(delay);
}
});
};
const options = {
taskName: 'MandaFrete',
taskTitle: 'MandaFrete',
taskDesc: 'GeoLocalization Listening...',
taskIcon: {
name: 'ic_launcher',
type: 'mipmap',
},
color: '#ff00ff',
linkingURI: 'geoLocTask://chat/jane', // See Deep Linking for more info
parameters: {
delay: 5,
},
};
if (!BackgroundService.isRunning()) {
await BackgroundService.start(veryIntensiveTask, options);
await BackgroundService.updateNotification({ taskDesc: 'Inicializando monitoramento...', linkingURI: "" }); // Only Android, iOS will ignore this call
console.log("NÃO ESTÁ RODANDO....")
}
// console.log(BackgroundService.)
// iOS will also run everything here in the background until .stop() is called
// await BackgroundService.stop();
}
// const preStartTask = async() => {
// let geolocation = await getGeolocation()
// let questionloc = await questionLocation()
// console.log("GEOLOCATION PERMITION STATUS SAVED: ", geolocation)
// console.log("GEOLOCATIONL PERMITION: ", questionloc)
// if(geolocation){
// StartTask()
// } else {
// setStateGeolocation({string:`Premissão para geolocalização não habilitado`, color:'red'})
// if (questionloc){
// setGeolocation("t")
// StartTask()
// // break
// }
// while(!questionloc){
// console.log("verificando....")
// questionloc = await questionLocation()
// if (questionloc){
// setGeolocation("t")
// StartTask()
// break
// }
// await sleep(3)
// }
// }
// }
const preStartTask = useCallback(async () => {
setStateGeolocation({ string: 'Iniciando rastreamento...', color: 'gray' })
let geolocation = await getGeolocation()
let questionloc = await questionLocation()
console.log("GEOLOCATION PERMITION STATUS SAVED: ", geolocation)
console.log("GEOLOCATIONL PERMITION: ", questionloc)
if(geolocation){
StartTask()
} else {
setStateGeolocation({string:`Premissão para geolocalização não habilitado`, color:'red'})
if (questionloc){
setGeolocation("t")
StartTask()
// break
}
while(!questionloc){
console.log("verificando....")
questionloc = await questionLocation()
if (questionloc){
setGeolocation("t")
StartTask()
break
}
await sleep(3)
}
}
}, [])
useEffect(() => {
if (BackgroundService.isRunning()) {
BackgroundService.stop()
}
}, [])
// AsyncStorage.clear()
useEffect(() => {
const activateGps = async () => {
RNAndroidLocationEnabler.promptForEnableLocationIfNeeded({
interval: 10000,
fastInterval: 5000,
})
.then((data) => {
// The user has accepted to enable the location services
// data can be :
// - "already-enabled" if the location services has been already enabled
// - "enabled" if user has clicked on OK button in the popup
})
.catch((err) => {
// The user has not accepted to enable the location services or something went wrong during the process
// "err" : { "code" : "ERR00|ERR01|ERR02|ERR03", "message" : "message"}
// codes :
// - ERR00 : The user has clicked on Cancel button in the popup
// - ERR01 : If the Settings change are unavailable
// - ERR02 : If the popup has failed to open
// - ERR03 : Internal error
});
}
activateGps()
// Geolocation.requestAuthorization();
// const questionLocation = async() => {
// const granted = await PermissionsAndroid.check( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION );
// return granted
// // if (granted) {
// // console.log( "You can use the ACCESS_FINE_LOCATION" )
// // }
// // else {
// // console.log( "ACCESS_FINE_LOCATION permission denied" )
// // }
// }
// const getPermission = () => {
// Geolocation.requestAuthorization();
// }
// const sleep = (time: number) => new Promise<void>((resolve) => setTimeout(() => resolve(), time * 1000));
// const StartTask = async () => {
// // await clearGeolocation()
// await sleep(10);
// const veryIntensiveTask = async (taskDataArguments: any) => {
// const { delay } = taskDataArguments;
// await new Promise( async (resolve) => {
// for (let i = 0; BackgroundService.isRunning(); i++) {
// // console.log(i);
// // console.log("BACKGROUND: ", BackgroundService.listeners.toString())
// // Geolocation.getCurrentPosition(async(info) => {console.log(info)}, (e)=>console.log("ERROR: ",e));
// // await Geolocation.getCurrentPosition(async(info) => {console.log(info); await saveDataGeoLoc(JSON.stringify(info))});
// // console.log("GET DATA -> ", await getDataGeoLoc())
// Geolocation.getCurrentPosition(async(info)=>{
// // console.log(info)
// // insertGeoLoc(info, setRequestInfo)
// setGeoInfo({...info, acturenumber: i})
// // await addGeolocation(info)
// // let geolocations = await getGeolocations()
// // send gelocations
// // let statusRequest: ResponseApi = await insertGeolocation()
// // let statusRequest: ResponseApi = await insertGeolocation(geolocations)
// let statusRequest = {status:true, message:"tudo ok"}
// if(!statusRequest.status){
// await BackgroundService.updateNotification({taskDesc: `Falha ao enviar dados!`, color: "red"}); // Only Android, iOS will ignore this call
// setStateGeolocation({string:statusRequest.message, color:'#FE0000'})
// return
// }else {
// await BackgroundService.updateNotification({taskDesc: `Monitoramento GPS ativado`, color: "green"}); // Only Android, iOS will ignore this call
// setStateGeolocation({string:'Monitoramento GPS ativado', color:'green'})
// }
// }, async(e: any)=>{
// if(e?.message){
// console.log("OPEN QUESTION!")
// // await questionLocation()
// // await requestLocationPermission()
// let verify = await questionLocation()
// if(!verify){
// setStateGeolocation({string:`Falha ao capturar geolocalização\n${e.message}`, color:'red'})
// await BackgroundService.updateNotification({taskDesc: `Falha ao capturar geolocalização\n${e.message}`, color: "red"}); // Only Android, iOS will ignore this call
// } else {
// setStateGeolocation({string:`${e.message}`, color:'#FE0000'})
// await BackgroundService.updateNotification({taskDesc: `${e.message}`, color: "red"}); // Only Android, iOS will ignore this call
// }
// // Geolocation.requestAuthorization(async()=>{console.log("SUCCESS")}, async(e)=>console.log("ERRO: ", e))
// // Geolocation.requestAuthorization(async()=>{console.log("SUCCESS")}, async(e)=>console.log("ERRO: ", e))
// // getPermission()
// }
// console.log(e)
// }, {timeout: 10000,enableHighAccuracy:true});
// await sleep(delay);
// }
// });
// };
// const options = {
// taskName: 'MandaFrete',
// taskTitle: 'MandaFrete',
// taskDesc: 'GeoLocalization Listening...',
// taskIcon: {
// name: 'ic_launcher',
// type: 'mipmap',
// },
// color: '#ff00ff',
// linkingURI: 'geoLocTask://chat/jane', // See Deep Linking for more info
// parameters: {
// delay: 5,
// },
// };
// if(!BackgroundService.isRunning()){
// await BackgroundService.start(veryIntensiveTask, options);
// await BackgroundService.updateNotification({taskDesc: 'Inicializando monitoramento...', linkingURI:""}); // Only Android, iOS will ignore this call
// console.log("NÃO ESTÁ RODANDO....")
// }
// // console.log(BackgroundService.)
// // iOS will also run everything here in the background until .stop() is called
// // await BackgroundService.stop();
// }
// const preStartTask = async() => {
// let geolocation = await getGeolocation()
// let questionloc = await questionLocation()
// console.log("GEOLOCATION PERMITION STATUS SAVED: ", geolocation)
// console.log("GEOLOCATIONL PERMITION: ", questionloc)
// if(geolocation){
// StartTask()
// } else {
// setStateGeolocation({string:`Premissão para geolocalização não habilitado`, color:'red'})
// if (questionloc){
// setGeolocation("t")
// StartTask()
// // break
// }
// while(!questionloc){
// console.log("verificando....")
// questionloc = await questionLocation()
// if (questionloc){
// setGeolocation("t")
// StartTask()
// break
// }
// await sleep(3)
// }
// }
// }
preStartTask()
}, [setGeoInfo, preStartTask])
const startStop = async() => {
if(isOnline){
setIsOnline(false)
await BackgroundService.stop()
return
}
setIsOnline(true)
await preStartTask()
}
const isDarkMode = useColorScheme() === 'dark';
return (
<View style={styles.sectionContainer}>
<Text
style={[
styles.sectionTitle,
{
color: isDarkMode ? Colors.white : Colors.black,
},
]}>
{title}
</Text>
<Text style={{ color: stateGeolocation.color, fontWeight: 'bold' }}>
{stateGeolocation?.string && stateGeolocation?.string}
</Text>
{stateGeolocation.color == "red" && <GeolocationRequest />}
<TouchableOpacity style={styles.button} onPress={() => Linking.openSettings()}>
<Text style={{ color: 'white', fontWeight: 'bold' }}>
Configurações do app
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={()=>startStop()} style={isOnline ? styles.buttonStop : styles.buttonStart}>
<Text style={{ color: 'white', fontWeight: 'bold' }}>
{isOnline ? "Parar Monitoramento" : "Iniciar Monitoramento"}
</Text>
</TouchableOpacity>
{/* <Button title="Clique aqui" onPress={()=> Linking.openSettings()}/> */}
{/* </Button> */}
<Text>
{geoInfo && `
Altitude: ${geoInfo.coords.altitude}
Longitude: ${geoInfo.coords.longitude}
Latitude: ${geoInfo.coords.latitude}
Speed: ${geoInfo.coords.speed}
Accuracy: ${geoInfo.coords.accuracy}
Captura n: ${geoInfo.acturenumber}
`}
</Text>
<Text
style={[
styles.sectionDescription,
{
color: isDarkMode ? Colors.light : Colors.dark,
},
]}>
{children}
</Text>
</View>
);
}
function App(): JSX.Element {
const isDarkMode = useColorScheme() === 'dark';
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<SafeAreaView style={backgroundStyle}>
<ScrollView
contentInsetAdjustmentBehavior="automatic">
{/* <Header /> */}
<View
style={{
backgroundColor: isDarkMode ? Colors.black : Colors.white,
}}>
<Section title="MandaFrete">
App
</Section>
</View>
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
},
highlight: {
fontWeight: '700',
},
button: {
backgroundColor: "gray",
marginTop: 15,
padding: 10,
borderRadius: 16,
fontSize: 50,
textAlign: 'center',
alignItems: 'center'
},
buttonStart: {
backgroundColor: "green",
marginTop: 15,
padding: 10,
borderRadius: 16,
fontSize: 50,
textAlign: 'center',
alignItems: 'center',
fontWeight: 'bold',
color: 'white',
},
buttonStop: {
backgroundColor: "red",
marginTop: 15,
padding: 10,
borderRadius: 16,
fontSize: 50,
color: 'white',
textAlign: 'center',
alignItems: 'center',
fontWeight: 'bold'
}
});
export default App;