Skip to content

Android Headless Mode

Chris Scott edited this page Jun 2, 2021 · 5 revisions

Android Headless Setup

  • With your app open in Android Studio, browse the app folder to find the MainActivity class. Right-click the containing folder and click New > Java Class.

  • You MUST name the file BackgroundFetchHeadlessTask.

  • Add the following Java code to BackgroundFetchHeadlessTask, taking care to preserve the top line:

package com.your.package.name:

package com.your.package.name  // <-- DO NOT REPLACE THIS LINE!!!!!!!!!!!!

/// ---------------- Paste everything BELOW THIS LINE: -----------------------
import android.content.Context;
import android.util.Log;

import com.transistorsoft.tsbackgroundfetch.BackgroundFetch;
import com.transistorsoft.tsbackgroundfetch.BGTask;

public class BackgroundFetchHeadlessTask{
    public void onFetch(Context context,  BGTask task) {
        // Get a reference to the BackgroundFetch Android API.
        BackgroundFetch backgroundFetch = BackgroundFetch.getInstance(context);
        // Get the taskId.
        String taskId = task.getTaskId();
        // Log a message to adb logcat.
        Log.d("MyHeadlessTask", "BackgroundFetchHeadlessTask onFetch -- CUSTOM IMPLEMENTATION: " + taskId);

        boolean isTimeout = task.getTimedOut();
        // Is this a timeout?
        if (isTimeout) {
          backgroundFetch.finish(taskId);
          return;
        }
        // Do your work here...
        //
        //
        // Signal finish just like the Javascript API.
        backgroundFetch.finish(taskId);
    }
}

Testing Your Headless-task:

After terminating your app with Javascript configuration above, simulate a fetch-event while observing $ adb logcat

In the following command, replace com.your.app.package.name with your app's actual package-name:

adb shell cmd jobscheduler run -f com.your.app.package.name 999

 

$ adb logcat

TSBackgroundFetch: - Background Fetch event received: capacitor-background-fetch
MyHeadlessTask: BackgroundFetchHeadlessTask onFetch -- CUSTOM IMPLEMENTATION: capacitor-background-fetch
TSBackgroundFetch: - finish: capacitor-background-fetch
TSBackgroundFetch: - jobFinished

Clone this wiki locally