Hello,
I am using @capacitor/geolocation to get the position of the user. Here is the code:
import { ForegroundService } from '@capawesome-team/capacitor-android-foreground-service';
import { Position, Geolocation } from '@capacitor/geolocation';
async startForegroundService() {
await ForegroundService.startForegroundService({
buttons: [
{
id: 1,
title: 'Stop',
},
],
body: 'This is the body of the notification',
title: 'This is the title of the notification',
id: 12398473,
smallIcon: 'push_icon',
}).then(async () => {
this.watchId = await Geolocation.watchPosition(
{ enableHighAccuracy: true, timeout: 5000 },
(position, err) => {
if (err) {
console.log(err);
}
this.addPosition(position)
}
);
});
}
It only works when the application is in the foreground, but when I put it in the background, the callback in watchPosition is not called anymore. It works again when I go back in the application.
I also tried to use Geolocation.getCurrentPosition():
async startForegroundService() {
await ForegroundService.startForegroundService({
buttons: [
{
id: 1,
title: 'Stop',
},
],
body: 'This is the body of the notification',
title: 'This is the title of the notification',
id: 12398473,
smallIcon: 'push_icon',
}).then(async () => this.timeout());
}
timeout() {
console.log("TIMEOUT");
if (this.isCurrentRide$.getValue()) {
setTimeout(async () => {
console.log('INSIDE_TIMEOUT');
try {
const pos = await Geolocation.getCurrentPosition({ timeout: 5000 });
console.log('POS', pos);
} catch (error) {
console.error("ERROR", error);
}
this.timeout();
}, 1000);
}
}
Unlike the first method, this one is more hazardous as it does not work sometimes. But, when it does, it works correctly when the application is open but when I put it in the background, it can’t get the position anymore (until I open the application again). It continues to call getCurrentPosition() but it always returns an error saying that the position is unavailable:
ERROR Error: location unavailable
I have given all the necessary permissions:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
I am testing with an Android Studio emulator (Pixel 7, API 33).