HaylLtd / cordova-background-geolocation-plugin

Background and foreground geolocation plugin for Cordova.
Apache License 2.0
57 stars 66 forks source link

App Crashes immediately when the 'Access to Device's location' dialog pops up and is allowed #122

Closed phiasco12 closed 1 year ago

phiasco12 commented 2 years ago

Describe the bug I've been having issues with this plugin recently on Android devices running Android 12.

The 'Access to Device's location' dialog pops up and when I press allow "while using the app: button, the app crashes and it seems like the whole background GPS fails to run even I close and reopen the app again!

I've tried using the variations of settings and haven't been able to eradicate this issue!

Some settings:

SDK 31 SDK 32

This plugin versions 2.0.7, 2.0.6, 2.0.5,

Cordova Android 10.1.2

I don't have any other plugins in my project so there's nothing that might conflict with this plugin!!

I've tried this in both Android studio simulator and a real device.

To Reproduce Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior N/A

Screenshots N/A

Desktop (please complete the following information):

Smartphone (please complete the following information):

Additional context This is my code:

      BackgroundGeolocation.configure({

    locationProvider: BackgroundGeolocation.ACTIVITY_PROVIDER,
    desiredAccuracy: BackgroundGeolocation.HIGH_ACCURACY,
    stationaryRadius: 50,
    distanceFilter: 50,
    startForeground: true,
    notificationIconColor: '#2A7682',
    notificationTitle: 'Background tracking',
    notificationText: 'enabled',
    debug: true,
    interval: 10000,
    fastestInterval: 5000,
    activitiesInterval: 10000,
    url: 'https://xxxxx.page.php',
    httpHeaders: {
      "Authorization": "Bearer gdfgdf"
    },

    // customize post properties
    postTemplate: {
      lat: '@latitude',
      lon: '@longitude',
      user: 'dingdong',
      token: 'fgjghjghjghjghjghjghjghj',
    }
  });

  BackgroundGeolocation.on('location', function(location) {

    //alert(JSON.stringify(location));
    // handle your locations here
    // to perform long running operation on iOS
    // you need to create background task
    BackgroundGeolocation.startTask(function(taskKey) {

alert(JSON.stringify(location));

      // execute long running task
      // eg. ajax post location
      // IMPORTANT: task has to be ended by endTask
      BackgroundGeolocation.endTask(taskKey);
    });
  });

  BackgroundGeolocation.on('stationary', function(stationaryLocation) {
    // handle stationary locations here

    alert('st');
  });

  BackgroundGeolocation.on('error', function(error) {
   alert('[ERROR] BackgroundGeolocation error:', error.code, error.message);
  });

  BackgroundGeolocation.on('start', function() {
    alert('[INFO] BackgroundGeolocation service has been started');
  });

  BackgroundGeolocation.on('stop', function() {
    alert('[INFO] BackgroundGeolocation service has been stopped');
  });

  BackgroundGeolocation.on('authorization', function(status) {
    alert('[INFO] BackgroundGeolocation authorization status: ' + status);
    if (status !== BackgroundGeolocation.AUTHORIZED) {
      // we need to set delay or otherwise alert may not be shown
      setTimeout(function() {
        var showSettings = confirm('App requires location tracking permission. Would you like to open app settings?');
        if (showSettings) {
          return BackgroundGeolocation.showAppSettings();
        }
      }, 1000);
    }
  });

  BackgroundGeolocation.on('background', function() {
   alert('[INFO] App is in background');
    // you can also reconfigure service (changes will be applied immediately)
    BackgroundGeolocation.configure({ debug: true });
  });

  BackgroundGeolocation.on('foreground', function() {
   alert('[INFO] App is in foreground');
    BackgroundGeolocation.configure({ debug: true });
  });

  BackgroundGeolocation.on('abort_requested', function() {
   alert('[INFO] Server responded with 285 Updates Not Required');

    // Here we can decide whether we want stop the updates or not.
    // If you've configured the server to return 285, then it means the server does not require further update.
    // So the normal thing to do here would be to `BackgroundGeolocation.stop()`.
    // But you might be counting on it to receive location updates in the UI, so you could just reconfigure and set `url` to null.
  });

  BackgroundGeolocation.on('http_authorization', () => {
    //alert('[INFO] App needs to authorize the http requests');
  });

  BackgroundGeolocation.checkStatus(function(status) {
  alert('[INFO] BackgroundGeolocation service is running', status.isRunning);
   alert('[INFO] BackgroundGeolocation services enabled', status.locationServicesEnabled);
    alert('[INFO] BackgroundGeolocation auth status: ' + status.authorization);

    // you don't need to check status before start (this is just the example)
    if (!status.isRunning) {
      BackgroundGeolocation.start(); //triggers start on start event
    }
  }); 
