Skip to content

Android Headless Mode

Chris Scott edited this page Jun 29, 2018 · 7 revisions

BackgroundGeolocation implements the "Headless Javascript" mechanism. With Headless Javascript, you can continue to respond to BackgroundGeolocation events after your app has been terminated (assuming you've configured stopOnTerminate: false).

Step 1: enableHeadless: true.

Where you execute BackgroundGeolocation#ready, add the following options:

import {BackgroundGeolocation} from "nativescript-background-geolocation-lt";

export class HelloWorldModel extends Observable {
  constructor() {
    
    BackgroundGeolocation.ready({
      enableHeadless: true,    // <-- Enable Android Headless mode
      stopOnTerminate: false,  // <-- required for Headless JS
      .
      .
      .
    }, (state) => {
      console.log('- Configure success');
    });

Step 2: BackgroundGeolocation#registerHeadlessTask

In your application's app.ts file, register your Javascript Headless Task:

📂 app/app.ts

import * as application from 'application';

import {BackgroundGeolocation} from "nativescript-background-geolocation-lt";
.
.
.
if (application.android) {
  BackgroundGeolocation.registerHeadlessTask((event, completionHandler) => {
    console.log('[My BackgroundGeolocation Headless Task]', event.name, event.params);
    // Do stuff.
    switch (event.name) {
      case 'boot':
        // handle boot event
        break;
      case 'terminate':
        // handle terminate event
        break;
      case 'location':
        // handle location event
        break;
      case 'motionchange':
         // handle motionchange event
         break;
      case 'geofence':
         // handle geofence event
         break;
      case 'heartbeat':
         // handle heartbeat event
         break;
      case 'providerchange':
         // handle providerchange event
         break;
      case 'activitychange':
         // handle activitychange event
         break;
      case 'http':
         // handle http event
         break;
      case 'schedule':
         // handle schedule event
         break;
    }
    completionHandler();  // <-- signal completion of your HeadlessTask
  });
}
application.run({ moduleName: 'app-root' });

Step 3: Try it!

  • Terminate your Android app.
  • Observe console messages from your registered Headless-task.