This commit is contained in:
Nedifinita
2025-09-27 00:50:12 +08:00
parent 9b0e9dcacf
commit 8d3366fbf9
7 changed files with 70 additions and 148 deletions

View File

@@ -712,9 +712,7 @@ class HistoryScreenState extends State<HistoryScreen> {
setState(() { setState(() {
_currentUserLocation = LatLng(position.latitude, position.longitude); _currentUserLocation = LatLng(position.latitude, position.longitude);
}); });
} catch (e) { } catch (e) {}
print('获取当前位置失败: $e');
}
} }
void _startLocationUpdates() { void _startLocationUpdates() {

View File

@@ -44,16 +44,12 @@ class _MapScreenState extends State<MapScreen> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
print('=== 地图页面初始化 ===');
_initializeMap(); _initializeMap();
_checkDatabaseSettings(); _checkDatabaseSettings();
//
_loadSettings().then((_) { _loadSettings().then((_) {
print('设置加载完成,开始加载列车记录');
_loadTrainRecords().then((_) { _loadTrainRecords().then((_) {
print('列车记录加载完成,开始位置更新');
_startLocationUpdates(); _startLocationUpdates();
}); });
}); });
@@ -61,40 +57,28 @@ class _MapScreenState extends State<MapScreen> {
Future<void> _checkDatabaseSettings() async { Future<void> _checkDatabaseSettings() async {
try { try {
print('=== 检查数据库设置 ===');
final dbInfo = await DatabaseService.instance.getDatabaseInfo(); final dbInfo = await DatabaseService.instance.getDatabaseInfo();
print('数据库信息: $dbInfo');
final settings = await DatabaseService.instance.getAllSettings(); final settings = await DatabaseService.instance.getAllSettings();
print('数据库设置详情: $settings');
if (settings != null) { if (settings != null) {
final lat = settings['mapCenterLat']; final lat = settings['mapCenterLat'];
final lon = settings['mapCenterLon']; final lon = settings['mapCenterLon'];
print('数据库中的位置坐标: lat=$lat, lon=$lon');
if (lat != null && lon != null) { if (lat != null && lon != null) {
if (lat == 39.9042 && lon == 116.4074) { if (lat == 39.9042 && lon == 116.4074) {
print('警告:数据库中保存的是北京默认坐标');
} else if (lat == 0.0 && lon == 0.0) { } else if (lat == 0.0 && lon == 0.0) {
print('警告:数据库中保存的是零坐标');
} else { } else {
print('数据库中保存的是有效坐标');
final beijingLat = 39.9042; final beijingLat = 39.9042;
final beijingLon = 116.4074; final beijingLon = 116.4074;
final distance = final distance =
_calculateDistance(lat, lon, beijingLat, beijingLon); _calculateDistance(lat, lon, beijingLat, beijingLon);
print('与北京市中心的距离: ${distance.toStringAsFixed(2)} 公里');
if (distance < 50) { if (distance < 50) {}
print('注意:保存的位置在北京附近(距离 < 50公里');
}
} }
} }
} }
} catch (e) { } catch (e) {}
print('检查数据库设置失败: $e');
}
} }
double _calculateDistance( double _calculateDistance(
@@ -154,25 +138,20 @@ class _MapScreenState extends State<MapScreen> {
Future<void> _getCurrentLocation() async { Future<void> _getCurrentLocation() async {
try { try {
print('=== 获取当前位置 ===');
Position position = await Geolocator.getCurrentPosition( Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high, desiredAccuracy: LocationAccuracy.high,
forceAndroidLocationManager: true, forceAndroidLocationManager: true,
); );
final newLocation = LatLng(position.latitude, position.longitude); final newLocation = LatLng(position.latitude, position.longitude);
print('获取到位置: $newLocation');
setState(() { setState(() {
_userLocation = newLocation; _userLocation = newLocation;
}); });
if (!_isMapInitialized) { if (!_isMapInitialized) {
print('获取位置后尝试初始化地图');
_initializeMapPosition(); _initializeMapPosition();
} }
} catch (e) { } catch (e) {}
print('获取位置失败: $e');
}
} }
void _startLocationUpdates() { void _startLocationUpdates() {
@@ -199,20 +178,13 @@ class _MapScreenState extends State<MapScreen> {
}); });
_mapController.move(newLocation, 15.0); _mapController.move(newLocation, 15.0);
} catch (e) { } catch (e) {}
print('强制更新位置失败: $e');
}
} }
Future<void> _loadSettings() async { Future<void> _loadSettings() async {
try { try {
print('=== 开始加载设置 ===');
final settings = await DatabaseService.instance.getAllSettings(); final settings = await DatabaseService.instance.getAllSettings();
print('设置数据: $settings');
if (settings != null) { if (settings != null) {
print(
'设置中的位置: lat=${settings['mapCenterLat']}, lon=${settings['mapCenterLon']}');
print('设置中的缩放: ${settings['mapZoomLevel']}');
setState(() { setState(() {
_railwayLayerVisible = _railwayLayerVisible =
(settings['mapRailwayLayerVisible'] as int?) == 1; (settings['mapRailwayLayerVisible'] as int?) == 1;
@@ -227,31 +199,17 @@ class _MapScreenState extends State<MapScreen> {
if (lat != null && lon != null && lat != 0.0 && lon != 0.0) { if (lat != null && lon != null && lat != 0.0 && lon != 0.0) {
_currentLocation = LatLng(lat, lon); _currentLocation = LatLng(lat, lon);
print('使用保存的位置: $_currentLocation');
} else {
print('保存的位置无效或为零,不使用');
} }
}); });
print('设置加载完成,当前位置: $_currentLocation');
if (!_isMapInitialized) { if (!_isMapInitialized) {
print('设置加载后尝试初始化地图');
_initializeMapPosition(); _initializeMapPosition();
} }
} else {
print('没有保存的设置数据');
} }
} catch (e) { } catch (e) {}
print('加载设置失败: $e');
}
} }
Future<void> _saveSettings() async { Future<void> _saveSettings() async {
try { try {
print('=== 保存设置到数据库 ===');
print('当前旋转角度: $_currentRotation');
print('当前缩放级别: $_currentZoom');
print('当前位置: $_currentLocation');
final center = _mapController.camera.center; final center = _mapController.camera.center;
final isDefaultLocation = final isDefaultLocation =
@@ -269,20 +227,14 @@ class _MapScreenState extends State<MapScreen> {
settings['mapCenterLon'] = center.longitude; settings['mapCenterLon'] = center.longitude;
} }
print('保存的设置数据: $settings');
await DatabaseService.instance.updateSettings(settings); await DatabaseService.instance.updateSettings(settings);
print('=== 设置保存成功 ==='); } catch (e) {}
} catch (e) {
print('保存设置失败: $e');
}
} }
Future<void> _loadTrainRecords() async { Future<void> _loadTrainRecords() async {
setState(() => _isLoading = true); setState(() => _isLoading = true);
try { try {
print('=== 开始加载列车记录 ===');
final records = await _getFilteredRecords(); final records = await _getFilteredRecords();
print('加载到 ${records.length} 条记录');
setState(() { setState(() {
_trainRecords.clear(); _trainRecords.clear();
_trainRecords.addAll(records); _trainRecords.addAll(records);
@@ -290,33 +242,22 @@ class _MapScreenState extends State<MapScreen> {
if (_trainRecords.isNotEmpty) { if (_trainRecords.isNotEmpty) {
final lastRecord = _trainRecords.first; final lastRecord = _trainRecords.first;
print(
'最新记录: ${lastRecord.fullTrainNumber}, 位置: ${lastRecord.position}');
final coords = lastRecord.getCoordinates(); final coords = lastRecord.getCoordinates();
final dmsCoords = _parseDmsCoordinate(lastRecord.positionInfo); final dmsCoords = _parseDmsCoordinate(lastRecord.positionInfo);
if (dmsCoords != null) { if (dmsCoords != null) {
_lastTrainLocation = dmsCoords; _lastTrainLocation = dmsCoords;
print('使用DMS坐标: $dmsCoords');
} else if (coords['lat'] != 0.0 && coords['lng'] != 0.0) { } else if (coords['lat'] != 0.0 && coords['lng'] != 0.0) {
_lastTrainLocation = LatLng(coords['lat']!, coords['lng']!); _lastTrainLocation = LatLng(coords['lat']!, coords['lng']!);
print('使用解析坐标: $_lastTrainLocation');
} else {
print('记录中没有有效坐标');
} }
} else {
print('没有列车记录');
} }
print('列车位置: $_lastTrainLocation');
if (!_isMapInitialized) { if (!_isMapInitialized) {
print('列车记录加载后尝试初始化地图');
_initializeMapPosition(); _initializeMapPosition();
} }
}); });
} catch (e) { } catch (e) {
setState(() => _isLoading = false); setState(() => _isLoading = false);
print('加载列车记录失败: $e');
} }
} }
@@ -338,31 +279,18 @@ class _MapScreenState extends State<MapScreen> {
LatLng? targetLocation; LatLng? targetLocation;
print('=== 初始化地图位置 ===');
print('当前位置: $_currentLocation');
print('列车位置: $_lastTrainLocation');
print('用户位置: $_userLocation');
print('地图已初始化: $_isMapInitialized');
if (_currentLocation != null) { if (_currentLocation != null) {
targetLocation = _currentLocation; targetLocation = _currentLocation;
print('使用保存的坐标: $targetLocation');
} else if (_lastTrainLocation != null) { } else if (_lastTrainLocation != null) {
targetLocation = _lastTrainLocation; targetLocation = _lastTrainLocation;
print('使用列车位置: $targetLocation');
} else if (_userLocation != null) { } else if (_userLocation != null) {
targetLocation = _userLocation; targetLocation = _userLocation;
print('使用用户位置: $targetLocation');
} else { } else {
targetLocation = const LatLng(39.9042, 116.4074); targetLocation = const LatLng(39.9042, 116.4074);
print('没有可用位置,使用北京默认位置: $targetLocation');
} }
print('最终选择位置: $targetLocation');
print('当前旋转角度: $_currentRotation');
_centerMap(targetLocation!, zoom: _currentZoom, rotation: _currentRotation); _centerMap(targetLocation!, zoom: _currentZoom, rotation: _currentRotation);
_isMapInitialized = true; _isMapInitialized = true;
print('地图初始化完成,旋转角度: $_currentRotation');
} }
void _centerMap(LatLng location, {double? zoom, double? rotation}) { void _centerMap(LatLng location, {double? zoom, double? rotation}) {
@@ -392,9 +320,7 @@ class _MapScreenState extends State<MapScreen> {
return LatLng(lat, lng); return LatLng(lat, lng);
} }
} }
} catch (e) { } catch (e) {}
print('解析DMS坐标失败: $e');
}
return null; return null;
} }