cbpolleydiscovr commented 2 years ago

I've recently migrated from the previous iterations of this plugin on Ionic / Capacitor and I feel your pain. It's likely something to do with how you've configured the plugin, it doesn't necessarily do it automatically for you. The Mauron 85 version seemed to have a few setup issues which may or may not have been ironed out in this version. I've got it up and running now though, so with any luck here' some things that might help you:

in android/app/src/main/res/values/strings.xml, add the following:

<string name="plugin_bgloc_account_name">@string/app_name</string> <string name="plugin_bgloc_content_authority">$PACKAGE_NAME</string> <string name="plugin_bgloc_account_type">$PACKAGE_NAME.account</string>

For the previous version we had to use the following which I guess has now been replaced.

<string name="mauron85_bgloc_account_name">@string/app_name</string> <string name="mauron85_bgloc_content_authority">$PACKAGE_NAME</string> <string name="mauron85_bgloc_account_type">$PACKAGE_NAME.account</string>

Depending on the nature of your error, you might want to put the following in your app level build.gradle dependencies, all of these may not be necessary but worth a try (android/app/build.gradle):

    implementation "androidx.annotation:annotation:1.1.0"
    implementation 'androidx.work:work-runtime:2.7.1'
    implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'

Make sure you have the correct permissions in the android manifest (android/app/src/main/AndroidManifest.xml), you may not need all of the following depending on your use case:

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_SERVICE"/>
    <uses-feature android:name="android.hardware.location.gps"/>

Otherwise it's useful to have a log of your error which would help pin down what's going on.

phiasco12 commented 2 years ago

@cbpolleydiscovr , Thank you for the reply.

Unfortunately none of the suggestions worked!

debugging the app in the Android Studio gives me this error:

2022-10-07 15:40:57.081 3454-3454/com.example.app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.app, PID: 3454
    java.lang.RuntimeException: Unable to start service com.marianhello.bgloc.service.LocationServiceImpl@7e93906 with null: java.lang.IllegalArgumentException: com.example.app: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
    Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4661)
        at android.app.ActivityThread.access$2000(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2095)
        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:7842)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.IllegalArgumentException: com.example.app: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
    Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
        at android.app.PendingIntent.checkFlags(PendingIntent.java:375)
        at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:645)
        at android.app.PendingIntent.getBroadcast(PendingIntent.java:632)
        at com.marianhello.bgloc.provider.ActivityRecognitionLocationProvider.onCreate(ActivityRecognitionLocationProvider.java:52)
        at com.marianhello.bgloc.service.LocationServiceImpl.start(LocationServiceImpl.java:359)
        at com.marianhello.bgloc.service.LocationServiceImpl.onStartCommand(LocationServiceImpl.java:274)
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4643)
            ... 9 more
2022-10-07 15:40:57.083 3454-3454/com.example.app E/com.marianhello.logging.UncaughtExceptionLogger: FATAL EXCEPTION: mainjava.lang.RuntimeException: Unable to start service com.marianhello.bgloc.service.LocationServiceImpl@7e93906 with null: java.lang.IllegalArgumentException: com.example.app: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
    Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4661)
        at android.app.ActivityThread.access$2000(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2095)
        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:7842)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.IllegalArgumentException: com.example.app: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
    Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
        at android.app.PendingIntent.checkFlags(PendingIntent.java:375)
        at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:645)
        at android.app.PendingIntent.getBroadcast(PendingIntent.java:632)
        at com.marianhello.bgloc.provider.ActivityRecognitionLocationProvider.onCreate(ActivityRecognitionLocationProvider.java:52)
        at com.marianhello.bgloc.service.LocationServiceImpl.start(LocationServiceImpl.java:359)
        at com.marianhello.bgloc.service.LocationServiceImpl.onStartCommand(LocationServiceImpl.java:274)
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4643)
        ... 9 common frames omitted

I'm not sure if this is to do with the FLAG_IMMUTABLE or FLAG_MUTABLE ?

I'm using the latest version of this plugin 2.0.7 which was supposed to be a fix for FLAG_IMMUTABLE or FLAG_MUTABLE.

phiasco12 commented 2 years ago

has anyone else got this issue?!

This's been bugging me for days now and I still can't figure it out!

Looking at the NotificationHelper.javafile, it seems to have the PendingIntent.FLAG_IMMUTABLE in place but the App still crashes and in Android Studio I see the Error that I mentioned above!!!

This doesn't make sense!

Can one of the maintainers please advice on this as I'm literally stuck in the limbo! Thanks

HarelM commented 2 years ago

Try deleting the plugins folder and run prepare again, set a breakpoint in the code and see that it reaches this point. Other than that, I don't have a better idea...

phiasco12 commented 2 years ago

