GithubHelp home page GithubHelp logo

vikeri / react-native-background-job Goto Github PK

View Code? Open in Web Editor NEW
743.0 17.0 107.0 1.07 MB

Schedule background jobs in React Native that run your JavaScript when your app is in the background/killed.

License: MIT License

Java 44.41% JavaScript 39.61% Objective-C 8.85% Python 3.90% Shell 3.23%
react-native scheduled-jobs background-jobs

react-native-background-job's Introduction

react-native-background-job npm version CircleCI

Schedule background jobs that run your JavaScript when your app is in the background or if you feel brave even in foreground.

The jobs will run even if the app has been closed and, by default, also persists over restarts.

This library relies on React Native's HeadlessJS which is currently only supported on Android.

On the native side it uses either Firebase JobDispatcher or a AlarmManager.

  • Firebase JobDispatcher (default): The jobs can't be scheduled exactly and depending on the Android API version different period time is allowed. FirebaseJobDispatcher is the most battery efficient backward compatible way of scheduling background tasks.

  • AlarmManager by setting exact to true: Simple propriatery implementation that is only ment to be used while testing. It only cares about executing on time, all other parameters are ignored - job is not persisted on reboot.

Requirements

  • RN 0.36+
  • Android API 16+

Supported platforms

  • Android

Want iOS? Go in and vote for Headless JS to be implemented for iOS: Product pains

Getting started

$ yarn add react-native-background-job

or

$ npm install react-native-background-job --save

Mostly automatic installation

$ react-native link react-native-background-job

Manual installation

Android

  1. Open up android/app/src/main/java/[...]/MainApplication.java

    • Add import com.pilloxa.backgroundjob.BackgroundJobPackage; to the imports at the top of the file.
    • Add new BackgroundJobPackage() to the list returned by the getPackages() method.
  2. Append the following lines to android/settings.gradle:

    include ':react-native-background-job'
    project(':react-native-background-job').projectDir = new File(rootProject.projectDir, 	'../node_modules/react-native-background-job/android')
    
  3. Insert the following lines inside the dependencies block in android/app/build.gradle and bump the minSdkVersion to 21:

    compile project(':react-native-background-job')
    

Usage

The jobs have to be registered each time React Native starts, this is done using the register function. Since HeadlessJS does not mount any components the register function must be run outside of any class definitions (see example/index.android.js)

Registering the job does not mean that the job is scheduled, it just informs React Native that this job function should be tied to this jobKey. The job is then scheduled using the schedule function. By default, the job will not fire while the app is in the foreground. This is since the job is run on the only JavaScript thread and if running the job when app is in the foreground it would freeze the app. By setting allowExecutionInForeground to true you allow this behavior. It is recommended that you do't use this, but for quick jobs should be fine.

For a full example check out example/index.android.js

API

Table of Contents

register

index.js:39-55

Registers the job and the functions they should run.

This has to run on each initialization of React Native and it has to run in the global scope and not inside any component life cycle methods. See example project. Only registering the job will not schedule the job. It has to be scheduled by schedule to start running.

Parameters

  • obj Object
    • obj.jobKey string A unique key for the job
    • obj.job function The JS-function that will be run

Examples

import BackgroundJob from 'react-native-background-job';

const backgroundJob = {
 jobKey: "myJob",
 job: () => console.log("Running in background")
};

BackgroundJob.register(backgroundJob);

schedule

index.js:95-142

Schedules a new job.

This only has to be run once while register has to be run on each initialization of React Native.

Parameters

  • obj Object
    • obj.jobKey string A unique key for the job that was used for registering, and be used for canceling in later stage.
    • obj.timeout number The amount of time (in ms) after which the React instance should be terminated regardless of whether the task has completed or not. (optional, default 2000)
    • obj.period number The frequency to run the job with (in ms). This number is not exact, Android may modify it to save batteries. Note: For Android > N, the minimum is 900 0000 (15 min). (optional, default 900000)
    • obj.persist boolean If the job should persist over a device restart. (optional, default true)
    • obj.override boolean Whether this Job should replace pre-existing jobs with the same key. (optional, default true)
    • obj.networkType number Only run for specific network requirements. (optional, default NETWORK_TYPE_NONE)
    • obj.requiresCharging boolean Only run job when device is charging, (not respected by pre Android N devices) docs (optional, default false)
    • obj.requiresDeviceIdle boolean Only run job when the device is idle, (not respected by pre Android N devices) docs (optional, default false)
    • obj.exact boolean Schedule an job to be triggered precisely at the provided period. Note that this is not power-efficient way of doing things. (optional, default false)
    • obj.allowWhileIdle boolean Allow the scheduled job to execute also while it is in doze mode. (optional, default false)
    • obj.allowExecutionInForeground boolean Allow the scheduled job to be executed even when the app is in foreground. Use it only for short running jobs. (optional, default false)
    • obj.notificationText string For Android SDK > 26, what should the notification text be (optional, default "Running in background...")
    • obj.notificationTitle string For Android SDK > 26, what should the notification title be (optional, default "Background job")

