Senty reporting. Fix background location tracking crash

This commit is contained in:
Yegor Vialov 2019-11-27 12:26:55 +00:00
parent e634253282
commit 1a9fec8b98
4 changed files with 44 additions and 33 deletions

View File

@ -30,6 +30,7 @@ import 'package:uni_links/uni_links.dart';
import 'package:workmanager/workmanager.dart' as workManager; import 'package:workmanager/workmanager.dart' as workManager;
import 'package:geolocator/geolocator.dart'; import 'package:geolocator/geolocator.dart';
import 'package:battery/battery.dart'; import 'package:battery/battery.dart';
import 'package:sentry/sentry.dart';
import 'utils/logger.dart'; import 'utils/logger.dart';
@ -138,6 +139,7 @@ part 'entities/media_player/widgets/media_player_progress_bar.widget.dart';
part 'pages/whats_new.page.dart'; part 'pages/whats_new.page.dart';
EventBus eventBus = new EventBus(); EventBus eventBus = new EventBus();
final SentryClient _sentry = SentryClient(dsn: "https://03ef364745cc4c23a60ddbc874c69925@sentry.io/1836118");
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin(); FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
const String appName = "HA Client"; const String appName = "HA Client";
@ -145,11 +147,31 @@ const appVersionNumber = "0.7.4";
const appVersionAdd = ""; const appVersionAdd = "";
const appVersion = "$appVersionNumber$appVersionAdd"; const appVersion = "$appVersionNumber$appVersionAdd";
void main() async { Future<void> _reportError(dynamic error, dynamic stackTrace) async {
FlutterError.onError = (errorDetails) { // Print the exception to the console.
Logger.e( "${errorDetails.exception}");
if (Logger.isInDebugMode) { if (Logger.isInDebugMode) {
FlutterError.dumpErrorToConsole(errorDetails); Logger.e('Caught error: $error');
Logger.p(stackTrace);
return;
} else {
Logger.e('Caught error: $error. Reporting to Senrty.');
// Send the Exception and Stacktrace to Sentry in Production mode.
_sentry.captureException(
exception: error,
stackTrace: stackTrace,
);
}
}
void main() async {
FlutterError.onError = (FlutterErrorDetails details) {
Logger.e(" Caut Flutter runtime error: ${details.exception}");
if (Logger.isInDebugMode) {
FlutterError.dumpErrorToConsole(details);
} else {
// In production mode, report to the application zone to report to
// Sentry.
Zone.current.handleUncaughtError(details.exception, details.stack);
} }
}; };
@ -161,11 +183,7 @@ void main() async {
runApp(new HAClientApp()); runApp(new HAClientApp());
}, onError: (error, stack) { }, onError: (error, stack) {
Logger.e("$error"); _reportError(error, stack);
Logger.e("$stack");
if (Logger.isInDebugMode) {
debugPrint("$stack");
}
}); });
} }

View File