Try deleting the plugins folder and run prepare again, set a breakpoint in the code and see that it reaches this point. Other than that, I don't have a better idea...

believe me.. done that countless times...

Not sure what you mean by "set a breakpoint in the code and see that it reaches this point".

But I believe the app goes as far as allowing 'Location' Permission and then crashes!

phiasco12 commented 2 years ago

Try deleting the plugins folder and run prepare again, set a breakpoint in the code and see that it reaches this point. Other than that, I don't have a better idea...

Do you know where the code is that creates a PendingIntent for LocationServiceImpl ? which file and location of it?

HarelM commented 2 years ago

You should be able to open android studio and debug the app. By doing so you can know for sure which part of the plugin is running and which part is crashing...

phiasco12 commented 2 years ago

That's what Ive been doing! and before I press allow device location on the device which crashes the app, I see these in the logcat in android studio:

2022-10-08 12:14:03.920 4667-4687/com.example.app I/com.marianhello.bgloc.service.LocationServiceImpl: Network condition changed has connectivity: true
2022-10-08 12:14:03.922 4667-4667/com.example.app D/com.marianhello.bgloc.service.LocationServiceImpl: Will start service with: Config[distanceFilter=50 stationaryRadius=50.0 desiredAccuracy=0 interval=10000 fastestInterval=5000 activitiesInterval=10000 isDebugging=false stopOnTerminate=true stopOnStillActivity=true startOnBoot=false startForeground=true notificationsEnabled=true locationProvider=1 nTitle=Background tracking nText=enabled nIconLarge= nIconSmall= nIconColor= url=http://192.168.81.15:3000/location syncUrl= syncThreshold=100 httpHeaders={X-FOO=bar} maxLocations=10000 postTemplate={"foo":"bar","lon":"@longitude","lat":"@latitude"}]
2022-10-08 12:14:03.922 4667-4667/com.example.app I/com.marianhello.bgloc.provider.ActivityRecognitionLocationProvider: Creating ActivityRecognitionLocationProvider
2022-10-08 12:14:03.923 4667-4667/com.example.app D/CompatibilityChangeReporter: Compat change id reported: 160794467; UID 10146; state: ENABLED
HarelM commented 2 years ago

Sorry man, I tired my best...

phiasco12 commented 2 years ago

WOW, 2 days and I finally managed to fix this!

the fix is rather strange!

So, first I copied the entire project in my own git and created a repo...

Then I edited android/build.gradleand added this:

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven { url "https://maven.google.com" }
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

ext {
    compileSdkVersion = 26
    targetSdkVersion = 26
    buildToolsVersion = "26.0.2"
    supportLibVersion = "26.1.0"
    googlePlayServicesVersion = "11.8.0"
}

Finally, I replaced ACTIVITY_PROVIDER with DISTANCE_FILTER_PROVIDER in my Javascript.

The strange part is that ACTIVITY_PROVIDER was working fine up until a few days ago! so not really sure what happened!!

at least this is my fix for now.

oracast commented 1 year ago

I've recently migrated from the previous iterations of this plugin on Ionic / Capacitor and I feel your pain. It's likely something to do with how you've configured the plugin, it doesn't necessarily do it automatically for you. The Mauron 85 version seemed to have a few setup issues which may or may not have been ironed out in this version. I've got it up and running now though, so with any luck here' some things that might help you:

in android/app/src/main/res/values/strings.xml, add the following:

<string name="plugin_bgloc_account_name">@string/app_name</string> <string name="plugin_bgloc_content_authority">$PACKAGE_NAME</string> <string name="plugin_bgloc_account_type">$PACKAGE_NAME.account</string>

For the previous version we had to use the following which I guess has now been replaced.

<string name="mauron85_bgloc_account_name">@string/app_name</string> <string name="mauron85_bgloc_content_authority">$PACKAGE_NAME</string> <string name="mauron85_bgloc_account_type">$PACKAGE_NAME.account</string>

Depending on the nature of your error, you might want to put the following in your app level build.gradle dependencies, all of these may not be necessary but worth a try (android/app/build.gradle):

    implementation "androidx.annotation:annotation:1.1.0"
    implementation 'androidx.work:work-runtime:2.7.1'
    implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'

Make sure you have the correct permissions in the android manifest (android/app/src/main/AndroidManifest.xml), you may not need all of the following depending on your use case:

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_SERVICE"/>
    <uses-feature android:name="android.hardware.location.gps"/>

Otherwise it's useful to have a log of your error which would help pin down what's going on.

It helped me to build project after migrating. Trying to test it properly. Thanks

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] commented 1 year ago

This issue has been automatically closed, because it has not had recent activity. If you believe this issue shouldn't be closed, please reopen or write down a comment requesting issue reopening with explanation why you think it's important. Thank you for your contributions.