Add location tracking switch disabled by default

This commit is contained in:
estevez-dev 2019-08-31 23:09:30 +03:00
parent 623634cb6e
commit cece4d1e16
2 changed files with 112 additions and 66 deletions

View File

@ -87,64 +87,89 @@ class LocationManager {
void _startLocationService() async { void _startLocationService() async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.reload(); await prefs.reload();
Duration locationUpdateInterval = Duration(minutes: prefs.getInt("location-interval") ?? defaultUpdateIntervalMinutes); bool enabled = prefs.getBool("location-enabled") ?? false;
Logger.d("Canceling previous schedule if any..."); if (enabled) {
await AndroidAlarmManager.cancel(alarmId); Duration locationUpdateInterval = Duration(
Logger.d("Scheduling location update for every ${locationUpdateInterval.inMinutes} minutes..."); minutes: prefs.getInt("location-interval") ??
await AndroidAlarmManager.periodic( defaultUpdateIntervalMinutes);
locationUpdateInterval, Logger.d("Canceling previous schedule if any...");
alarmId, await AndroidAlarmManager.cancel(alarmId);
LocationManager.updateDeviceLocationIsolate, Logger.d("Scheduling location update for every ${locationUpdateInterval
wakeup: true, .inMinutes} minutes...");
rescheduleOnReboot: true await AndroidAlarmManager.periodic(
); locationUpdateInterval,
alarmId,
LocationManager.updateDeviceLocationIsolate,
wakeup: true,
rescheduleOnReboot: true
);
} else {
Logger.d("Location tracking is disabled");
Logger.d("Canceling previous schedule if any...");
await AndroidAlarmManager.cancel(alarmId);
}
} }
void updateDeviceLocation() async { void updateDeviceLocation() async {
print("[Location] started"); print("[Location] started");
if (ConnectionManager().webhookId != null && ConnectionManager().webhookId.isNotEmpty) { SharedPreferences prefs = await SharedPreferences.getInstance();
DateTime currentTime = DateTime.now(); await prefs.reload();
String timeData = "${currentTime.year}-${currentTime.month}-${currentTime.day} ${currentTime.hour}:${currentTime.minute}"; bool enabled = prefs.getBool("location-enabled") ?? false;
print("[Location] Sending test time data home..."); if (enabled) {
String url = "${ConnectionManager().httpWebHost}/api/webhook/${ConnectionManager().webhookId}"; if (ConnectionManager().webhookId != null &&
Map<String, String> headers = {}; ConnectionManager().webhookId.isNotEmpty) {
headers["Content-Type"] = "application/json"; DateTime currentTime = DateTime.now();
var data = { String timeData = "${currentTime.year}-${currentTime
"type": "call_service", .month}-${currentTime.day} ${currentTime.hour}:${currentTime
"data": { .minute}";
"domain": "input_datetime", print("[Location] Sending test time data home...");
"service": "set_datetime", String url = "${ConnectionManager()
"service_data": { .httpWebHost}/api/webhook/${ConnectionManager().webhookId}";
"entity_id": "input_datetime.app_alarm_service_test", Map<String, String> headers = {};
"datetime": timeData headers["Content-Type"] = "application/json";
var data = {
"type": "call_service",
"data": {
"domain": "input_datetime",
"service": "set_datetime",
"service_data": {
"entity_id": "input_datetime.app_alarm_service_test",
"datetime": timeData
}
} }
} };
}; await http.post(
await http.post( url,
url, headers: headers,
headers: headers, body: json.encode(data)
body: json.encode(data) );
); Logger.d("[Location] Getting device location...");
Logger.d("[Location] Getting device location..."); Position location = await Geolocator().getCurrentPosition(
Position location = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.medium); desiredAccuracy: LocationAccuracy.medium);
Logger.d("[Location] Got location: ${location.latitude} ${location.longitude}. Sending home..."); Logger.d("[Location] Got location: ${location.latitude} ${location
int battery = DateTime.now().hour; .longitude}. Sending home...");
data = { int battery = DateTime
"type": "update_location", .now()
"data": { .hour;
"gps": [location.latitude, location.longitude], data = {
"gps_accuracy": location.accuracy, "type": "update_location",
"battery": battery "data": {
} "gps": [location.latitude, location.longitude],
}; "gps_accuracy": location.accuracy,
await http.post( "battery": battery
url, }
headers: headers, };
body: json.encode(data) await http.post(
); url,
Logger.d("[Location] ...done."); headers: headers,
body: json.encode(data)
);
Logger.d("[Location] ...done.");
} else {
print("[Location] No webhook id. Aborting");
}
} else { } else {
print("[Location] No webhook id. Aborting"); Logger.d("[Location] Location tracking is disabled");
} }
} }