View File

@@ -20,9 +20,9 @@ class BackgroundService {
if (_isInitialized) return; if (_isInitialized) return;
final service = FlutterBackgroundService(); final service = FlutterBackgroundService();
final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
if (Platform.isAndroid) { if (Platform.isAndroid) {
const AndroidNotificationChannel channel = AndroidNotificationChannel( const AndroidNotificationChannel channel = AndroidNotificationChannel(
_notificationChannelId, _notificationChannelId,
@@ -34,10 +34,12 @@ class BackgroundService {
playSound: false, playSound: false,
); );
await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation< await flutterLocalNotificationsPlugin
AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(channel); .resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
} }
await service.configure( await service.configure(
androidConfiguration: AndroidConfiguration( androidConfiguration: AndroidConfiguration(
onStart: _onStart, onStart: _onStart,
@@ -81,8 +83,9 @@ class BackgroundService {
if (service is AndroidServiceInstance) { if (service is AndroidServiceInstance) {
await Future.delayed(const Duration(seconds: 1)); await Future.delayed(const Duration(seconds: 1));
if (await service.isForegroundService()) { if (await service.isForegroundService()) {
final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); final flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
try { try {
const AndroidNotificationChannel channel = AndroidNotificationChannel( const AndroidNotificationChannel channel = AndroidNotificationChannel(
_notificationChannelId, _notificationChannelId,
@@ -94,8 +97,10 @@ class BackgroundService {
playSound: false, playSound: false,
); );
await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation< await flutterLocalNotificationsPlugin
AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(channel); .resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await flutterLocalNotificationsPlugin.show( await flutterLocalNotificationsPlugin.show(
_notificationId, _notificationId,
@@ -122,10 +127,7 @@ class BackgroundService {
), ),
), ),
); );
print('前台服务通知显示成功'); } catch (e) {}
} catch (e) {
print('前台服务通知显示失败: $e');
}
} }
} }
@@ -136,8 +138,9 @@ class BackgroundService {
final bleService = BLEService(); final bleService = BLEService();
final isConnected = bleService.isConnected; final isConnected = bleService.isConnected;
final deviceStatus = bleService.deviceStatus; final deviceStatus = bleService.deviceStatus;
final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); final flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin.show( await flutterLocalNotificationsPlugin.show(
_notificationId, _notificationId,
'LBJ Console', 'LBJ Console',
@@ -163,9 +166,7 @@ class BackgroundService {
), ),
), ),
); );
} catch (e) { } catch (e) {}
print('前台服务通知更新失败: $e');
}
} }
} }
}); });
@@ -179,7 +180,7 @@ class BackgroundService {
static Future<void> startService() async { static Future<void> startService() async {
await initialize(); await initialize();
final service = FlutterBackgroundService(); final service = FlutterBackgroundService();
if (Platform.isAndroid) { if (Platform.isAndroid) {
final isRunning = await service.isRunning(); final isRunning = await service.isRunning();
if (!isRunning) { if (!isRunning) {
@@ -208,4 +209,4 @@ class BackgroundService {
service.invoke('setAsBackground'); service.invoke('setAsBackground');
} }
} }
} }

View File

@@ -330,9 +330,7 @@ class BLEService {
_dataController.add(trainRecord); _dataController.add(trainRecord);
DatabaseService.instance.insertRecord(trainRecord); DatabaseService.instance.insertRecord(trainRecord);
} }
} catch (e) { } catch (e) {}
print("$TAG: JSON Decode Error: $e, Data: $jsonData");
}
} }
void _updateConnectionState(bool connected, String status) { void _updateConnectionState(bool connected, String status) {

View File

@@ -12,7 +12,8 @@ class LocationService {
LatLng? _currentLocation; LatLng? _currentLocation;
Timer? _locationTimer; Timer? _locationTimer;
bool _isLocationPermissionGranted = false; bool _isLocationPermissionGranted = false;
final StreamController<LatLng?> _locationStreamController = StreamController<LatLng?>.broadcast(); final StreamController<LatLng?> _locationStreamController =
StreamController<LatLng?>.broadcast();
Stream<LatLng?> get locationStream => _locationStreamController.stream; Stream<LatLng?> get locationStream => _locationStreamController.stream;
LatLng? get currentLocation => _currentLocation; LatLng? get currentLocation => _currentLocation;
@@ -30,7 +31,6 @@ class LocationService {
try { try {
bool serviceEnabled = await Geolocator.isLocationServiceEnabled(); bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) { if (!serviceEnabled) {
print('定位服务未开启');
return; return;
} }
@@ -40,14 +40,11 @@ class LocationService {
} }
if (permission == LocationPermission.deniedForever) { if (permission == LocationPermission.deniedForever) {
print('定位权限被拒绝,请在设置中开启');
return; return;
} }
_isLocationPermissionGranted = true; _isLocationPermissionGranted = true;
} catch (e) { } catch (e) {}
print('请求定位权限失败: $e');
}
} }
Future<void> _getCurrentLocation() async { Future<void> _getCurrentLocation() async {
@@ -56,14 +53,12 @@ class LocationService {
try { try {
Position position = await Geolocator.getCurrentPosition( Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high, desiredAccuracy: LocationAccuracy.high,
forceAndroidLocationManager: true, // 强制使用Android LocationManager forceAndroidLocationManager: true,
); );
_currentLocation = LatLng(position.latitude, position.longitude); _currentLocation = LatLng(position.latitude, position.longitude);
_locationStreamController.add(_currentLocation); _locationStreamController.add(_currentLocation);
} catch (e) { } catch (e) {}
print('获取当前位置失败: $e');
}
} }
void _startLocationUpdates() { void _startLocationUpdates() {
@@ -86,4 +81,4 @@ class LocationService {
_locationTimer?.cancel(); _locationTimer?.cancel();
_locationStreamController.close(); _locationStreamController.close();
} }
} }

View File

@@ -9,7 +9,7 @@ class MapStateService {
MapStateService._internal(); MapStateService._internal();
static const String _tableName = 'record_map_states'; static const String _tableName = 'record_map_states';
final Map<String, MapState> _memoryCache = {}; final Map<String, MapState> _memoryCache = {};
Future<void> _ensureTableExists() async { Future<void> _ensureTableExists() async {
@@ -34,10 +34,10 @@ class MapStateService {
Future<void> saveMapState(String key, MapState state) async { Future<void> saveMapState(String key, MapState state) async {
try { try {
_memoryCache[key] = state; _memoryCache[key] = state;
final db = await DatabaseService.instance.database; final db = await DatabaseService.instance.database;
await _ensureTableExists(); await _ensureTableExists();
await db.insert( await db.insert(
_tableName, _tableName,
{ {
@@ -47,9 +47,7 @@ class MapStateService {
}, },
conflictAlgorithm: ConflictAlgorithm.replace, conflictAlgorithm: ConflictAlgorithm.replace,
); );
} catch (e) { } catch (e) {}
print('保存地图状态失败: $e');
}
} }
Future<MapState?> getMapState(String key) async { Future<MapState?> getMapState(String key) async {
@@ -60,7 +58,7 @@ class MapStateService {
try { try {
final db = await DatabaseService.instance.database; final db = await DatabaseService.instance.database;
await _ensureTableExists(); await _ensureTableExists();
final result = await db.query( final result = await db.query(
_tableName, _tableName,
where: 'key = ?', where: 'key = ?',
@@ -74,16 +72,14 @@ class MapStateService {
_memoryCache[key] = state; _memoryCache[key] = state;
return state; return state;
} }
} catch (e) { } catch (e) {}
print('读取地图状态失败: $e');
}
return null; return null;
} }
Future<void> deleteMapState(String key) async { Future<void> deleteMapState(String key) async {
_memoryCache.remove(key); _memoryCache.remove(key);
try { try {
final db = await DatabaseService.instance.database; final db = await DatabaseService.instance.database;
await db.delete( await db.delete(
@@ -91,23 +87,19 @@ class MapStateService {
where: 'key = ?', where: 'key = ?',
whereArgs: [key], whereArgs: [key],
); );
} catch (e) { } catch (e) {}
print('删除地图状态失败: $e');
}
} }
Future<void> clearAllMapStates() async { Future<void> clearAllMapStates() async {
_memoryCache.clear(); _memoryCache.clear();
try { try {
final db = await DatabaseService.instance.database; final db = await DatabaseService.instance.database;
await db.delete(_tableName); await db.delete(_tableName);
} catch (e) { } catch (e) {}
print('清空地图状态失败: $e');
}
} }
void clearMemoryCache() { void clearMemoryCache() {
_memoryCache.clear(); _memoryCache.clear();
} }
} }

View File

@@ -90,20 +90,32 @@ class NotificationService {
String _buildNotificationContent(TrainRecord record) { String _buildNotificationContent(TrainRecord record) {
final buffer = StringBuffer(); final buffer = StringBuffer();
buffer.writeln('车次: ${record.fullTrainNumber}'); buffer.write(record.fullTrainNumber);
buffer.writeln('线路: ${record.route}'); if (_isValidValue(record.route)) {
buffer.writeln('方向: ${record.directionText}'); buffer.write(' ${record.route}');
}
if (_isValidValue(record.directionText)) {
buffer.write(' ${record.directionText}');
}
if (_isValidValue(record.positionInfo)) {
buffer.write(' ${record.positionInfo}');
}
buffer.writeln();
if (_isValidValue(record.locoType) && _isValidValue(record.loco)) {
final shortLoco = record.loco.length > 5
? record.loco.substring(record.loco.length - 5)
: record.loco;
buffer.write('${record.locoType}-$shortLoco');
} else if (_isValidValue(record.locoType)) {
buffer.write(record.locoType);
} else if (_isValidValue(record.loco)) {
buffer.write(record.loco);
}
if (_isValidValue(record.speed)) { if (_isValidValue(record.speed)) {
buffer.writeln('速度: ${record.speed} km/h'); buffer.write(' ${record.speed}km/h');
} }
if (_isValidValue(record.positionInfo)) {
buffer.writeln('位置: ${record.positionInfo}');
}
buffer.writeln('时间: ${record.formattedTime}');
return buffer.toString().trim(); return buffer.toString().trim();
} }