Giter Club home page Giter Club logo

react-native-sync-adapter's Introduction

react-native-sync-adapter

Circle CI npm version

Intelligent Job-Scheduling port to React Native: Scheduling data background synchronizations that run in your JavaScript.

Read a broader introduction in the following post: React Native and Native Modules: The Android SyncAdapter

Requirements

  • React Native 0.60+

Pros

Under the hood, this library uses a SyncAdapter:

  • Android will trigger a sync using our syncFlexTime to decide when is the best moment to do so (battery efficiency)
  • No need to worry about internet connection
  • No need to worry about the user restarting the device
  • Compatible with all Android versions supported by RN (4.1+)

Caveats

This library is only for Android. If you want to do something similar on iOS, I recommend using react-native-background-fetch.

Getting started

yarn add react-native-sync-adapter

Installation

The library will be linked automatically by Autolinking. However, this library requires some manual steps:

Manual Android required step

Open up the string.xml file of your Android project. You need to add the following (just change the content):

<string name="app_name">YourAppName</string>
<string name="rnsb_sync_account_type" translatable="false">your.android.package.name</string>
<string name="rnsb_content_authority" translatable="false">your.android.package.name.provider</string>

This will override the default values from the library and make them unique for your app.

Usage

You need to register a task with a specific name and only with this specific name: TASK_SYNC_ADAPTER. You should do it in the same place where you register your app:

AppRegistry.registerComponent('MyApp', () => MyApp);
AppRegistry.registerHeadlessTask('TASK_SYNC_ADAPTER', () => TestTask);

Then, for example, on your root component:

import {useEffect} from 'react';
import SyncAdapter from 'react-native-sync-adapter';

useEffect(() => {
  SyncAdapter.init({
    syncInterval,
    syncFlexTime,
  });
}, []);

That is all! Some extras:

Timeout

The default timeout for your Headless JS task is 5 minutes (300000ms). If you want to override this value, you will also need to override strings.xml again:

<!-- Overrides default timeout to 10 minutes -->
<string name="rnsb_default_timeout" translatable="false">600000</string>

User visible

By default the user will not be able to manually enable/disable syncs through the Account settings. If you want the user to have this option, you need to override strings.xml:

<!-- Allows the user to enable/disable the sync functionality through the Account settings -->
<string name="rnsb_user_visible" translatable="false">true</string>

Running the task while the app is in the foreground

By default, the sync task will only run if the app is not in the foreground. This is one of the default caveats from HeadlessJS. If you want to override this behavior, you can, one more time overriding strings.xml:

<string name="rnsb_allow_foreground">true</string>

Broadcast Receiver

If you want to trigger a sync natively (e.g. responding to a broadcast receiver), you can call:

SyncAdapter.syncImmediately(Context context, int syncInterval, int syncFlexTime);

API

init

Schedules background syncs within your app.

Object: {
  syncInterval: number;
  syncFlexTime: number;
}
  • syncInterval: The amount of time in seconds that you wish to elapse between periodic syncs
  • syncFlexTime: The amount of flex time in seconds before syncInterval that you permit for the sync to take place. Must be less than syncInterval

A good example could be syncInterval: 12 * 60 * 60 (12 hours) and syncFlexTime: 0.5 * 60 * 60 (30 minutes).

Notice that syncFlexTime only works for Android 4.4+, for older versions, that value will be ignored and syncs will be always exact.

syncImmediately

Invoke the sync task. Use the same values as in the init call.

Object: {
  syncInterval: number;
  syncFlexTime: number;
}

Be aware that for this method to work (if you call it from inside your app) you need to allow the task to work on the foreground.

Running example

You can try this library running the example app:

cd example && yarn && npm start

Then just run:

yarn android

Be careful: The installed example app will trigger a sync around every minute (so it is easy to see that is working). If you debug the app, you should be able to see the HeadlessJS ouputing: Headless JS task was fired! (remember not to have the app on the foreground: Unless you override this behavior). After you try it, I recommend to uninstall the app so you don't harm your device battery life.

