GithubHelp home page GithubHelp logo

jamesisaac / react-native-background-task Goto Github PK

View Code? Open in Web Editor NEW
1.1K 12.0 113.0 38 KB

Periodic background tasks for React Native apps, cross-platform (iOS and Android), which run even when the app is closed.

License: MIT License

JavaScript 25.05% Java 74.95%
react-native background-jobs fetch android ios offline sync

react-native-background-task's People

Contributors

jamesisaac 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

react-native-background-task's Issues

BackgroundJob.schedule got 8 arguments, expected 11

Trying to run your example code.

import BackgroundTask from 'react-native-background-task'

BackgroundTask.register(() => {
    console.log('Hello from a background task');
    BackgroundTask.finish()
});

screenshot_20170605-155815

register: function(task, {
    period = 9000, // 15 minutes
    timeout = 30,
  } = {}) {
    // Cancel any existing tasks, as we can only have one to match iOS, and we
    // have no way to tell whether the function has changed or not.
    RNBackgroundJob.cancelAll()

    // Register the headless task
    const fn = async () => { task() }
    AppRegistry.registerHeadlessTask(JOB_KEY, () => fn)

    // Schedule it to run as a periodic task
    AppState.getCurrentAppState(
      ({ appState }) => {
        RNBackgroundJob.schedule(
          JOB_KEY,
          timeout,
          period,
          true, // persist after restart
          appState === 'active',
          RNBackgroundJob.ANY, // network type
          false, // requires charging
          false, // requires device idle
        )
      },
      () => { console.error(`Can't get AppState`) }
    )
  },

Error seems to be correct. You are only giving 8 params.

no timers in background task

I think this info should be in the documentation
if you define task with a setTimeont - callback will be called only after app comeback to foreground mode


export const define = function (dispatch) {
  BackgroundTask.define(() => {
    dispatch(devicesDetailsActions.startUpdatingCycleBackground())
    setTimeout(() => {
      console.log('BackgroundTask timeout') // <===THIS WILL BE RUN IN FOREGROUND
    }, 3000)
  })
}

[Android] fatalTried to start task BackgroundTask while in foreground, but this is not allowed

I can not understand this error. My configuration is that below:

import React, { Component } from 'react';
import BackgroundTask from 'react-native-background-task';

// Async requests
const financialUpdate = async () => {};
const salesUpdate = async () => {};

BackgroundTask.define(async () => {
  console.log('=> Running background tasks...');
  await Promise.all([
    financialUpdate(),
    salesUpdate()
  ]);

  BackgroundTask.finish();
  console.log('=> Finish!');
});

export default class Home extends Component {
  componentDidMount() {
    this.enableBackgroundFetch();
  }

  async enableBackgroundFetch() {
    console.log('Enabling background fetch...');
    const status = await BackgroundTask.statusAsync();

    if (status.available) {
      console.log('Enabled!');
      BackgroundTask.schedule({
        period: 1800
      });
    }
  }
}

I supressed non relevant imports and methods.
What I'm doing wrong?

Manually linking is missing from docs :(

I have some problem in automatic linking, it will greate this feature to add how to link this library manually to react native project. Almost every library has its guide to link packages manually.

Thanks in advance :)

No task registered for key BackgroundTask

Hello. This is android related issue. I experienced this behavior after starting up the emulator when the app was installed on it before. I saw in the logs that the Job is starting. After a minute or tho I get the following crash:
App crash

Also some of the engineers reported with release builds that they got few times the crash dialog "App stopped working" while using the phone.
We are defining the task inside root component (the one you register in AppRegistry) in componentDidMount() function.

"react": "16.0.0",
"react-native": "0.49.3",
"react-native-background-fetch": "2.2.1",
"react-native-background-task": "0.2.1"

Alert or Toast does not work in background task

The background task is running but not displaying the alert or toast notifications

