ekasetiawans / flutter_background_service

269 stars 192 forks source link

Foreground service started from background can not have location/camera/microphone access #279

Open Parvez6084 opened 1 year ago

Parvez6084 commented 1 year ago

I used GeoLocator, When I minimize my application then it works perfectly. I get location data every 200 meters and send it server. bt Problem was when I closed my app than foreground service started but the location data did not get and was not sent server
"Foreground service started from the background can not have location/camera/microphone access"

aditional The other problem is the app opens first-time foreground service does not start. but when I closed it and again open it start.


Future<void> backgroundServiceRegister() async {

  final service = FlutterBackgroundService();
  var localNotifications = FlutterLocalNotificationsPlugin();
  var channel = const AndroidNotificationChannel(
      fgNotificationChannelId,
      'FOREGROUND SERVICE',//title
      importance: Importance.high);

  if (Platform.isIOS) {
    await localNotifications.initialize(
      const InitializationSettings(
        iOS: DarwinInitializationSettings(),
      ),
    );
  }

  await localNotifications
      .resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

  await service.configure(
    androidConfiguration: AndroidConfiguration(
      onStart: onStart,
      autoStart: true,
      isForegroundMode: true,
      notificationChannelId: fgNotificationChannelId,
      initialNotificationTitle: AppString.trackingFG,
      initialNotificationContent: AppString.trackingMotoFG,
      foregroundServiceNotificationId: fgNotificationId,
    ),
    iosConfiguration: IosConfiguration(
      autoStart: true,
      onForeground: onStart,
      onBackground: onIosBackground,
    ),
  );

  service.startService();
}
@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
  WidgetsFlutterBinding.ensureInitialized();
  DartPluginRegistrant.ensureInitialized();
  callbackDispatcher();

  return true;
}
@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
  DartPluginRegistrant.ensureInitialized();

  if (service is AndroidServiceInstance) {
    service.on('setAsForeground').listen((event) async {
      await service.setAsForegroundService();
    });
    service.on('setAsBackground').listen((event) async {
      await service.setAsBackgroundService();
    });
  }
  service.on('stopService').listen((event) async {
    await service.stopSelf();
  });

  if (service is AndroidServiceInstance) {
    if (await service.isForegroundService()) {
      callbackDispatcher();
    }
  }

}
void callbackDispatcher() async {
  late LocationSettings locationSettings;
  String? device = 'notIdentifier';
  var endpoint = "${BASE_URL}Rest/AddCoordinates";
  final prefs = await SharedPreferences.getInstance();
  final String? userId = prefs.getString(PreferenceManager.keyUser);

  Helper.deviceInfo().then((value) => device = value);

  if (defaultTargetPlatform == TargetPlatform.android) {
    locationSettings = AndroidSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: locationDistance,  // locationDistance =200
        forceLocationManager: true,
        intervalDuration: const Duration(minutes: 1),
        foregroundNotificationConfig: const ForegroundNotificationConfig(
          notificationText: AppString.locationTrackingMoto,
          notificationTitle: AppString.locationTracking,
          enableWakeLock: true,
        ));
  }
  else if (defaultTargetPlatform == TargetPlatform.iOS) {
    locationSettings = AppleSettings(
      accuracy: LocationAccuracy.high,
      activityType: ActivityType.fitness,
      distanceFilter: locationDistance,   // locationDistance =200
      pauseLocationUpdatesAutomatically: true,
      showBackgroundLocationIndicator: true,
    );
  }

  if(userId != null && userId != ''){
    Geolocator.getPositionStream(locationSettings: locationSettings).listen((Position? position) async {
      var payload = LocationModel(
          latitude: position?.latitude ?? 0.0,
          longitude: position?.longitude ?? 0.0,
          deviceId: device, uId: userId).toJson();
      await Dio().get(endpoint, queryParameters: payload);
    });
  }
}
Parvez6084 commented 1 year ago

I think this is the solution!! I add this line AndroidManifest.xml Folder

<application
...
          <service 
            android:enabled="true"
            android:exported="true"
            android:name="id.flutter.flutter_background_service.BackgroundService"
            android:foregroundServiceType="location"
            />
</application> 
Parvez6084 commented 1 year ago

additional The other problem is the app opens first-time foreground service does not start. but when I closed it and again open it start. ??

