import 'dart:async'; import 'dart:ui'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:flutter_background_service_android/flutter_background_service_android.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_overlay_window/flutter_overlay_window.dart'; import 'package:socket_io_client/socket_io_client.dart' as IO; import 'package:flutter_overlay_window/flutter_overlay_window.dart' as Overlay; import 'package:get_storage/get_storage.dart'; import '../../constant/box_name.dart'; const String notificationChannelId = 'driver_service_channel'; const int notificationId = 888; const String notificationIcon = '@mipmap/launcher_icon'; @pragma('vm:entry-point') Future onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); await GetStorage.init(); final box = GetStorage(); IO.Socket? socket; String driverId = box.read(BoxName.driverID) ?? ''; String token = box.read(BoxName.tokenDriver) ?? ''; if (driverId.isNotEmpty) { socket = IO.io( 'https://location.intaleq.xyz', IO.OptionBuilder() .setTransports(['websocket']) .disableAutoConnect() .setQuery({'driver_id': driverId, 'token': token}) .setReconnectionAttempts(double.infinity) .build()); socket.connect(); socket.onConnect((_) { print("✅ Background Service: Socket Connected!"); if (service is AndroidServiceInstance) { flutterLocalNotificationsPlugin.show( notificationId, 'أنت متصل الآن', 'بانتظار الطلبات...', const NotificationDetails( android: AndroidNotificationDetails( notificationChannelId, 'خدمة السائق', icon: notificationIcon, ongoing: true, importance: Importance.low, priority: Priority.low, ), ), ); } }); socket.on('new_ride_request', (data) async { print("🔔 Background Service: Received new_ride_request"); // 🔥 قراءة حالة التطبيق مباشرة قبل العرض await GetStorage.init(); // تأكد من تحديث البيانات final box = GetStorage(); bool isAppInForeground = box.read(BoxName.isAppInForeground) ?? false; // 🔥 Check إضافي: هل الـ Overlay مفتوح بالفعل؟ bool overlayActive = await Overlay.FlutterOverlayWindow.isActive(); if (isAppInForeground || overlayActive) { print("🛑 App is FOREGROUND or Overlay already shown. Skipping."); return; } // عرض الـ Overlay print("🚀 App is BACKGROUND. Showing Overlay..."); try { await Overlay.FlutterOverlayWindow.showOverlay( enableDrag: true, overlayTitle: "طلب جديد", overlayContent: "لديك طلب جديد وصل للتو!", flag: OverlayFlag.focusPointer, positionGravity: PositionGravity.auto, height: WindowSize.matchParent, width: WindowSize.matchParent, startPosition: const OverlayPosition(0, -30), ); await Overlay.FlutterOverlayWindow.shareData(data); } catch (e) { print("Overlay Error: $e"); } }); } service.on('stopService').listen((event) { socket?.disconnect(); service.stopSelf(); }); Timer.periodic(const Duration(seconds: 30), (timer) async { if (service is AndroidServiceInstance) { if (await service.isForegroundService()) { flutterLocalNotificationsPlugin.show( notificationId, 'خدمة السائق نشطة', 'بانتظار الطلبات...', const NotificationDetails( android: AndroidNotificationDetails( notificationChannelId, 'خدمة السائق', icon: notificationIcon, ongoing: true, importance: Importance.low, priority: Priority.low, ), ), ); } } }); return true; } class BackgroundServiceHelper { static Future initialize() async { final service = FlutterBackgroundService(); await service.configure( androidConfiguration: AndroidConfiguration( onStart: onStart, autoStart: false, isForegroundMode: true, notificationChannelId: notificationChannelId, initialNotificationTitle: 'تطبيق السائق', initialNotificationContent: 'تجهيز الخدمة...', foregroundServiceNotificationId: notificationId, ), iosConfiguration: IosConfiguration( autoStart: false, onForeground: onStart, onBackground: onStart, ), ); } static Future startService() async { final service = FlutterBackgroundService(); if (!await service.isRunning()) { await service.startService(); } } static Future stopService() async { final service = FlutterBackgroundService(); service.invoke("stopService"); } }