BackgroundTask.define(async () => {
ToastAndroid.show('Task started !', ToastAndroid.SHORT);
Alert.alert('Restricted', 'Hello from background task');
console.log("running background task");

console.log("completed background task --- "+new Date());

ToastAndroid.show('Task completed!', ToastAndroid.SHORT);

BackgroundTask.finish();

})

Not allowed to start service Intent

It's not working on Android 8 and above.
Background start not allowed: service Intent
java.lang.IllegalStateException: Not allowed to start service Intent

Proposal of channel discussion

Hi, I took the liberty of creating a public chat in the discord facing React-Native. With the intention of uniting the React-native community and improving communication.

I'm creating a channel for public discussions about your project. To avoid flooding "chat" on your github. If you can support the initiative, great! Just share the link below xD

I'm adding RN only projects to this public chat service. And I commit myself to manage chat rooms.
You would just need to observe the chat related to your project.

here's the link
https://discord.gg/RvFM97v

Cheers.

Task defined did not run in IOS

I used the Simple example provided in your readme and I can't see the msg logged in the Chrome React Native Debugger. Not sure what I missed.

Packages Versions:

  • Xcode: 8.2.1
  • NPM: 3.10.10
    "react": "16.0.0-alpha.12",
    "react-native": "0.45.1",
    "react-native-background-fetch": "^2.0.8",
    "react-native-background-task": "^0.2.0"

Not working on Android

I am using this library for background work but not working....
This part seams no response ...(no error but not working )