react-native-sync-adapter's People

Contributors

ferrannp avatar nvlbg 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

react-native-sync-adapter's Issues

Example not working

The given example is not logging anything ( or outputting"Headless JS task was fired!") at the chrome debug or "adb logcat" console, though the app is not running in the foreground (app closed). Could you please check this or if there is anything which I missed, let me know. Thanks.

Device : Moto E 1st Gen
OS: Android 5.1

PS: Wanted to use rn-sync-adapter to check location of the device every 3 mins in a production app

App not working

Capturar

I tried everything, I did everything right, but I can't do the job.

App stops working if its in background

Im trying to integrate this in my RN project, every-time app goes background, the app crashes.

Logcat error output
Process: app.my.com, PID: 16407
java.lang.RuntimeException: Unable to start service com.fnp.reactnativesyncadapter.HeadlessService@89518c2 with Intent { cmp=app.my.com/com.fnp.reactnativesyncadapter.HeadlessService }: java.lang.ClassCastException: host.exp.exponent.MainApplication cannot be cast to com.facebook.react.ReactApplication
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3027)
at android.app.ActivityThread.-wrap17(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1442)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.ClassCastException: host.exp.exponent.MainApplication cannot be cast to com.facebook.react.ReactApplication
at com.facebook.react.HeadlessJsTaskService.getReactNativeHost(HeadlessJsTaskService.java:171)
at com.facebook.react.HeadlessJsTaskService.startTask(HeadlessJsTaskService.java:100)
at com.facebook.react.HeadlessJsTaskService.onStartCommand(HeadlessJsTaskService.java:52)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3010)
at android.app.ActivityThread.-wrap17(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1442) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417)

node_modules\react-native-sync-adapter\android\src\main\res\xml\authenticator.xml:2: AAPT: error: resource mipmap/ic_launcher (aka com.fnp.reactnativesyncadapter:mipmap/ic_launcher) not found

Environment

React native : 0.64.1

Description

When i tried to run the release apk build I am getting below error :
node_modules\react-native-sync-adapter\android\src\main\res\xml\authenticator.xml:2: AAPT: error: resource mipmap/ic_launcher (aka com.fnp.reactnativesyncadapter:mipmap/ic_launcher) not found

But this is not coming in case of debug apk.

Reproducible Demo

Expected to run on UI thread

Facing the error Expected to run on UI thread. When the task is running.

"react-native-sync-adapter": "^2.0.0",

Dependencies:
"react": "16.0.0-alpha.12",
"react-native": "0.48.1",

screen shot 2017-12-13 at 5 24 32 pm

Sometimes I am getting the error as Object is not a function (evaluating 'taskProvider()(data)')

Please help, I am struggling from past 2 days.
screen shot 2017-12-13 at 5 15 51 pm

Can't change sync period

When I change syncInterval value and recompile the effective sync period is still 1 min.
I reproduce with the provided example project.

How to stop the headless task?

I have successfully implemented the react-native-sync-adapter and is working fine for the foreground and background sync. But the main issue is, I want to stop the sync interval task after single sync. I want to sync the data only once when user taps on the sync button in the application. Can anyone help me how to achieve that?

I am registering the task like:

const TASK_ID = 'TASK_SYNC_ADAPTER';

AppRegistry.registerComponent(appName, () => SyncAdapterExample);
AppRegistry.registerCancellableHeadlessTask(
    TASK_ID,
    () => TestTask,
    () => {},
);

And canceling the task after my operation has been completed in TestTask.js file like:

const TASK_ID = 'TASK_SYNC_ADAPTER';
AppRegistry.cancelHeadlessTask(TASK_ID, TASK_ID);

But I am getting an error while canceling the task:

TypeError: taskCancelProvider() is not a function. (In 'taskCancelProvider()()', 'taskCancelProvider()' is undefined)

Better example

Send notifications when task is fired instead of making use of console.log.

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.