Parvez6084 commented 1 year ago

Log

  V  Service already running, using existing service
2023-02-05 14:09:54.794  9488-9488  AndroidRuntime          com.xxx.xxxxxxxx                 D  Shutting down VM
2023-02-05 14:09:54.798  9488-9488  AndroidRuntime          com.xxx.xxxxxxxx                 E  FATAL EXCEPTION: main
                                                                                                    Process: com.xxx.xxxxxxxx, PID: 9488
                                                                                                    java.lang.IncompatibleClassChangeError: Found interface com.google.android.gms.location.FusedLocationProviderClient, but class was expected (declaration of 'com.google.android.gms.location.FusedLocationProviderClient' appears in /data/app/~~9Be8qOt94tOS6oqGkqm9Hw==/com.xxx.xxxxxxxx-ts7AZp4ug0qU5nYNJmuq0g==/base.apk)
                                                                                                        at com.lyokone.location.FlutterLocation.setActivity(FlutterLocation.java:109)
                                                                                                        at com.lyokone.location.FlutterLocationService.setActivity(FlutterLocationService.kt:255)
                                                                                                        at com.lyokone.location.LocationPlugin.dispose(LocationPlugin.java:121)
                                                                                                        at com.lyokone.location.LocationPlugin.detachActivity(LocationPlugin.java:56)
                                                                                                        at com.lyokone.location.LocationPlugin.onDetachedFromActivity(LocationPlugin.java:69)
                                                                                                        at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.detachFromActivity(FlutterEngineConnectionRegistry.java:387)
                                                                                                        at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onDetach(FlutterActivityAndFragmentDelegate.java:742)
                                                                                                        at io.flutter.embedding.android.FlutterActivity.onDestroy(FlutterActivity.java:908)
                                                                                                        at android.app.Activity.performDestroy(Activity.java:8315)
                                                                                                        at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1364)
                                                                                                        at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:5413)
                                                                                                        at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:5459)
                                                                                                        at android.app.servertransaction.DestroyActivityItem.execute(DestroyActivityItem.java:47)
                                                                                                        at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
                                                                                                        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
                                                                                                        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2247)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                                        at android.os.Looper.loopOnce(Looper.java:201)
                                                                                                        at android.os.Looper.loop(Looper.java:288)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7880)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:568)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1045)
