Giter Site home page Giter Site logo

Comments (18)

ocetnik avatar ocetnik commented on September 23, 2024

Hi @Rewieer, thank you for your observation.

@ericacooksey fixed it in #17 but on my devices everything worked well also with previous version (0.1.3).

I just released 0.1.4-beta so please try npm i react-native-background-timer@beta --save and let me know if it works properly when phone is locked.

Many thanks.

from react-native-background-timer.

ancyrweb avatar ancyrweb commented on September 23, 2024

I'm sorry, I cannot try your solution for now as I've finally implemented my own background-timer system. If you want to know, I'm using a wakelock that is acquired when the module is loaded (i'm using intervals).

I want to point that using sony phones, when stamina mode is on (or what the setting to disallow applications to fetch datas while in sleep mode) disable using a background timer. I've been tricked for the whole week-end on this. You should maybe talk about it in the README to avoid further problems on these phones.

from react-native-background-timer.

MaximilianKindshofer avatar MaximilianKindshofer commented on September 23, 2024

When the phone is locked and the screen is off the events don't fire. I am using 0.1.4 (beta) as suggested.

from react-native-background-timer.

ancyrweb avatar ancyrweb commented on September 23, 2024

@MaximilianKindshofer do you want me to share the solution ? It requires a bit of knowledge in Java to implement through

from react-native-background-timer.

MaximilianKindshofer avatar MaximilianKindshofer commented on September 23, 2024

This would be great!
I am not so skilled at Java - but I am sure I can dive into it

from react-native-background-timer.

ancyrweb avatar ancyrweb commented on September 23, 2024

It's pretty minimal for my purpose.
The module looks like this :

import android.os.Handler;
import android.os.PowerManager;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import static android.content.Context.POWER_SERVICE;

public class BackgroundTimerModule extends ReactContextBaseJavaModule {
  private PowerManager powerManager;
  private PowerManager.WakeLock wakeLock;

  public BackgroundTimerModule(ReactApplicationContext reactContext){
    super(reactContext);

    this.powerManager = (PowerManager) getReactApplicationContext().getSystemService(POWER_SERVICE);
    this.wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "rewieer_bg_wakelock");
    this.wakeLock.acquire();
  }

  @Override
  public String getName() {
    return "RewieerBackgroundTimerModule";
  }

  @ReactMethod
  public void setTimeout(final int id, final int timeout){
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        if(getReactApplicationContext().hasActiveCatalystInstance()){
          getReactApplicationContext()
              .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
              .emit("rewieer.backgroundTimer.timeout", id);
        }
      }
    }, timeout);

  }
}

It basically acquire a partial wakelock permanently to ensure CPU is not sleeping.
Then in JS :

import { NativeModules, DeviceEventEmitter } from 'react-native';

const NativeEVOBackgroundTimer = NativeModules.RewieerBackgroundTimerModule;

const listeners = {};
let uniqueId = 0;

const nextId = () => uniqueId++;

const RewieerBackgroundTimer = {
  setInterval(callback, delay){

    let id = nextId();
    listeners[id] = {
      isInterval: true,
      callback,
      timeout: delay,
    };

    NativeEVOBackgroundTimer.setTimeout(id, delay);
    return id;
  },
  clearInterval(id){
    listeners[id] && delete listeners[id];
  }
};

DeviceEventEmitter.addListener("rewieer.backgroundTimer.timeout", (id) => {
  const listener = listeners[id];
  if(!listener){
    return;
  }

  listener.callback();
  if(listener.isInterval){
    NativeEVOBackgroundTimer.setTimeout(id, listener.timeout);
    return;
  }

  delete listeners[id];
});

export default RewieerBackgroundTimer;

The interface is the same as RNBT but it doesn't provide any setTimeout function, because I don't need it. You can implement it easily through, just copy the code of RNBT.
If you have no idea on how to implement this head to the react native doc.

Don't forget to add <uses-permission android:name="android.permission.WAKE_LOCK" /> to your manifest.

This solution can certainly be discussed and improved, as it drains the battery life when used heavily.

from react-native-background-timer.

MaximilianKindshofer avatar MaximilianKindshofer commented on September 23, 2024

Yes I can see that this will be really battery heavy - meanwhile I found:
https://github.com/vikeri/react-native-background-job
Utilizing the https://developer.android.com/reference/android/app/job/JobScheduler.html

But this wont work in foreground

from react-native-background-timer.

ancyrweb avatar ancyrweb commented on September 23, 2024

You might actually implement an interface and switch given the context.
For my project I have a BaseComponent React Element. If the app is in background, it renders BackgroundComponent. If the app is in foreground, it renders ForegroundComponent. Each use different kind of periodic methods.

from react-native-background-timer.

ancyrweb avatar ancyrweb commented on September 23, 2024

