Options
All
  • Public
  • Public/Protected
  • All
Menu

BackgroundFetch is a module to receive periodic callbacks (min every 15 min) while your app is running in the background or terminated.

import {BackgroundFetch} from '@transistorsoft/capacitor-background-fetch';

class HomePage {

  // Initialize in ngAfterContentInit
  // [WARNING] DO NOT use ionViewWillEnter, as that method won't run when app is launched in background.
  ngAfterContentInit() {
    this.initBackgroundFetch();
  }

  async initBackgroundFetch() {
    const status = await BackgroundFetch.configure({
      minimumFetchInterval: 15
    }, async (taskId) => {  // <---------------- Event handler.
      console.log('[BackgroundFetch] EVENT:', taskId);
      // Perform your work in an awaited Promise
      const result = await this.performYourWorkHere();
      console.log('[BackgroundFetch] work complete:', result);
      // [REQUIRED] Signal to the OS that your work is complete.
      BackgroundFetch.finish(taskId);
    }, async (taskId) => {  // <---------------- Event timeout handler
      // The OS has signalled that your remaining background-time has expired.
      // You must immediately complete your work and signal #finish.
      console.log('[BackgroundFetch] TIMEOUT:', taskId);
      // [REQUIRED] Signal to the OS that your work is complete.
      BackgroundFetch.finish(taskId);
    });

    // Checking BackgroundFetch status:
    if (status !== BackgroundFetch.STATUS_AVAILABLE) {
      // Uh-oh:  we have a problem:
      if (status === BackgroundFetch.STATUS_DENIED) {
        alert('The user explicitly disabled background behavior for this app or for the whole system.');
      } else if (status === BackgroundFetch.STATUS_RESTRICTED) {
        alert('Background updates are unavailable and the user cannot enable them again.')
      }
    }
  }

  // Simulate a long-running task (eg:  an HTTP request)
  async performYourWorkHere() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(true);
      }, 5000);
    });
  }
}

iOS

  • There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently.
  • scheduleTask seems only to fire when the device is plugged into power.
  • ⚠️ When your app is terminated, iOS no longer fires events — There is no such thing as stopOnTerminate: false for iOS.
  • iOS can take days before Apple's machine-learning algorithm settles in and begins regularly firing events. Do not sit staring at your logs waiting for an event to fire. If your simulated events work, that's all you need to know that everything is correctly configured.
  • If the user doesn't open your iOS app for long periods of time, iOS will stop firing events.

Android

Hierarchy

  • BackgroundFetch

Index

Constructors

constructor

Accessors

Static NETWORK_TYPE_ANY

  • This job requires network connectivity.

    Returns NetworkType

Static NETWORK_TYPE_CELLULAR

  • This job requires network connectivity that is a cellular network.

    Returns NetworkType

Static NETWORK_TYPE_NONE

  • This job doesn't care about network constraints, either any or none.

    Returns NetworkType

Static NETWORK_TYPE_NOT_ROAMING

  • This job requires network connectivity that is not roaming.

    Returns NetworkType

Static NETWORK_TYPE_UNMETERED

  • This job requires network connectivity that is unmetered.

    Returns NetworkType

Static STATUS_AVAILABLE

Static STATUS_DENIED

  • The user explicitly disabled background behavior for this app or for the whole system.

    Returns BackgroundFetchStatus

Static STATUS_RESTRICTED

  • Background fetch updates are unavailable and the user cannot enable them again. For example, this status can occur when parental controls are in effect for the current user.

    Returns BackgroundFetchStatus

Methods

Static configure

  • Initial configuration of BackgroundFetch, including config-options and Fetch-callback. The start method will automatically be executed.

      async initBackgroundFetch() {
        const status = await BackgroundFetch.configure({
          minimumFetchInterval: 15
        }, async (taskId) => {  // <---------------- Event handler.
          console.log('[BackgroundFetch] EVENT:', taskId);
          // Perform your work in an awaited Promise
          const result = await this.performYourWorkHere();
          console.log('[BackgroundFetch] work complete:', result);
          // [REQUIRED] Signal to the OS that your work is complete.
          BackgroundFetch.finish(taskId);
        }, async (taskId) => {  // <---------------- Event timeout handler
          // The OS has signalled that your remaining background-time has expired.
          // You must immediately complete your work and signal #finish.
          console.log('[BackgroundFetch] TIMEOUT:', taskId);
          // [REQUIRED] Signal to the OS that your work is complete.
          BackgroundFetch.finish(taskId);
        });
    
        // Checking BackgroundFetch status:
        if (status !== BackgroundFetch.STATUS_AVAILABLE) {
          // Uh-oh:  we have a problem:
          if (status === BackgroundFetch.STATUS_DENIED) {
            alert('The user explicitly disabled background behavior for this app or for the whole system.');
          } else if (status === BackgroundFetch.STATUS_RESTRICTED) {
            alert('Background updates are unavailable and the user cannot enable them again.')
          }
        }
      }
    
      // Simulate a long-running task (eg:  an HTTP request)
      async performYourWorkHere() {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve(true);
          }, 5000);
        });
      }
    }
    

    Parameters

    • config: BackgroundFetchConfig
    • onEvent: (taskId: string) => void
        • (taskId: string): void
        • Parameters

          • taskId: string

          Returns void

    • Optional onTimeout: (taskId: string) => void
        • (taskId: string): void
        • Parameters

          • taskId: string

          Returns void

    Returns Promise<BackgroundFetchStatus>