Examples

import BackgroundJob from 'react-native-background-job';

const backgroundJob = {
 jobKey: "myJob",
 job: () => console.log("Running in background")
};

BackgroundJob.register(backgroundJob);

var backgroundSchedule = {
 jobKey: "myJob",
}

BackgroundJob.schedule(backgroundSchedule)
  .then(() => console.log("Success"))
  .catch(err => console.err(err));

cancel

index.js:156-166

Cancel a specific job

Parameters

Examples

import BackgroundJob from 'react-native-background-job';

BackgroundJob.cancel({jobKey: 'myJob'})
  .then(() => console.log("Success"))
  .catch(err => console.err(err));

cancelAll

index.js:177-187

Cancels all the scheduled jobs

Examples

import BackgroundJob from 'react-native-background-job';

BackgroundJob.cancelAll()
  .then(() => console.log("Success"))
  .catch(err => console.err(err));

setGlobalWarnings

index.js:199-201

Sets the global warning level

Parameters

Examples

import BackgroundJob from 'react-native-background-job';

BackgroundJob.setGlobalWarnings(false);

isAppIgnoringBatteryOptimization

index.js:213-229

Checks Whether app is optimising battery using Doze,returns Boolean.

Parameters

  • callback Callback gets called with according parameters after result is received from Android module.

Examples

import BackgroundJob from 'react-native-background-job';

BackgroundJob.isAppIgnoringBatteryOptimization((err, isIgnoring) => console.log(`Callback: isIgnoring = ${isIgnoring}`))
  .then(isIgnoring => console.log(`Promise: isIgnoring = ${isIgnoring}`))
  .catch(err => console.err(err));

Troubleshooting

No task registered for key myJob

Make sure you call the register function at the global scope (i.e. not in any component life cycle methods (render, iDidMount etc)). Since the components are not rendered in Headless mode if you run the register function there it will not run in the background and hence the library will not find which function to run.

See example project

AppState.currentState is "active" when I'm running my Headless task in the background

This is a React Native issue, you can get around it by calling NativeModules.AppState.getCurrentAppState directly instead.

My job always runs in the background even if I specified requiresCharging, requiresDeviceIdle or a specific networkType

This is an Android issue, it seems that you can not have these restrictions at the same time as you have a periodic interval for pre Android N devices.

Pull Request Details

Included function for checking if the app is ignoring battery optimizations. #62

In Android SDK versions greater than 23, Doze is being used by apps by default, in order to optimize battery by temporarily turning off background tasks when the phone is left undisturbed for some hours.

But, some apps may require background tasks to keep running, ignoring doze and not optimizing battery (this means battery needs to be traded off for performance as per required). Apps that require continuous syncing of data to the server at short intervals of time are examples of such apps.

It would be good if the developer can check whether the app is optimizing battery. If it is, the user can be notified that the app would not perform as per expected and it will work properly only if the user manually removes it from the battery optimizing apps list which can be found in Settings-> Battery -> Options (button on top right) -> Battery Optimization and then selecting "All Apps" to change the battery optimization settings for the particular app.

The Changes that have been made are specifically for that purpose, a function (isAppIgnoringBatteryOptimization) has been included. It checks if the app is ignoring battery optimization and returns false if it is optimizing battery (in which case the user has to manually remove it from battery settings) and true otherwise.

Logic has also been added for scheduling the task by ignoring battery optimizations, if the app has been manually removed from the battery optimization list in settings (by the User).

Sponsored by

pilloxa

react-native-background-job's People

Contributors