For my work I need to do repetitive task every 30 seconds. I've looked at JobSchedulers but it's more like a way to synchronize your application. I don't think your setInterval method has an interval of 15 minutes :p

from react-native-background-timer.

irekrog avatar irekrog commented on September 23, 2024

@ocetnik Is a chance to resolve this problem?
I have noticed when app is running by react-native run-android a timer still working even when phone is locked. But when app has been installed by .apk file then timer is stopped after 30-40 seconds (when phone is locked).

from react-native-background-timer.

ancyrweb avatar ancyrweb commented on September 23, 2024

@irekrog there might be many causes to this and I must admit i'm as well struggling with such problems.
If the timer stop workings when phone is locked, it's a Wakelock problem.

from react-native-background-timer.

qingtian5266 avatar qingtian5266 commented on September 23, 2024

rn can't run task on background, it can be killed when CPU dormancy, I use Android native run background task and emit event to rn listener .....
https://facebook.github.io/react-native/docs/native-modules-android.html

from react-native-background-timer.

ancyrweb avatar ancyrweb commented on September 23, 2024

Well RN is perfectly capable of doing this with a bit of native code, at least under android. That's what HeadlessJS do. A wakelock is sufficient to keep the CPU awake for background tasks, but it's resource consuming.
If it's about fetching notification like every hour or so, AlarmManager fits perfectly.

from react-native-background-timer.

sindhu732 avatar sindhu732 commented on September 23, 2024

Issue still present on Android. Is there a solution?

from react-native-background-timer.

rohitshampur avatar rohitshampur commented on September 23, 2024

hey @sindhu732 i have added the solution given by @Rewieer , check this Link

from react-native-background-timer.

GhayoorUlHaq avatar GhayoorUlHaq commented on September 23, 2024

It's pretty minimal for my purpose.
The module looks like this :

import android.os.Handler;
import android.os.PowerManager;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import static android.content.Context.POWER_SERVICE;

public class BackgroundTimerModule extends ReactContextBaseJavaModule {
  private PowerManager powerManager;
  private PowerManager.WakeLock wakeLock;

  public BackgroundTimerModule(ReactApplicationContext reactContext){
    super(reactContext);

    this.powerManager = (PowerManager) getReactApplicationContext().getSystemService(POWER_SERVICE);
    this.wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "rewieer_bg_wakelock");
    this.wakeLock.acquire();
  }

  @Override
  public String getName() {
    return "RewieerBackgroundTimerModule";
  }

  @ReactMethod
  public void setTimeout(final int id, final int timeout){
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        if(getReactApplicationContext().hasActiveCatalystInstance()){
          getReactApplicationContext()
              .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
              .emit("rewieer.backgroundTimer.timeout", id);
        }
      }
    }, timeout);

  }
}

It basically acquire a partial wakelock permanently to ensure CPU is not sleeping.
Then in JS :

import { NativeModules, DeviceEventEmitter } from 'react-native';

const NativeEVOBackgroundTimer = NativeModules.RewieerBackgroundTimerModule;

const listeners = {};
let uniqueId = 0;

const nextId = () => uniqueId++;

const RewieerBackgroundTimer = {
  setInterval(callback, delay){

    let id = nextId();
    listeners[id] = {
      isInterval: true,
      callback,
      timeout: delay,
    };

    NativeEVOBackgroundTimer.setTimeout(id, delay);
    return id;
  },
  clearInterval(id){
    listeners[id] && delete listeners[id];
  }
};

DeviceEventEmitter.addListener("rewieer.backgroundTimer.timeout", (id) => {
  const listener = listeners[id];
  if(!listener){
    return;
  }

  listener.callback();
  if(listener.isInterval){
    NativeEVOBackgroundTimer.setTimeout(id, listener.timeout);
    return;
  }

  delete listeners[id];
});

export default RewieerBackgroundTimer;

The interface is the same as RNBT but it doesn't provide any setTimeout function, because I don't need it. You can implement it easily through, just copy the code of RNBT.
If you have no idea on how to implement this head to the react native doc.

Don't forget to add <uses-permission android:name="android.permission.WAKE_LOCK" /> to your manifest.

This solution can certainly be discussed and improved, as it drains the battery life when used heavily.

As you wrote setTimeOut, how can I implement SetTimeInterval in same way?

from react-native-background-timer.

ancyrweb avatar ancyrweb commented on September 23, 2024

@GhayoorUlHaq just call setTimeout again once the function times out.

from react-native-background-timer.

GhayoorUlHaq avatar GhayoorUlHaq commented on September 23, 2024

@rewieer actually I have to execute a some lines of code after specific time period that will be defined by user and those lines should execute periodically even app is in background and phone is locked unless user stop that.

from react-native-background-timer.

Related Issues (20)

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.