Reputation: 3986
I wanted to run deviceInfo function which is written below once user enabled the GPS/Location Services. Currently it is running only to check Location Services is enabled or not. If its disabled then it shows alert dialog.
As you can see i am using If condition. If location is disabled then show the alert dialog else proceed to the next step.
Problem is if user enable the locations services then how can i execute code those are written under else condition.
Here is the code.
Future<void> deviceInfo() async {
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
print(androidInfo.androidId);
print('Is Physical Device: ${androidInfo.isPhysicalDevice}');
physicaldevice = androidInfo.isPhysicalDevice;
if(physicaldevice == true){
var isGpsEnabled = await Geolocator().isLocationServiceEnabled();
if(isGpsEnabled == false){
setState(() {
visible = false;
});
_showAlert(context);
print(isGpsEnabled);
}else{
------ Some Codes if GPS is enabled ------
}
Here is the AlertBox for GPS enable message
void _showAlert(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text("Error"),
content: Text("Location Service is disabled. Please enable it."),
actions: <Widget>[
FlatButton(child: Text('Ok'),
onPressed: () {
final AndroidIntent intent = AndroidIntent(
action: 'android.settings.LOCATION_SOURCE_SETTINGS');
intent.launch();
Navigator.of(context, rootNavigator: true).pop();
})],
)
);
}
In Simple words i want to re-run DeviceInfo function once GPS is enabled.
Upvotes: 1
Views: 735
Reputation: 506
You can try using Timer.periodic if isGpsEnabled is false
Future<void> deviceInfo() async {
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
print(androidInfo.androidId);
print('Is Physical Device: ${androidInfo.isPhysicalDevice}');
physicaldevice = androidInfo.isPhysicalDevice;
if(physicaldevice == true){
var isGpsEnabled = await Geolocator().isLocationServiceEnabled();
if(isGpsEnabled == false){
setState(() {
visible = false;
});
_showAlert(context);
print(isGpsEnabled);
// new code //
Timer.periodic(Duration(seconds: 1), (timer) async {
var isGpsEnabled = await Geolocator().isLocationServiceEnabled();
if (isGpsEnabled) {
timer.cancel();
------ Some Codes if GPS is enabled ------
}
});
}else{
------ Some Codes if GPS is enabled ------
}
Upvotes: 2