View File

@ -9,8 +9,9 @@ class ConfigPanelWidget extends StatefulWidget {
class _ConfigPanelWidgetState extends State<ConfigPanelWidget> { class _ConfigPanelWidgetState extends State<ConfigPanelWidget> {
int locationInterval; int _locationInterval = LocationManager().defaultUpdateIntervalMinutes;
bool needToRestartLocationTracking = false; bool _locationTrackingEnabled = false;
bool _needToRestartLocationTracking = false;
@override @override
void initState() { void initState() {
@ -23,29 +24,30 @@ class _ConfigPanelWidgetState extends State<ConfigPanelWidget> {
await prefs.reload(); await prefs.reload();
SharedPreferences.getInstance().then((prefs) { SharedPreferences.getInstance().then((prefs) {
setState(() { setState(() {
locationInterval = prefs.getInt("location-interval") ?? LocationManager().defaultUpdateIntervalMinutes; _locationTrackingEnabled = prefs.getBool("location-enabled") ?? false;
_locationInterval = prefs.getInt("location-interval") ?? LocationManager().defaultUpdateIntervalMinutes;
}); });
}); });
} }
void incLocationInterval() { void incLocationInterval() {
needToRestartLocationTracking = true; _needToRestartLocationTracking = true;
if (locationInterval < 720) { if (_locationInterval < 720) {
setState(() { setState(() {
locationInterval = locationInterval + 1; _locationInterval = _locationInterval + 1;
}); });
SharedPreferences.getInstance().then((prefs) => prefs.setInt("location-interval", locationInterval)); SharedPreferences.getInstance().then((prefs) => prefs.setInt("location-interval", _locationInterval));
} }
} }
void decLocationInterval() { void decLocationInterval() {
needToRestartLocationTracking = true; _needToRestartLocationTracking = true;
if (locationInterval > 1) { if (_locationInterval > 1) {
setState(() { setState(() {
locationInterval = locationInterval - 1; _locationInterval = _locationInterval - 1;
}); });
SharedPreferences.getInstance().then((prefs) { SharedPreferences.getInstance().then((prefs) {
prefs.setInt("location-interval", locationInterval); prefs.setInt("location-interval", _locationInterval);
}); });
} }
} }
@ -131,6 +133,22 @@ class _ConfigPanelWidgetState extends State<ConfigPanelWidget> {
Divider(), Divider(),
Text("Location tracking", style: TextStyle(fontSize: Sizes.largeFontSize-2)), Text("Location tracking", style: TextStyle(fontSize: Sizes.largeFontSize-2)),
Container(height: Sizes.rowPadding,), Container(height: Sizes.rowPadding,),
Row(
children: <Widget>[
Text("Enable device location tracking"),
Switch(
value: _locationTrackingEnabled,
onChanged: (value) {
SharedPreferences.getInstance().then((prefs) => prefs.setBool("location-enabled", value));
setState(() {
_locationTrackingEnabled = value;
_needToRestartLocationTracking = true;
});
},
),
],
),
Container(height: Sizes.rowPadding,),
Text("Location update interval in minutes:"), Text("Location update interval in minutes:"),
Row( Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
@ -142,7 +160,7 @@ class _ConfigPanelWidgetState extends State<ConfigPanelWidget> {
child: Text("+", style: TextStyle(fontSize: Sizes.largeFontSize)), child: Text("+", style: TextStyle(fontSize: Sizes.largeFontSize)),
onPressed: () => incLocationInterval(), onPressed: () => incLocationInterval(),
), ),
Text("$locationInterval", style: TextStyle(fontSize: Sizes.largeFontSize)), Text("$_locationInterval", style: TextStyle(fontSize: Sizes.largeFontSize)),
FlatButton( FlatButton(
padding: EdgeInsets.all(0.0), padding: EdgeInsets.all(0.0),
child: Text("-", style: TextStyle(fontSize: Sizes.largeFontSize)), child: Text("-", style: TextStyle(fontSize: Sizes.largeFontSize)),
@ -173,9 +191,12 @@ class _ConfigPanelWidgetState extends State<ConfigPanelWidget> {
@override @override
void dispose() { void dispose() {
if (needToRestartLocationTracking) { if (_needToRestartLocationTracking) {
Logger.d("Location tracking interval was changed. Rescheduling location service..."); Logger.d("Location tracking settings was changed. Restarting location service...");
LocationManager()._startLocationService(); LocationManager()._startLocationService();
if (_locationTrackingEnabled) {
LocationManager().updateDeviceLocation();
}
} }
super.dispose(); super.dispose();
} }