@ -83,7 +83,7 @@ class LocationManager {
Logger.d("Scheduling location update task #$i for every ${interval.inMinutes} minutes in $delay minutes..."); Logger.d("Scheduling location update task #$i for every ${interval.inMinutes} minutes in $delay minutes...");
await workManager.Workmanager.registerPeriodicTask( await workManager.Workmanager.registerPeriodicTask(
"$backgroundTaskId$n", "$backgroundTaskId$n",
"haClientLocationTracking", "haClientLocationTracking-0$n",
tag: backgroundTaskTag, tag: backgroundTaskTag,
inputData: { inputData: {
"webhookId": webhookId, "webhookId": webhookId,
@ -109,8 +109,7 @@ class LocationManager {
updateDeviceLocation() async { updateDeviceLocation() async {
Logger.d("[Foreground location] Started"); Logger.d("[Foreground location] Started");
//Logger.d("[Foreground location] Forcing Android location manager..."); Geolocator geolocator = Geolocator();
Geolocator geolocator = Geolocator()..forceAndroidLocationManager = true;
var battery = Battery(); var battery = Battery();
String webhookId = ConnectionManager().webhookId; String webhookId = ConnectionManager().webhookId;
String httpWebHost = ConnectionManager().httpWebHost; String httpWebHost = ConnectionManager().httpWebHost;
@ -150,14 +149,14 @@ class LocationManager {
void updateDeviceLocationIsolate() { void updateDeviceLocationIsolate() {
workManager.Workmanager.executeTask((backgroundTask, data) { workManager.Workmanager.executeTask((backgroundTask, data) {
//print("[Background $backgroundTask] Started"); print("[Background $backgroundTask] Started");
Geolocator geolocator = Geolocator()..forceAndroidLocationManager = true; Geolocator geolocator = Geolocator();
var battery = Battery(); var battery = Battery();
int batteryLevel = 100; int batteryLevel = 100;
String webhookId = data["webhookId"]; String webhookId = data["webhookId"];
String httpWebHost = data["httpWebHost"]; String httpWebHost = data["httpWebHost"];
if (webhookId != null && webhookId.isNotEmpty) { if (webhookId != null && webhookId.isNotEmpty) {
//print("[Background $backgroundTask] hour=$battery"); print("[Background $backgroundTask] hour=$battery");
String url = "$httpWebHost/api/webhook/$webhookId"; String url = "$httpWebHost/api/webhook/$webhookId";
Map<String, String> headers = {}; Map<String, String> headers = {};
headers["Content-Type"] = "application/json"; headers["Content-Type"] = "application/json";
@ -169,36 +168,25 @@ void updateDeviceLocationIsolate() {
"battery": batteryLevel "battery": batteryLevel
} }
}; };
//print("[Background $backgroundTask] Getting battery level..."); print("[Background $backgroundTask] Getting battery level...");
battery.batteryLevel.then((val) => data["data"]["battery"] = val).whenComplete((){ battery.batteryLevel.then((val) => data["data"]["battery"] = val).whenComplete((){
//print("[Background $backgroundTask] Getting device location..."); print("[Background $backgroundTask] Getting device location...");
geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high, locationPermissionLevel: GeolocationPermission.locationAlways).then((location) { geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high, locationPermissionLevel: GeolocationPermission.locationAlways).then((location) {
//print("[Background $backgroundTask] Got location: ${location.latitude} ${location.longitude}");
if (location != null) { if (location != null) {
print("[Background $backgroundTask] Got location: ${location.latitude} ${location.longitude}");
data["data"]["gps"] = [location.latitude, location.longitude]; data["data"]["gps"] = [location.latitude, location.longitude];
data["data"]["gps_accuracy"] = location.accuracy; data["data"]["gps_accuracy"] = location.accuracy;
//print("[Background $backgroundTask] Sending data home..."); print("[Background $backgroundTask] Sending data home.");
http.post( http.post(
url, url,
headers: headers, headers: headers,
body: json.encode(data) body: json.encode(data)
); );
} else {
print("[Background $backgroundTask] No location. Finishing.");
} }
}).catchError((e) { }).catchError((e) {
//print("[Background $backgroundTask] Error getting current location: ${e.toString()}. Trying last known..."); print("[Background $backgroundTask] Error getting current location: ${e.toString()}");
geolocator.getLastKnownPosition(desiredAccuracy: LocationAccuracy.medium).then((location){
//print("[Background $backgroundTask] Got last known location: ${location.latitude} ${location.longitude}");
if (location != null) {
data["data"]["gps"] = [location.latitude, location.longitude];
data["data"]["gps_accuracy"] = location.accuracy;
//print("[Background $backgroundTask] Sending data home...");
http.post(
url,
headers: headers,
body: json.encode(data)
);
}
});
}); });
}); });
} }

View File

@ -23,6 +23,10 @@ class Logger {
return inDebugMode; return inDebugMode;
} }
static void p(data) {
print(data);
}
static void e(String message) { static void e(String message) {
_writeToLog("Error", message); _writeToLog("Error", message);
} }

View File

@ -29,6 +29,7 @@ dependencies:
geolocator: ^5.1.5 geolocator: ^5.1.5
workmanager: ^0.1.3 workmanager: ^0.1.3
battery: ^0.3.1+1 battery: ^0.3.1+1
sentry: ^2.3.1
share: share:
git: git:
url: https://github.com/d-silveira/flutter-share.git url: https://github.com/d-silveira/flutter-share.git