BackgroundTask.define(async () => {
// Fetch some data over the network which we want the user to have an up-to-
// date copy of, even if they have no network when using the app
const response = await fetch('http://feeds.bbci.co.uk/news/rss.xml')
const text = await response.text()

// Data persisted to AsyncStorage can later be accessed by the foreground app
await AsyncStorage.setItem('@myapp:key', text)

unable to link the project on window react native project

Hi I am trying to link the plugin but it keeps failing and giving me this error.
I have installed these versions of the plugns
"react-native-background-fetch": "^2.0.8",
"react-native-background-task": "^0.2.0",

react-native link react-native-background-task
Scanning 739 folders for symlinks in abcd\node_modules (52ms)
rnpm-install info Linking react-native-background-task android dependency
rnpm-install info Android module react-native-background-task has been successfully linked
rnpm-install info Linking assets to ios project
rnpm-install ERR! Something went wrong while linking. Error: Expected "/* Begin ", "/* End ", """, or [A-Za-z0-9_.] but "<" found.
Please file an issue here: https://github.com/facebook/react-native/issues

Expected "/* Begin ", "/* End ", """, or [A-Za-z0-9_.] but "<" found.

This is my system configuraton.
System
platform win32
arch x64
cpu 4 cores Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz
directory abcd

JavaScript
node 7.10.0
npm 4.2.0
yarn 0.23.4

React Native
react-native-cli 2.0.1
app rn version 0.44.0

Also i am getting these errors when i build the code after wrapping up the linking

abcd\android\app\src\main\java\com\tocdocdoctor\MainActivity.java:5: error: package com.jamesisaac.rnbackgroundtask does not exist
import com.jamesisaac.rnbackgroundtask.BackgroundTaskPackage;
^
abdc\android\app\src\main\java\com\tocdocdoctor\MainApplication.java:6: error: package com.jamesisaac.rnbackgroundtask does not exist
import com.jamesisaac.rnbackgroundtask.BackgroundTaskPackage;
^
abcd\android\app\src\main\java\com\tocdocdoctor\MainActivity.java:20: error: cannot find symbol
BackgroundTaskPackage.useContext(this);
^
symbol: variable BackgroundTaskPackage
location: class MainActivity
abcd\android\app\src\main\java\com\tocdocdoctor\MainApplication.java:40: error: cannot find symbol
new BackgroundTaskPackage(),
^
symbol: class BackgroundTaskPackage
4 errors
:app:compileDebugJavaWithJavac FAILED

Can you suggest a method to sort this issue out?

regards
Abhishek

Cannot read property 'schedule' of undefined

i followed Your README documentation but i am getting this error.
colud you help me to solve this.

Version
Dependency Version : "react-native-background-task": "^0.2.1"
version of RN is: 0.50.3
react-native-cli: 2.0.1
My Device : windows-7, 64-bit , 8GB RAM

Undefined symbols for architecture arm64: "_OBJC_CLASS_$_TSBackgroundFetch", referenced from: objc-class-ref in libRNBackgroundFetch.a(RNBackgroundFetch.o)

When building the app on iOS device, build always fails with this error.

Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_TSBackgroundFetch", referenced from:
      objc-class-ref in libRNBackgroundFetch.a(RNBackgroundFetch.o)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

[email protected] is installed and successfully linked, but the build always fails

Android: default timeout is set to 30ms instead of 30s

As per Headless JS documentation, timeout should be provided as a number of miliseconds.

In default configuration, this library sets 30 as timeout parameter, which means 30ms.

Relevant source code lines: index.android.js and RNJob.java.

This typo is very difficult to notice, as it's only visible in logcat:
01-31 16:22:07.293 9869-9869/com.my.app D/BackgroundTask: Returning HeadlessJsTaskConfig, timeout=30 ms

This could be overriden by timeout property in schedule method (setting that to 30000). I'm not sure it this wouldn't break iOS implementation though.

Expected to run on UI thread!

Expected to run on UI thread!
I got that error.

My code

BackgroundTask.define(async () => { 
              try{ 
                  navigator.geolocation.getCurrentPosition(
                    async (position)=>{                       
                        fetch(publicUrl+'/posisi_members',{
                          method:'post',
                          credentials:'include',
                          headers:{
                             'Accept': 'application/json',
                             'Content-Type': 'application/json',
                          },
                          body:JSON.stringify({
                            latitude:position.coords.latitude,
                            longitude:position.coords.longitude,
                            test:true,
                          }), 
                        }).then(response=>{}).catch(error=>{});

                    },(error)=>{},{enableHighAccuracy: false, timeout: 20000, maximumAge: 100000});

              } catch (error){

              }    
            ;
})

No effect on Android

I'm a green hand.
I paste the code into my program.And have already executed "react-native link react-native-background-task" successfully,but the function is not realized!

Run task when in foreground and keep running when in background

Hi, I'm not sure if this is the best place to ask this, because it's not properly an issue, but as the title suggests I need to know: does this module allow me to launch the task immediately and if the app goes to background continue the execution?
Thank you so much and please tell me if I wasn't clear.

Native module cannot be null

When I import:

import BackgroundTask from 'react-native-background-task';

I get:

Native module cannot be null.

NativeEventEmitter
    NativeEventEmitter.js:31:16
<unknown>
    index.ios.js:3:44
loadModuleImplementation
    require.js:174:12
<unknown>
    index.ios.js:3
loadModuleImplementation
    require.js:174:12
<unknown>
    index.js:6
loadModuleImplementation
    require.js:174:12
<unknown>
    App.js:25
loadModuleImplementation
    require.js:174:12
<unknown>
    AppEntry.js:2
loadModuleImplementation
    require.js:174:12
guardedLoadModule
    require.js:119:45
global code
    <unknown file>:0

Background task works but always opens the app even when i am using other apps

I have everything all set up and working.
but the app opens up when the task starts in the background which means if i am using another app i would be interrupted by the background task and the app opens up.

is there a way to start the task without the app opening up and interrupting whatever app i may be using at the time.

Thanks

The task written under register() method never gets called

Somehow the task written under the register() method never gets called !
Below is my code, please let me know what i'm doing wrong.

` <TouchableNativeFeedback
onPress={() => {
//this.interval = setInterval(this.tick(), 1000);

            BackgroundTask.register(() => {
              console.log('Hello from a background task')
              BackgroundTask.finish()
            },{
              period : 1
            })

this.setState({
timerStarted : true
})
}
}
background={TouchableNativeFeedback.SelectableBackground()}>

{!this.state.timerStarted && <Text style={[styles.buttonContainer,{borderColor: '#DA9F0C'}]}>Start}


`

iOS task did not run at all.

Waited about 30 mins and the task defined only had a console.log and it did not fire. Tested on a physical device.

Problem in background task with minimize-maximize app

Hello. I found problem in your module. I have app, when i minimize it or close it on android all works fine. But when i have these steps:

  • open app
  • minimize
  • maximize
  • minimize

background task does not work. Help me please, what i can do with that ?

Tasks that occur every 30 seconds

Hi @jamesisaac
I'm working with background geolocation and need it to run a check every 30 seconds to check if the user is in a certain location and send a push. I set the "priod" to 60, but nothing happens when the app goes to background.

Is it possible to work this way with your library?

Not working on Android 8.0

First of all, thanks for sharing this amazing package. I have been running this package successfully on Android 7.0 for months now. Then I tested it on two different Android 8.0 devices (Pixel & Xperia) and the background tasks don't execute. Here's what the logcat looks like:

04-24 20:56:14.959 1470 1470 D BackgroundTask: Setting foreground true
04-24 20:56:17.880 1470 1470 D BackgroundTask: Setting foreground false
04-24 20:56:17.881 1470 1470 D BackgroundTask: Committing job schedule
04-24 20:56:20.001 1470 1470 D ReactNative: ReactInstanceManager.detachViewFromInstance()
04-24 21:04:09.176 2563 2592 D BackgroundTask: Job is running

It does not move on from this point. I've tested it many times for up to several days in length.

react-native-background-task is not working in background or foreground not in ios or android

hello author,
we have been trying to using react-native-background-task as our native module in our app.
so i started coding like this

import React, { Component } from 'react';
import { StyleSheet, Text, View} from 'react-native';
import BackgroundTask from 'react-native-background-task'
BackgroundTask.define(async () => {
       console.log('welcime to react native background task');
  BackgroundTask.finish()
})
type Props = {};
export default class App extends Component<Props> {
  constructor(props) {
    super(props);
  }

  state ={
    toggle:false,
  }

  componentDidMount() {
      this.getLocation();
  }
startBackgroundTask(){
  this.setState({toggle:!this.state.toggle},()=>{
      if (this.state.toggle) {
        BackgroundTask.schedule()
      }
    })
  }
}
  render() {
    return (
 <View style={styles.container}>
        <Text style={styles.welcome}>
           Start Your Back Ground Task
        </Text>
        <Switch value={this.state.toggle} disabled={false} onValueChange={this.startBackgroundTask.bind(this)}/>
   
      </View>
    );
  }
}

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

it is not logging out in background or foreground

Undefined is not an object

Hello, I just started experimenting with this android background tasks, but i was not able to run even simple example.

screenshot_20180406-151055

I have started with create-react-native-app, ejected from expo, added react-native-background-task, linked, updated MainApplication.java and tried to implement Simple example from this project's readme. After running the app, i got this error. I want this to run just on android, so i did not install react-native-background-fetch.

My package versions:
"react": "16.3.0-alpha.1",
"react-native": "0.54.0",
"react-native-background-task": "^0.2.1",
"react-navigation": "^1.5.11"

Any clue about how to fix this? Thanks.

Unable to resolve module in typescript

I am unable to resolve 'react-native'background-task' module in TypeScript. It is not able to find this module and shows error on typescript compilation

TIA

clang: error: no such file or directory: '/Users/harshagoli/Projects/Hail-react-native/ios/node_modules/react-native-background-fetch/ios/RNBackgroundFetch/RNBackgroundFetch+AppDelegate.m' clang: error: no input files

Hey guys,

Set up react-native-background-task and following all the instructions but running into some weird errors for iOS with Xcode 9

clang: error: no such file or directory: '/Users/harshagoli/Projects/Hail-react-native/ios/node_modules/react-native-background-fetch/ios/RNBackgroundFetch/RNBackgroundFetch+AppDelegate.m'
clang: error: no input files

Any thoughts on how to fix this?

How can I call a function inside background task?

Hi all! I'm new in React Native and I'm working on building a forecast application. Right now, I can fetch some data from a forecast API when the app is in background. It works fine. On the other hand, I'm also using react-native-push-notification in the app. All I want to do is to create a local notification whenever a new data fetched in the background and set the notficiation's message property as the fetched data. To do this, I'm calling PushNotification.configure and PushNotification.localNotification functions inside BackgroundTask.define but it's not working. I need to make a connection between these two but I have no idea how to do.

Can anybody help me or give me some advices?

Why schedule tasks rather than emit for timeout?

Just curious: How come tasks are scheduled on top of Headless JS (and Background Fetch for iOS) rather than emit and listen for events (using RCTDeviceEventEmitter and NativeEventEmitter)? Wouldn't this require no additional dependency and bypass Android scheduling restrictions as well?

App crash in background

Hello,

I'm using the module and after some times, I got an error MyApp don't respond.
Do you have an idea about how to track/handle this ? Is this a JavaScript issue in my code ?

Thanks :)

