jamesisaac / react-native-background-task Goto Github PK
View Code? Open in Web Editor NEWPeriodic background tasks for React Native apps, cross-platform (iOS and Android), which run even when the app is closed.
License: MIT License
Periodic background tasks for React Native apps, cross-platform (iOS and Android), which run even when the app is closed.
License: MIT License
Trying to run your example code.
import BackgroundTask from 'react-native-background-task'
BackgroundTask.register(() => {
console.log('Hello from a background task');
BackgroundTask.finish()
});
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.
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)
})
}
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?
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 :)
componentDidMount() {
console.log("BackgroundTask", BackgroundTask); // this show a object
BackgroundTask.schedule(); // here i got this error
}
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:
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"
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();
})
It's not working on Android 8 and above.
Background start not allowed: service Intent
java.lang.IllegalStateException: Not allowed to start service Intent
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.
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:
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)
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
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
Hi,
I am getting the following warning after reopening the app or reloading it.
registerHeadlessTask called multiple times for same key 'BackgroundTask'
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
on Android and on iOS?
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.
I assumed you could persist and run multiple tasks, but it's seeming more and more like I should use something like react-native-queue to accomplish this within a single define
This is probably because I'm using expokit, but there is no onCreate function in MainApplication.java. Ideas?
Breaking change in RN 0.47 (facebook/react-native@ce6fb33) causes Android compilation to fail.
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){
}
;
})
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!
My Platform is Android.
The task gets executed when the app is in background, but when i forcefully kill the app that is the app is now neither in background nor in foreground then the task doesn't gets executed.
Please help
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.
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
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
What are the limitations of this react-native-background-fetch?
What are the advantages of this package?
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}
`
Waited about 30 mins and the task defined only had a console.log and it did not fire. Tested on a physical device.
It would be useful to get Windows (https://github.com/Microsoft/react-native-windows) support for this library.
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:
background task does not work. Help me please, what i can do with that ?
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?
I need to check the status of the wifi, that is if it is connected to a specific wifi.
Could this library fit my case? works well?
Thanks
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.
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
Hello, I just started experimenting with this android background tasks, but i was not able to run even simple example.
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.
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
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?
Specifically, Is their a way to do cleanup before the Task is terminated ?
Uses JobScheduler which is only available from Android 5.0. Would be nice to come up with a more backwards-compatible solution.
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?
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?
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 :)
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.
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?
I have submitted a question on stackowerflow.
Could there be a bug in the this library? Because when I run the react-natove-background-fetch example app it works.
error: package com.jamesisaac.rnbackgroundtask does not exist
what does that mean? how can i fix it?
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()
});
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.