2023-02-05 14:09:54.805   814-948   libPowerHal             pid-814                              I  [perfNotifyAppState] pack:com.xxx.xxxxxxxx, act:com.xxx.xxxxxxxx, state:3, pid:9488, uid:10218, fps:60
2023-02-05 14:09:54.806   814-948   libPowerHal             pid-814                              I  [perfNotifyAppState] pack:com.xxx.xxxxxxxx, pid:9488, STATE_DEAD
2023-02-05 14:09:54.813  9488-9488  Process                 com.xxx.xxxxxxxx                 I  Sending signal. PID: 9488 SIG: 9
2023-02-05 14:09:55.043  1461-5015  LocationManagerService  pid-1461                             D  registration onInactive from uid: 10218 package: com.xxx.xxxxxxxx
2023-02-05 14:09:55.043  1461-5015  LocationManagerService  pid-1461                             D  fused provider removed registration from 10218/com.xxx.xxxxxxxx/074B3F6A
2023-02-05 14:09:55.046  1461-1527  ActivityManager         pid-1461                             I  Process com.xxx.xxxxxxxx (pid 9488) has died: fg +50 FGS 
2023-02-05 14:09:55.048  1461-5043  WindowManager           pid-1461                             I  WIN DEATH: Window{1b9f078 u0 com.xxx.xxxxxxxx/com.xxx.xxxxxxxx.MainActivity}
2023-02-05 14:09:55.048  1461-5043  InputManager-JNI        pid-1461                             W  Input channel object '1b9f078 com.xxx.xxxxxxxx/com.xxx.xxxxxxxx.MainActivity (client)' was disposed without first being removed with the input manager!
2023-02-05 14:09:55.049  1461-5043  WindowManager           pid-1461                             D  setParent old=ActivityRecord{763d5c8 u0 com.xxx.xxxxxxxx/.MainActivity t1699 f}},new=null,this window=Window{1b9f078 u0 com.xxx.xxxxxxxx/com.xxx.xxxxxxxx.MainActivity},callers=com.android.server.wm.WindowContainer.removeChild:594 com.android.server.wm.ActivityRecord.removeChild:3769 com.android.server.wm.ActivityRecord.removeChild:365 com.android.server.wm.WindowContainer.removeImmediately:646 com.android.server.wm.WindowState.removeImmediately:2380 com.android.server.wm.WindowState.removeIfPossible:2567 
2023-02-05 14:09:55.061   827-827   BufferQueueDebug        pid-827                              I  [SurfaceView[com.xxx.xxxxxxxx/com.xxx.xxxxxxxx.MainActivity](BLAST)#0](this:0xb400007eb37ad218,id:-1,api:0,p:-1,c:827) onDestructor()
2023-02-05 14:09:55.061  1461-1527  ActivityManager         pid-1461                             W  Scheduling restart of crashed service com.xxx.xxxxxxxx/id.flutter.flutter_background_service.BackgroundService in 1000ms for start-requested
2023-02-05 14:09:55.081   814-948   libPowerHal             pid-814                              I  [perfNotifyAppState] pack:com.xxx.xxxxxxxx, act:com.xxx.xxxxxxxx, state:3, pid:9488, uid:10218, fps:60
2023-02-05 14:09:55.081   814-948   libPowerHal             pid-814                              I  [perfNotifyAppState] pack:com.xxx.xxxxxxxx, pid:9488, STATE_DEAD
2023-02-05 14:09:55.082  1461-1527  WindowManager           pid-1461                             D  setParent old=Task{32bb43c #1699 type=standard A=10218:com.xxx.xxxxxxxx U=0 visible=false mode=fullscreen translucent=true sz=0},new=null,this window=ActivityRecord{763d5c8 u0 com.xxx.xxxxxxxx/.MainActivity t1699 f}},callers=com.android.server.wm.WindowContainer.removeChild:594 com.android.server.wm.Task.removeChild:1813 com.android.server.wm.Task.removeChild:1796 com.android.server.wm.WindowContainer.removeImmediately:646 com.android.server.wm.WindowToken.removeImmediately:360 com.android.server.wm.ActivityRecord.removeImmediately:3586 
2023-02-05 14:09:55.085  1461-1527  WindowManager           pid-1461                             D  setParent old=DefaultTaskDisplayArea@175208919,new=null,this window=Task{32bb43c #1699 type=standard A=10218:com.xxx.xxxxxxxx U=0 visible=false mode=fullscreen translucent=true sz=0},callers=com.android.server.wm.WindowContainer.removeChild:594 com.android.server.wm.TaskDisplayArea.removeChildTask:397 com.android.server.wm.TaskDisplayArea.removeChild:388 com.android.server.wm.WindowContainer.removeImmediately:646 com.android.server.wm.Task.removeImmediately:3278 com.android.server.wm.Task.removeIfPossible:1026 
2023-02-05 14:09:55.090  1710-1833  PeopleSpaceWidgetMgr    pid-1710                             D  Sbn doesn't contain valid PeopleTileKey: null/0/com.xxx.xxxxxxxx
2023-02-05 14:09:55.096  1461-1487  UsageStatsService       pid-1461                             W  Unexpected activity event reported! (com.xxx.xxxxxxxx/com.xxx.xxxxxxxx.MainActivity event : 23 instanceId : 173689558)
2023-02-05 14:09:55.122  1710-1833  PeopleSpaceWidgetMgr    pid-1710                             D  Sbn doesn't contain valid PeopleTileKey: null/0/com.xxx.xxxxxxxx
2023-02-05 14:09:55.217  1461-4755  ActivityManager         pid-1461                             I  Force stopping com.xxx.xxxxxxxx appid=10218 user=0: from pid 9700
2023-02-05 14:09:55.220  1461-4755  ActivityManager         pid-1461                             I    Force stopping service ServiceRecord{8c7714 u0 com.xxx.xxxxxxxx/id.flutter.flutter_background_service.BackgroundService}
2023-02-05 14:09:55.226  1461-4755  haohaov                 pid-1461                             I  [HMDenterprise broadcastIntentLocked] intent=Intent { act=android.intent.action.PACKAGE_RESTARTED dat=package:com.xxx.xxxxxxxx (has extras) }