Как справиться с GetCurrentPosition (), висящим, если GPS выключен и включен во время выполнения?Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Как справиться с GetCurrentPosition (), висящим, если GPS выключен и включен во время выполнения?

Сообщение Anonymous »

Я пишу довольно простое приложение для погоды для Android, используя DART и Flutter.final geolocationProvider = FutureProvider((ref) async {
return await determinePosition();
});
< /code>
и обрабатывается в эксплуатации следующим образом: < /p>
import 'package:geolocator/geolocator.dart';
import 'package:shared_preferences/shared_preferences.dart';

//simple class to wrap coordinates. move this elswhere if needed.
class Coordinates {
final latitude;
final longitude;

Coordinates({required this.latitude, required this.longitude});
}

Future determinePosition() async {
bool serviceEnabled;
LocationPermission permission;

permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
//permission denied, so ask again next time
return Future.error('Location permissions are denied.');
}
}

if (permission == LocationPermission.deniedForever) {
//permissions are denied forever, handle appropriately.
//ask to turn them on for current location functionality
return Future.error('Location permissions are permanently denied, we cannot request permissions.\nOpen app settings and go to permissions.');
}

serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
//service disabled, so get last known location
final cachedLocation = await _getCachedLocation();
if (cachedLocation != null) {
return Coordinates(latitude: cachedLocation.latitude, longitude: cachedLocation.longitude);
}
return Future.error('Location services are disabled.' +
'\nNo last known location.' +
'\nPlease turn on geolocation and retry.' +
'\nThe first loading screen may take a minute.'
);
}

//if this is reached, then the location should be available
final location = await Geolocator.getCurrentPosition().timeout(
Duration(seconds: 5),
//the gps gets confused if turned on mid-runtime. this is here to address that
//TODO: improve this maybe?
onTimeout: () => Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best,
forceAndroidLocationManager: true
), //this takes longer so only use if gps is stuck
);

//cache the location
_cacheLocation(location.latitude, location.longitude);

return Coordinates(latitude: location.latitude, longitude: location.longitude);
}

//fucntion to cache the location
Future _cacheLocation(double lat, double lon) async {
final prefs = await SharedPreferences.getInstance(); //use shared preferences

prefs.setDouble('last_lat', lat);
prefs.setDouble('last_lon', lon);
}

//function to get the cached values if they exist
Future _getCachedLocation() async {
final prefs = await SharedPreferences.getInstance();

final lat = prefs.getDouble('last_lat');
final lon = prefs.getDouble('last_lon');

if (lat != null && lon != null) { //if cache exists return the stored values
return Coordinates(latitude: lat, longitude: lon);
}
return null;
}
< /code>
Определяется один раз в среде выполнения, если все проверки проходят успешно, и в противном случае либо бросает ошибку, либо считывает кэшированные значения (если доступно). Когда ошибка выброшена, она передается в простой Showdialog, и возможность повторить, выполняя < /p>
ref.invalidate(geolocationProvider)
< /code>
доступен. Проблема здесь заключается в том, что если приложение запущено с выключением службы GPS, и после диалога, в котором говорится, что «Поверните сервис GPS на» отображается, пользователь включает указанную службу и попадает в «повторную попытку», GPS, казалось бы, умирает. Очистка кэша и данных, включающий и выключенный GPS, все не работают.
Обходной путь, который я использую сейчас, - это часть: < /p>
onTimeout: () => Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best,
forceAndroidLocationManager: true
), //this takes longer so only use if gps is stuck
);
< /code>
Это работает, но требует от 30 секунд до минуты, чтобы возродить GPS. Я хочу улучшить это или вообще решить проблему, если это возможно.

Подробнее здесь: https://stackoverflow.com/questions/796 ... -on-during
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»