alexey-kuznetsov avatar dependabot[bot] avatar hkairi avatar joeltok avatar jussisaurio avatar mauriciopasquier avatar maximiliankindshofer avatar mkds622 avatar niclas-jetset avatar proshoumma avatar sagium avatar toteto avatar vikeri avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-background-job's Issues

Lock screen location

Can you continue positioning in the lock screen status?
Now the app can be positioned in the foreground and background, but it's a bit of a fix in the lock screen state

Background jobs never running (Android)

I'm trying to get run some code in the background when the app is closed. I start up the app and get the console log saying the job has been scheduled, but then after i exit the code never seems to run and I can't find it in my phones list of processes/services.

This is the code, am I using the package incorrectly?

import FCM from 'react-native-fcm';
import { Alert } from 'react-native';
import * as AuthService from './app/services/auth';
import BadgeAndroid from './native_modules/BadgeAndroid';

import Index from './index.ios';

BackgroundJob.register({
  jobKey: 'pushListener',
  timeout: 15000,
  job: async () => {
    const fcmToken = await FCM.getFcmToken();
    const response = await AuthService.fetchBadgeCount(fcmToken);
    Alert.alert(JSON.stringify(response.data));
    BadgeAndroid.setBadge(response.data.data.attributes.badge_count);
  },
});

BackgroundJob.register({
  jobKey: 'testAlert',
  job: () => {
    Alert.alert('test')
  },
});

BackgroundJob.schedule({ jobKey: 'pushListener' });
BackgroundJob.schedule({ jobKey: 'testAlert' });

export default Index;

Exception thrown while job is fired

Running reference example app on latest react-native build.

"react": "16.0.0-alpha.12",
"react-native": "0.48.2",
"react-native-background-job": "^2.0.0"

Exception: Expected to run on UI thread!
2017-09-12 21 54 13

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';
import BackgroundJob from 'react-native-background-job';

const myJobKey = "myJobKey";

BackgroundJob.register({
 jobKey: myJobKey,
 job: () => {
   console.log("Running in background");
   console.log((new Date).toString());
 }
});

