Я пишу довольно простое приложение для погоды для 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
Как справиться с GetCurrentPosition (), висящим, если GPS выключен и включен во время выполнения? ⇐ Android
Форум для тех, кто программирует под Android
1747425190
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. Я хочу улучшить это или вообще решить проблему, если это возможно.
Подробнее здесь: [url]https://stackoverflow.com/questions/79625862/how-do-i-handle-getcurrentposition-hanging-if-gps-is-turned-off-and-on-during[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия