proxibuy/lib/services/background_service.dart

128 lines
4.1 KiB
Dart

import 'dart:async';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:geolocator/geolocator.dart';
import 'package:proxibuy/services/mqtt_service.dart';
const notificationChannelId = 'proxibuy_foreground_service';
const notificationId = 888;
@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
DartPluginRegistrant.ensureInitialized();
final MqttService mqttService = MqttService();
const storage = FlutterSecureStorage();
if (service is AndroidServiceInstance) {
service.setForegroundNotificationInfo(
title: "ProxiBuy فعال است",
content: "در حال جستجو برای تخفیف های اطراف شما...",
);
service.on('stopService').listen((event) {
service.stopSelf();
});
}
Future<void> sendGpsData() async {
try {
// Check location service status
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
debugPrint("Background Service: Location service is disabled.");
return;
}
// Check location permission
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
debugPrint("Background Service: Location permission denied.");
return;
}
if (permission == LocationPermission.deniedForever) {
debugPrint("Background Service: Location permission denied forever.");
return;
}
final position = await Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
));
final token = await storage.read(key: 'accessToken');
final userID = await storage.read(key: 'userID');
if (token != null && userID != null) {
if (!mqttService.isConnected) {
await mqttService.connect(token);
final topic = 'user-proxybuy/$userID';
mqttService.subscribe(topic);
}
if (mqttService.isConnected) {
final payload = {
"userID": userID,
"lat": position.latitude,
"lng": position.longitude
};
mqttService.publish("proxybuy/sendGps", payload);
debugPrint("Background Service: GPS sent successfully.");
}
}
} catch (e) {
debugPrint("❌ Background Service Error: $e");
}
}
mqttService.messages.listen((data) {
service.invoke('update', {'offers': data});
});
service.on('force_refresh').listen((event) async {
debugPrint("✅ Background Service: Received force_refresh event.");
await sendGpsData();
});
Timer.periodic(const Duration(seconds: 30), (timer) async {
debugPrint("✅ Background Service: Sending location via periodic timer...");
await sendGpsData();
});
}
Future<void> initializeService() async {
final service = FlutterBackgroundService();
const AndroidNotificationChannel channel = AndroidNotificationChannel(
notificationChannelId,
'ProxiBuy Background Service',
description: 'This channel is used for location service notifications.',
importance: Importance.low,
);
final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await service.configure(
androidConfiguration: AndroidConfiguration(
onStart: onStart,
isForegroundMode: true,
autoStart: true,
notificationChannelId: notificationChannelId,
initialNotificationTitle: 'ProxiBuy فعال است',
initialNotificationContent: 'در حال جستجو برای تخفیف‌های اطراف شما...',
foregroundServiceNotificationId: notificationId,
),
iosConfiguration: IosConfiguration(
autoStart: true,
onForeground: onStart,
),
);
}