export default class BackgroundJobApp extends Component {
  componentDidMount() {
    BackgroundJob.schedule({
     jobKey: myJobKey,
     period: 900000,
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Double tap R on your keyboard to reload,{'\n'}
          Shake or press menu button for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('BackgroundJob', () => BackgroundJobApp);

Error at compilation

Hey ! Thank for you plugin !

I have a problem when i'm trying to compile my project i have this error :

* What went wrong:
A problem occurred configuring project ':app'.
> A problem occurred configuring project ':react-native-background-job'.
   > failed to find Build Tools revision 23.0.3

Do you have an idea?

Passing variables to the job function?

Is there anyway to pass variables to the job function? Was hoping to use this lib for running a timer in the background which has a time determined by the user, as well as send a post request to a user assigned address.

Job does not run at fixed interval

Hi vikeri,

I want to run a JS task at interval of every 2 minute or so while app is in background or when rebooted. Job runs on reboot or in background always and schedules tasks. This works fine. Only issue I am facing is that it does not start JS task every two minutes. It will start JS task at 2min, 5min or 7min or max 18 mins or so.

Is there way to ensure JS task runs always consistently at fix interval overwriting previous task?
Thanks
Satish

Tried to start task while in foreground

screenshot_2017-08-31-00-42-34

I'm new to react native, i coded it like this:

BackgroundJob.register({
    jobKey: "userNotif",
    job: async () => {
        try {
          const value = await AsyncStorage.getItem(USER_DATA);
            if (value !== null) {
                if (value !== 'anonymous') {
                    let parsedValue = JSON.parse(value);
                    await navigator.geolocation.getCurrentPosition(
                    async (position) => {
                        let userData = parsedValue;
                        let userLocation = {};
                        userLocation.latitude = position.coords.latitude;
                        userLocation.longitude = position.coords.longitude;
                        const timeInterval = await AsyncStorage.getItem(SELECTED_TIME_INTERVAL);
                        const reportRadius = await AsyncStorage.getItem(SELECTED_RADIUS);
                        const notificationAxios = axios.create({
                            baseURL: 'test-url',
                        });

                        await notificationAxios.post('test-url/reports/nearby', {
                            selected_radius: reportRadius ? parseFloat(reportRadius) : 0.5,
                            user_location: userLocation,
                            time_interval: timeInterval ? parseFloat(timeInterval) : 5,
                        })
                        .then((response) => {
                            if (response.data.status == 'success') {
                                if (response.data.reports.length > 0) {
                                    let isSingular = response.data.reports.length == 1;

                                    NotificationsAndroid.localNotification({
                                        title: "Please Be Careful!",
                                        body: "There " + ( isSingular ? 'is' : 'are' ) + " " + response.data.reports.length + " " + ( isSingular ? 'report' : 'reports' ) + " near your location!. Please be aware and if you feel something bad may happen, don't hesitate to call the police. Thanks!",
                                        extra: {
                                            time: MOMENT(),
                                        }
                                    });
                                }
                            }
                        })
                        .catch((error) => {
                            console.log(JSON.stringify(error));
                        });
                    },
                    (error) => {
                        console.log(JSON.stringify(error));
                    },
                        {enableHighAccuracy: true, timeout: 20000}
                    );
                }
            }
        } catch (error) {
            console.log(error);
        }
    }
});

export default class VeevMobile extends Component {
    componentDidMount() {
          BackgroundJob.schedule({
                    jobKey: 'userNotif',
                    // period: 300000,
                    period: 30000,
                    period: 10000,
                    timeout: 5000,
                    persist: true
         });
   }
}

All the time, after closing my app it crashes and stops. Then when I opened my app, i see this error. How can i fix this one?

Just another question, I am testing my app on real device, when i open the app and after the background job has been registered, i tried clicking the android home button which makes me go to Android Home. it doesnt notify me even if its on the recent list of apps. Is it because of my device? or something with the jobs?

Using for background audio?

On the native side it uses JobScheduler which means that the jobs can't be scheduled exactly and for Android 23+ they fire at most once per 15 minutes +-5 minutes.

So is it safe to say that this wouldn't be a good tool to use for managing background audio? (eg, getting a playlist to switch to the next song while backgrounded).

not working in android 8.0

i tried working it in android 8.0 background job is getting fired when the app is in background but doesn't work when the app is closed.

List of all scheduled jobs

Is it possible to get a list of scheduled jobs and their configurations?
Possible use case might be to check if a job is scheduled and override it with new config if needed.

PS. Great package. Thank you!

Do it suite for Android 7?

Hi, I am newer, maybe It's my problem of my code.
I tested in both of Android 6 (1 emulator & 1 device) and 7(1 emulator and 1 device).
6 is fine, but 7 always crashed and shows error "tried to start task myJob while in the foreground, but it's not allowed."

and in 6 & 7
I gots same yellow warning "backgroundjob: overwriting background job: myjob
but 6 don't crash.

my RN version:
react-native-cli: 1.2.0
react-native: 0.40.0

app Crash when background start [Android]

I have a problem with my background Job.
When ร  leave the app (without kill it) I have my background running.

But If I kill the app (swiping to the left in android) I have a message " has closed" or " keeps stopping" every 5 second (period of my background). Every time the background task start, the app crash.
I know you'll say that it's at least 15 min, but I have also try without the period field.

I can past my code but I can garantee you it's okay like on the example. I have try a lot of different thing before posting...

I have try react-native-background-task, and it's exactly the same ! I think I have a problem on my app. Maybe an other dependency who conflict with a background task, or other.

With backround task I don't have this problem on IOS, only on Android.
Always crashed...

Any help ? :)

current ios native module

Hey,

I'm getting an error when I import the module on iOS. I'm aware that the functionality isn't there yet, but I'd rather not have to make two separate files to handle my main app logic.

I was able to fix the problem if I did this:


const AppState = NativeModules.AppState;
const tag = "BackgroundJob:";
const jobModule = NativeModules.BackgroundJob;
if (Platform.OS === 'ios') jobModule = {}; // added this line
const nativeJobs = jobModule.jobs;
var jobs = {};
var globalWarning = __DEV__;

I think something like this might be helpful for others as well.

Thanks!
RB

Support with create-react-native-app

Is there any solution for getting this to work with create-react-native-app or expo?

getting undefined is not an object (evaluating "jobModules.jobs"

Tried using the example code on a fresh CRNA install.

Persist react-native-router-flux scene

On android, when I schedule background job with alwaysRunning: true, fold app into background and press on notification tile it opens app on initial scene instead of last active scene. Not sure if it's an issue or I'm doing something wrong

How can I use this library for location tracking task?

I am trying to understand how this library works by running it on my phone. It works great so far but how can I use it for location tracking task?

I am building an app where it requires conscience when it goes to background. The app would actively track user' coordinates (not by the interval, but according to the updates emit by the user' walking activity).

I've run the example and notice a few features. When the app goes into the background, it runs the job every 5 seconds. But when I lock my phone, it hardly runs the job, more like every 1 - 2 minute. If I understand correctly, it's Android that's trying to save battery.

So it isn't practical if I encapsulate my LocationManager GPS function inside the register() method, right? For example, if the phone is locked, and register() method only gets called every 2 minutes, then watchPosition() would not be called, if somehow, Android kills my app because of its running low on memory.

BackgroundJob.register({
  jobKey: myJobKey,
  job: () => {
    this.location = navigator.geolocation.watchPosition(({ coords}) => {
      // other methods
    })
  }
});

Ultimately I just need something to keep the app alive so that my other methods can run happily.

Crash after close app

Hello,
If app is in background everything work fine. If I close app, crash message pops up every period time:
RN 0.40
Android 6.0

Code:
` const backgroundJob = {
jobKey: "speedtask",
job: () => {
console.log('error');
}
};
BackgroundJob.cancelAll();
BackgroundJob.register(backgroundJob);
BackgroundJob.schedule({jobKey: 'speedtask', period: 5000, timeout: 30000 })

`

Can you paste working code ?

Job doesn't start again after restarting the phone

Hi,
I am scheduling a job like so:

var backgroundSchedule = {
        jobKey: BACKGROUND_JOB_KEY,
        timeout: 5000,
        period: 9999999,
        alwaysRunning: true,
        notificationTitle: str('notificationTitle'),
        notificationIcon: 'ic_infinity',
        persist: true
}

BackgroundJob.schedule(backgroundSchedule);

The job runs in the background and the notification is on. But, after restarting the phone, the job doesn't start again.
Tried this on a few android phones.

Any ideas?

API in background not working

hello ,
I am facing an issue of how to call the inside class method outside the class.
What I want is to call driversetstatus method in background.register

Please help asap.
Thanks

Code:

const myJobKey = "Hej";
BackgroundJob.register({
jobKey: myJobKey,#
job: () => driverSetStatus();
});

export default class BroadcastTask extends Component {
constructor(props) {
super(props);
this.state = {
jobs: [] ,
userId: '',
status: '',
latitude: '',
longitude: '',
address: '',
flag: '',
};

}

getAll() {
BackgroundJob.getAll({
callback: jobs => {
this.setState({ jobs });
console.log("Jobs:", jobs);
}
});
}

driverSetStatus() {
BackgroundJob.getAll({
callback: status => {
this.setState({ status });
console.log("Status:", status);
}
});
debugger;
fetch(API_URL_POST_BaseURL + API_SET_DRIVER_STATUS, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Application-Type': (Platform.OS === 'ios') ? "IOS" : "ANDROID",
'Application-Token': 'any key',
'Device-Token': { devicesToken }
},

  body: JSON.stringify({
    "userId": "681",
    "status": "ONLINE",
    "latitude": "30.710656",
    "longitude":"76.7090749",
    "address": "any address",
    "flag": "1"
  })
})

  .then((response) => response.json())

  .then((responseData) => {
    console.log(responseData)
   
    if (responseData.response.code == 200) {
       ToastAndroid.show('Driver status service hits', ToastAndroid.SHORT);
    } else {
      ToastAndroid.show('Failed', ToastAndroid.SHORT);
    }
  })
  .done();

}

Is there anyway to display dynamic content in the notification?

With the alwaysRunning set to true, I can show a notification when the App goes background. It works well for static notificationTitle and notificationText. In my case (GPS tracking app), I need to display some data from the App in the notification. For an example, Distance traveled: x km

Compiling fails

FAILURE: Build failed with an exception.

  • Where:
    Build file '/home/maximilian/code/chaosdoor/node_modules/react-native-background-job/android/build.gradle' line: 15

  • What went wrong:
    A problem occurred evaluating project ':react-native-background-job'.

No such property: incremental for class: com.android.build.gradle.internal.CompileOptions_Decorated

I went to line 15 and deleted the the option wich led me to the next problem:

Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : uses-sdk:minSdkVersion 16 cannot be smaller than version 21 declared in library [chaosdoor:react-native-background-job:unspecified] /home/maximilian/code/chaosdoor/android/app/build/intermediates/exploded-aar/chaosdoor/react-native-background-job/unspecified/AndroidManifest.xml
Suggestion: use tools:overrideLibrary="com.pilloxa.backgroundjob" to force usage

So I upgraded the minSdkVersion in my android/app/build.gradle to 21.

Now it is compiling

error: cannot find symbol new BackgroundJobPackage()

In the manual installation there is a step :
Add new BackgroundJobPackage() to the list returned by the getPackages() method in MainApplication.java

However when I build on android it gives me the error:
:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
C:\Users...\Desktop\React Native\neck\android\app\src\main\java\com\neck\MainApplication.java:26: error: cannot find symbol
new BackgroundJobPackage()
^
symbol: class BackgroundJobPackage
1 error
:app:compileDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

should I remove the line from MainApplication.java??

Losing handle to jobs after app termination & restart

First, really appreciate this library, it's been great.

One issue I've run into is losing the handle to a job such that duplicate executions can occur. Here's how it happens:

  • I have a alwaysRunning job registered/scheduled. Using v1.2.4.

BackgroundJob.register({
jobKey: 'jobkey',
job: processingFunction
})

BackgroundJob.schedule({
jobKey: 'jobkey',
period: 1000
timeout: 3000,
alwaysRunning: true,
persist: false
})

  • When the app is placed into the background or terminated, the job executes. All good there. When I return from the background, the job execution ceases as expected.

  • However, in the case of a terminated app, if I then restart it (i.e. click on the icon on Android home, re-enter the app, etc), the handle to the previous job execution is lost yet it keeps executing despite the app having returned to an active state.

  • I noticed this because I started seeing API calls at a more frequent rate (issued from my job) due to multiple jobs being executed but all for the same app (just different instances).

  • I attempted to first check via a getAll to ensure no other registered jobs, this returned no entries (even though the job was actually running). I also attempted cancel and cancelAll which also did not find the running job.

Continually runs in background

I found that the headless task that is started by the scheduler continually runs in the background, causing battery drain if you follow the following steps:

  1. Set up a background task according to the documentation
  2. Run your app using react-native run-android
  3. After your app loads, close it by removing it from your 'recent apps' list
  4. Wait for the background task to execute, or force execution of the job

At this point if I shake my phone, the developer menu appears. Only after I open the app, and minimise it do things start to work as normal again. It seems like more than just a headless JS task is starting as it is causing a lot of battery drain on my phone until I open the APP to reschedule the background task.

Have someone else experienced this issue as well?

How to keep Socketio connected

Hi, im trying to keep my socket.io connected even the app is in background , cause i lose socket connection once the app goes background, i don't know if react-native-background-job can help in this ? , thanks in advance.

Call the task dynamically

Hi, i'm working with Firebase, i want to when the database has new data, job will be called, how can i do that?
This is Firebase code:

comments.on('child_added', function(data) {
  addCommentElement(data);
  // job_run(); Job will be callled
});

Thanks.

Should I be able to cancel an alwaysRunning foreground service?

Trying to implement a feature where user can select in UI whether (s)he wants the app to run in BG. Enabling it works but disabling still leaves the notification on and the app running, even though the jobKey is no longer scheduled according to the library.

Error: cannot read property 'jobs' of undefined.

Cannot read property 'jobs' of undefined.

Here is my index.android.js

import { AppRegistry } from 'react-native';
import App from './App';
import Store from './redux/store';
import * as actions from './actions/addressbook'
import BackgroundJob from 'react-native-background-job';

AppRegistry.registerComponent('contactsync', () => App);

// puller =  () => {
//     console.log("RUNNO IN BACKGROUND");
//   Store.dispatch(actions.requestedNewNumber());
// }

const backgroundJob = {
 jobKey: "myJob",
 job: () => console.log("Running in background")
};

BackgroundJob.register(backgroundJob);

var backgroundSchedule = {
 jobKey: "myJob",
 timeout: 2000
}

BackgroundJob.schedule(backgroundSchedule);

My dependencies:

{
  "react-native": "^0.45.1",
    "react-native-background-job": "^1.2.4"
}

Does this work for iOS?

According to the readme only Android is supported but the project also has an iOS Xcode-project. So does it work on both platforms? If so, I think the readme should be updated to reflect support.

Crashing after App is Closed

So basically, i stumbled this on api 25.. i put my register outside the class while the schedule inside componentDidMount. But after closing the app(not existing on background), my app crashes. this is my code:

BackgroundJob.register({
    jobKey: "userNotif",
    job: () => {
        console.log('registered');
    }
});


export default class VeevMobile extends Component {
    componentDidMount() {
        BackgroundJob.schedule({
          jobKey: 'userNotif',
          period: 10000,
          timeout: 10000,
          allowExecutionInForeground: false,
        });
   }
}

I hope you can help me asap thanks ๐Ÿฅ‚

failed to find Build Tools revision 25.0.0

why i must be update my build too revision ?
my project already use with build tools revision 23

i get error like this

Building and installing the app on the device (cd android && ./gradlew installDebug)...
Failed to notify ProjectEvaluationListener.afterEvaluate(), but primary configuration failure takes precedence.
java.lang.IllegalStateException: failed to find Build Tools revision 25.0.0
	at com.android.builder.sdk.DefaultSdkLoader.getTargetInfo(DefaultSdkLoader.java:93)
	at com.android.build.gradle.internal.SdkHandler.initTarget(SdkHandler.java:89)
	at com.android.build.gradle.BasePlugin.ensureTargetSetup(BasePlugin.groovy:507)
	at com.android.build.gradle.BasePlugin.createAndroidTasks(BasePlugin.groovy:455)
	at com.android.build.gradle.BasePlugin$_createTasks_closure13_closure17.doCall(BasePlugin.groovy:415)
	at com.android.build.gradle.BasePlugin$_createTasks_closure13_closure17.doCall(BasePlugin.groovy)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
	at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
	at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:292)
	at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1015)
	at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:39)
	at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
	at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:54)
	at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
	at com.android.build.gradle.internal.profile.SpanRecorders$2.call(SpanRecorders.groovy:52)
	at com.android.builder.profile.ThreadRecorder$1.record(ThreadRecorder.java:48)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMet

thanks :)

All tasks has pauses in execution

When I tried to run you example app on me machine, then I see that all tasks has pauses during execution. And doesn't matter, job in background or not. On screen shot log of react-native example app. There in one of several pauses between 14:50:17.725 and 14:54:53
screen shot 2017-11-09 at 14 58 13

Is it fixable? Thank you

allowExecutionInForeground doesn't work

There is no option to start job in foreground now. Option 'allowExecutionInForeground' doesn't affect anything. And this is reason:
if (appInForeground) { return null; }

I found it in ReactNativeEventStarter.java, and when I commented these lines, all works properly.

Jobs are only executed in foreground

First, thanks to this awesome tool ๐Ÿ‘

When i try this simple code:

index.android.js(outside of a class)

const myJobKey = "Hej";

BackgroundJob.register({
  jobKey: myJobKey,
   job: () => {
     setInterval(()=>{
     Vibration.vibrate(200,false)
     },2000)
   }
});

main.js(within a class)

     <Button title="start" onPress={async () => {
                    const myJobKey = "Hej";
                         BackgroundJob.schedule({
                        jobKey: myJobKey,
                        timeout: 5000
                    });
                }}>

and my app goes into the background or will be terminated, nothing happens. Back in the foreground, my phone vibrate. Same when i try it with console.log instead of Vibration.

    "react": "16.0.0-alpha.6",
    "react-native": "0.44.0",
    "react-native-background-job": "^1.2.3",

Thx

"allowWhileIdle" option needed to run while in Doze

I found out that my background job doesn't run while in doze mode (Android 7.0) if using exact timing mode. I think it could be fixed by adding an option for schedule() to use setExactAndAllowWhileIdle instead of setExact

https://developer.android.com/training/monitoring-device-state/doze-standby.html

Standard AlarmManager alarms (including setExact() and setWindow()) are deferred to the next maintenance window.

  • If you need to set alarms that fire while in Doze, use setAndAllowWhileIdle() or setExactAndAllowWhileIdle().
  • Alarms set with setAlarmClock() continue to fire normally โ€” the system exits Doze shortly before those alarms fire.

Task not fired

I've copied the example project into my app but when i tried to run the background task was never fired.
I got on the console that the task was successfully scheduled but when the app entered background mode, nothing happens.

Got error when in apk-release

hi friend, when in develop its work, but when i compile my project to apk-release i got error like this
16736648_120300002079936928_49178595_n

can you help me friend ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.