Single periodic task?

Sorry, this is probably a stupid question but I want to clear this up before I get too involved with this module. The readme says "This library allows the scheduling of a single periodic task" so I am a little confused if I can do multiple "tasks". For example, say I want to make 3 web services calls (with different intervals) and do something with the responses.

Proguard warning

I couldn't build with release mode (./gradlew assembleRelease) due to proguard warning:

Warning: com.evernote.android.job.v24.JobProxy24: can't find referenced method 'android.app.job.JobInfo ...
...
Warning: there were 2 unresolved references to library class members.
         You probably need to update the library versions.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedlibraryclassmember)
Warning: Exception while processing task java.io.IOException: Please correct the above warnings first.

Solved it by adding: -dontwarn com.evernote.android.job.** to proguard rules.
Actual fix might be upgrading dependency to latest evernote android job library?

cannot build project

error: package com.jamesisaac.rnbackgroundtask does not exist
what does that mean? how can i fix it?

Always crashes app when job starts

I am defining my background task so that it is not doing anything, simply running, and then finishing. The task schedules just fine, and adb says the job is running, however my app immediately crashes ('Appname' has stopped). I double checked based off of the other issues and the manual configuration is correct. I am running an Expokit project, where the only linked libraries are react-native-background-task and realm (for react-native-queue). I haven't been able to get any actual error information (adb doesn't show any errors, and I can't run the Android debugger at the same time as expo). Any ideas on what the issue might be?