Static finish

  • finish(taskId: string): Promise<void>
  • You must execute BackgroundFetch.finish(taskId) within your fetch-callback to signal completion of your task.

    If you fail to call .finish(), the OS will punish your app for poor behaviour and stop firing events.

    await BackgroundFetch.configure({
      minimumFetchInterval: 15
    }, async (taskId) => {
      console.log('[BackgroundFetch] EVENT', taskId);
      // Always signal completion of your tasks.
      BackgroundFetch.finish(taskId);
    }, async (taskId) => {
      console.log('[BackgroundFetch] TIMEOUT', taskId);
      // Always signal completion of your tasks.
      BackgroundFetch.finish(taskId);
    });
    

    Parameters

    • taskId: string

    Returns Promise<void>

Static scheduleTask

  • Execute a custom task in addition to the one initially provided to configure. This event can be configured to either a "ONE-SHOT" or "PERIODIC" with TaskConfig.periodic.

    // You must ALWAYS first configure BackgroundFetch.
    const status = await BackgroundFetch.configure({
      minimumFetchInterval: 15
    }, async (taskId) => {
      console.log('[BackgroundFetch] EVENT', taskId);
      if (taskId === 'my-custom-task') {
        console.log('Handle your custom-task here');
      } else {
        console.log('This is the default, periodic fetch task');
      }
      // Always signal completion of your tasks.
      BackgroundFetch.finish(taskId);
    }, async (taskId) => {
      console.log('[BackgroundFetch] TIMEOUT', taskId);
      if (taskId === 'my-custom-task') {
        console.log('My custom task timed-out');
      } else {
        console.log('The default, periodic fetch task timed-out');
      }
      BackgroundFetch.finish(taskId);
    });
    
    // Execute an additional custom-task.
    BackgroundFetch.scheduleTask({
      taskId: 'my-custom-task',  // <-- REQUIRED
      delay: 10000,              // <-- REQUIRED
      periodic: false            // <-- ONE-SHOT (default)
    })
    

    Parameters

    Returns Promise<void>

Static start

  • Start subscribing to fetch events.

    Note: The inital call to configure automatically calls BackgroundFetch.start()

      async initBackgroundFetch() {
        // Calling .configure() automatically starts the plugin.
        const status = await BackgroundFetch.configure({
          minimumFetchInterval: 15
        }, async (taskId) => {  // <---------------- Event handler.
          console.log('[BackgroundFetch] EVENT:', taskId);
          BackgroundFetch.finish(taskId);
        }, async (taskId) => {  // <---------------- Event timeout handler
          console.log('[BackgroundFetch] TIMEOUT:', taskId);
          // [REQUIRED] Signal to the OS that your work is complete.
          BackgroundFetch.finish(taskId);
        });
      }
    
      // Stop BackgroundFetch
      onClickStop() {
        BackgroundFetch.stop();
      }
    
      // Re-start BackgroundFetch
      onClickStart() {
        BackgroundFetch.start();
      }
    
    

    Returns Promise<BackgroundFetchStatus>

Static status

  • Query the BackgroundFetch API status

    // Checking BackgroundFetch status:
    const status = await BackgroundFetch.status();
    
    if (status !== BackgroundFetch.STATUS_AVAILABLE) {
      // Uh-oh:  we have a problem:
      if (status === BackgroundFetch.STATUS_DENIED) {
        alert('The user explicitly disabled background behavior for this app or for the whole system.');
      } else if (status === BackgroundFetch.STATUS_RESTRICTED) {
        alert('Background updates are unavailable and the user cannot enable them again.')
      }
    }
    
    BackgroundFetchStatus Description
    BackgroundFetch.STATUS_RESTRICTED Background fetch updates are unavailable and the user cannot enable them again. For example, this status can occur when parental controls are in effect for the current user.
    BackgroundFetch.STATUS_DENIED The user explicitly disabled background behavior for this app or for the whole system.
    BackgroundFetch.STATUS_AVAILABLE Background fetch is available and enabled.

    Returns Promise<BackgroundFetchStatus>

Static stop

  • stop(taskId?: string): Promise<void>
  • Stop subscribing to fetch events.

    // Stop everything.
    BackgroundFetch.stop();
    

    You may also provide an optional taskId to stop a scheduleTask:

    // Stop a particular task scheduled with BackgroundFetch.scheduleTask
    await BackgroundFetch.scheduleTask({
      taskId: 'my-custom-task',
      delay: 10000,
      periodic: false
    });
    .
    .
    .
    BackgroundFetch.stop('my-custom-task');
    

    Parameters

    • Optional taskId: string

    Returns Promise<void>

Generated using TypeDoc