mauron85 / cordova-plugin-background-geolocation

Background and foreground geolocation plugin for Cordova.
Apache License 2.0
538 stars 406 forks source link

Unable to start service Intent on calling BackgroundGeolocation.start() #549

Closed Amsvartner closed 5 years ago

Amsvartner commented 5 years ago

Your Environment

Context

Using the example code provided, the GPS tracking doesn't initialize properly and cannot be used.

Expected Behavior

The GPS tracking service should start, and the foreground notification in the top drawer should be visible.

Actual Behavior

Nothing happens, the service isn't started. Foreground notification does not appear (but the events for background mode triggers in the console.log)

Possible Fix

There has been changes to background mode, and how you start Intents, in Android 8.0+ https://developer.android.com/about/versions/oreo/background

The following issue in the react-native project may be of interest: https://github.com/mauron85/react-native-background-geolocation/issues/172

Debug logs

02-04 09:04:57.034  5194  5270 I com.marianhello.bgloc.BackgroundGeolocationFacade: Initializing plugin
02-04 09:04:57.082  5194  5270 D com.tenforwardconsulting.bgloc.cordova.BackgroundGeolocationPlugin: Registering event listeners
02-04 09:04:57.109  5194  5270 W PluginManager: THREAD WARNING: exec() call to BackgroundGeolocation.addEventListener blocked the main thread for 27ms. Plugin should use CordovaInterface.getThreadPool().
02-04 09:04:57.117  5194  5230 D NetworkSecurityConfig: No Network Security Config specified, using platform default
02-04 09:04:57.362  5194  5194 D SystemWebChromeClient: file:///android_asset/www/plugins/cordova-plugin-android-softinputmode/www/interface.js: Line 3 : Success
02-04 09:04:57.362  5194  5194 I chromium: [INFO:CONSOLE(3)] "Success", source: file:///android_asset/www/plugins/cordova-plugin-android-softinputmode/www/interface.js (3)
02-04 09:04:57.462  5194  5272 D com.marianhello.bgloc.data.sqlite.SQLiteConfigurationDAO: Configuration persisted with rowId = 1
02-04 09:04:57.466  5194  5272 D com.marianhello.bgloc.BackgroundGeolocationFacade: Service configured with: Config[distanceFilter=50 stationaryRadius=100.0 desiredAccuracy=0 interval=3000 fastestInterval=5000 activitiesInterval=10000 isDebugging=true stopOnTerminate=true stopOnStillActivity=true startOnBoot=false startForeground=true notificationsEnabled=true locationProvider=1 nTitle=PolarFleet GPS tracking nText=enabled nIconLarge= nIconSmall= nIconColor= url=myUrl Threshold=100 httpHeaders={Content-Type=application/json} maxLocations=1 postTemplate={"heading":"@bearing","foo":"bar","lon":"@longitude","id":"ADG198","lat":"@latitude","speed":"@speed","timestamp":""}]
02-04 09:04:57.490  5194  5251 D EGL_emulation: eglMakeCurrent: 0xa9205d80: ver 3 0 (tinfo 0x9563a050)
02-04 09:04:57.508  1638  1941 W ActivityManager: Unable to start service Intent { cmp=myApp/com.marianhello.bgloc.service.LocationServiceImpl (has extras) } U=0: not found
mauron85 commented 5 years ago

It is the exact same problem as has been posted and fixed in the react-native project: mauron85/react-native-background-geolocation#172

if it's exactly same problem, then it was already merged here somewhere before alpha.50.

Amsvartner commented 5 years ago

That doesn't give me much to go on in trying to solve the problem :)

It is giving me the same error messages in the log and the same unexpected behaviour from the plugin, thus I assumed it had the same cause. I am not familiar with java.

int128fly commented 5 years ago