Using Galaxy S8+ running 7.0.0 (same issue on GS4 running 5.0.1)

Example adb logs

02-27 09:55:33.844 28582 28582 D BackgroundTask: Setting foreground false
02-27 09:55:33.844 28582 28582 D BackgroundTask: Committing job schedule
02-27 10:04:00.142 28582 29554 D BackgroundTask: Job is running
02-27 10:04:00.166 28582 28582 D BackgroundTask: Returning HeadlessJsTaskConfig, timeout=30 ms
02-27 10:04:33.210 29702 29805 D BackgroundTask: Job is running
02-27 10:04:33.268 29702 29702 D BackgroundTask: Returning HeadlessJsTaskConfig, timeout=30 ms
02-27 10:06:12.750 29966 30016 D BackgroundTask: Job is running
02-27 10:06:12.832 29966 29966 D BackgroundTask: Returning HeadlessJsTaskConfig, timeout=30 ms
02-27 10:08:33.252 30304 30352 D BackgroundTask: Job is running
02-27 10:08:33.339 30304 30304 D BackgroundTask: Returning HeadlessJsTaskConfig, timeout=30 ms
02-27 10:08:46.141 30363 30363 D BackgroundTask: Returning HeadlessJsTaskConfig, timeout=30 ms

Defining Background task in root App.js outside of component as

BackgroundTask.define(() => {
    //tried adding console.log("words") but it doesn't seem to get that far
    BackgroundTask.finish()
});

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.