Search code examples
androidflutterlocation

flutter location , Unhandled Exception: PlatformException(PERMISSION_DENIED_NEVER_ASK, Background location permission denied forever


I'm using Location flutter package to access the user's background location, first time any user opens the app it asks for permission, and when the user accepts it brings back this error in the console

Unhandled Exception: PlatformException(PERMISSION_DENIED_NEVER_ASK, Background location permission denied forever - please open app settings, null, null)

if the user closed the app and reopened it .. it works perfectly fine ( fetches location in both foreground and background) without even asking again for location permission.

Following the getting started guide in the package itself, here is how I added permission to my AndroidManifest.xml file :

  <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
  <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

Solution

  • I've been working on this issue and I discovered that the problem is when you use location.enableBackgroundMode() then choose always when you hit back first time it throws an exception and isBackgroundModeEnabled will be false too "despite the backgroundmode is enabled in system" and you have to restart the app to check if background mode is enabled correctly.

    but, I've found that calling location.enableBackgroundMode() again is solving the issue too and it really doesn't ask for enabling background again but it somehow make isBackgroundModeEnabled return true value. Here's my fix code:

    Future<bool> enableBackgroundMode() async {
    bool _bgModeEnabled = await location.isBackgroundModeEnabled();
    if (_bgModeEnabled) {
      return true;
    } else {
      try {
        await location.enableBackgroundMode();
      } catch (e) {
        debugPrint(e.toString());
      }
      try {
        _bgModeEnabled = await location.enableBackgroundMode();
      } catch (e) {
        debugPrint(e.toString());
      }
      print(_bgModeEnabled); //True!
      return _bgModeEnabled;
     }
    }