I have the exact same issue, my cordova and android version is the exact same as @Amsvartner but I am using ionic (shouldn't matter). The issue isn't with the .start() but .configure() anything below it is not getting executed like if there were an error or something but the app don't crash.

import { Component } from '@angular/core';
import { Platform, AlertController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';
import { BackgroundGeolocation, BackgroundGeolocationConfig, BackgroundGeolocationResponse } from '@ionic-native/background-geolocation/ngx';
import { LocalNotifications } from '@ionic-native/local-notifications';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;

  constructor(public platform: Platform, 
              public statusBar: StatusBar, 
              public splashScreen: SplashScreen,
              protected backgroundGeolocation: BackgroundGeolocation,
              protected alert: AlertController,
              private localNotifications: LocalNotifications) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();

      console.log('pre-initializing everything! <--------------------------------------------------------------');

      const config: BackgroundGeolocationConfig = {
        desiredAccuracy: 1000,
        locationProvider: 1,
        stationaryRadius: 50,
        distanceFilter: 50,
        notificationTitle: 'Background tracking',
        notificationText: 'enabled',
        debug: true,
        interval: 10000,
        fastestInterval: 5000,
        activitiesInterval: 10000,
      };

      this.backgroundGeolocation.configure(config)
        .subscribe((location: BackgroundGeolocationResponse) => {
          console.log(location);

          // IMPORTANT:  You must execute the finish method here to inform the native plugin that you're finished,
          // and the background-task may be completed.  You must do this regardless if your HTTP request is successful or not.
          // IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
          this.backgroundGeolocation.finish(); // FOR IOS ONLY
        }, (error) => {
          console.log('hey something bad happened!');
          console.log(error);
        });

      console.log('hey before we start anything did configure work?');

      // start recording location
      this.backgroundGeolocation.start();

      console.log('hey everything should be initialized!');

      // If you wish to turn OFF background-tracking, call the #stop method.
      //this.backgroundGeolocation.stop();
    });
  }
}
D/SystemWebChromeClient: http://localhost/build/vendor.js: Line 134709 : Ionic Native: deviceready event fired after 1433 ms
I/chromium: [INFO:CONSOLE(134709)] "Ionic Native: deviceready event fired after 1433 ms", source: http://localhost/build/vendor.js (134709)
D/SystemWebChromeClient: http://localhost/build/main.js: Line 218 : pre-initializing everything! <--------------------------------------------------------------
I/chromium: [INFO:CONSOLE(218)] "pre-initializing everything! <--------------------------------------------------------------", source: http://localhost/build/main.js (218)
D/SystemWebChromeClient: http://localhost/build/vendor.js: Line 2085 : ERROR
I/chromium: [INFO:CONSOLE(2085)] "ERROR", source: http://localhost/build/vendor.js (2085)
D/EGL_emulation: eglMakeCurrent: 0x9079a120: ver 3 0 (tinfo 0x93f07980)

edit: I've tried alpha.46 and I have the same issue.

just in case your interested to know what is line 2085 in vendor.js

/**
 * @param {?} console
 * @param {...?} values
 * @return {?}
 */
function defaultErrorLogger(console) {
    var values = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        values[_i - 1] = arguments[_i];
    }
    console.error.apply(console, values); // <---- LINE 2085
}

I've posted my project on github if that can help. The project is almost blank. https://github.com/int128fly/Ionic-Background-Notification-not-working

Amsvartner commented 5 years ago

I suspect that we may not have the same problem, because everything else works for me (background/foreground mode, app settings etc) but nothing happens when I call start() in the checkStatus callback, and no notification about background mode is shown in the drawer at the top.

Javascript

BackgroundGeolocation.configure({
    locationProvider : BackgroundGeolocation.ACTIVITY_PROVIDER,
    desiredAccuracy : BackgroundGeolocation.HIGH_ACCURACY,
    stationaryRadius : 100,
    distanceFilter : 50,

    startForeground : true,
    notificationTitle : 'GPS tracking',
    notificationText : 'enabled',

    debug : true,
    interval : 3000,
    fastestInterval : 5000,
    activitiesInterval : 10000,
    maxLocations : 1,
    url : "http://something",

    httpHeaders : {
        'Content-Type' : 'application/json'
    }
});

BackgroundGeolocation.on('location', function (location) {
    console.log(location);

    BackgroundGeolocation.startTask(function (taskKey) {
         BackgroundGeolocation.endTask(taskKey);
    });
});

BackgroundGeolocation.on('stationary', function (stationaryLocation) {
    console.log(stationaryLocation);
});

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

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

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

BackgroundGeolocation.on('authorization', function (status) {
    console.log('[INFO] BackgroundGeolocation authorization status: ' + status);

    if (status !== BackgroundGeolocation.AUTHORIZED) {
        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 () {
    console.log('[INFO] App is in background');
    BackgroundGeolocation.configure({ debug : true });
});

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

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

BackgroundGeolocation.on('http_authorization', function () {
    console.log('[INFO] App needs to authorize the http requests');
});

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

    if (!status.isRunning) {
        BackgroundGeolocation.start(); //nothing happens..
    }
});

console.log output

[INFO] BackgroundGeolocation service is running false
[INFO] BackgroundGeolocation services enabled true
[INFO] BackgroundGeolocation auth status: 1
int128fly commented 5 years ago

Thanks for your inputs, I've just got it working, apparently the issue was in the @ionic-native/background-geolocation/ngx

Using the following work properly, I will create my own ionic provider at that point.

declare var BackgroundGeolocation: any;

and you were correct we do not have the same issue, sorry for stealing your thread