Search code examples
angulartypescriptionic-frameworkcapacitor

Capacitor BackgroundTask Err: 'Cannot read property 'beforeExit' of undefined'


I have set up a background Task as shown in the Capacitor Docs and i get this Error. https://capacitorjs.com/docs/v2/apis/background-task

The Error occurs upon closing the Application

TypeError: Cannot read property 'beforeExit' of undefined
    at Object.callback (main.js:76)
    at Object.cap.fromNative ((index):434)
    at <anonymous>:1:18

My Background task Code

import { Component, OnInit } from '@angular/core'
import { DeviceService } from 'repapp-common-lib'
import { Plugins } from '@capacitor/core';

const { App, BackgroundTask, LocalNotifications } = Plugins;

export class AppComponent implements OnInit {

constructor(){}

 ngOnInit() {
  App.addListener('appStateChange', state => {
   if (!state.isActive) {

    let taskId = BackgroundTask.beforeExit(async () => {

      var start = new Date().getTime();
      for (var i = 0; i < 1e18; i++) {
        if (new Date().getTime() - start > 20000) {
          break;
        }
      }
      BackgroundTask.finish({
        taskId,
      });
    });
   }
  });
 }
}

Solution

  • Capacitor has no BackgroundTask function implemented yet.