React-Native Android上的后台服务

61

有没有办法在react-native上创建一个后台服务,在Android上实现?我需要一个定时器,每小时唤醒一次并启动一个简单的JavaScript任务。


你找到任何解决方案了吗? - Sriraman
我也想知道:你找到任何解决方案了吗? - Terry Sahaidak
4
不过我有一个解决方法。我使用Java创建了后台服务,然后通过reactContext.getJSModule(...).emit('javascript_event_name', params)调用了一些JavaScript代码。遗憾的是,React Native API中没有直接提供服务。 - andri
@andri 但是如果主要的React应用程序已经关闭,你如何调用JavaScript代码? - Adil
@delboud请查看我的答案,这是一个仅使用JS的解决方案。 - billmalarky
5个回答

15

是的,这是可以实现的。

React Native在本地桥接(Java/Objc)和JS之间运行,其中涉及“本地”和JS模块的概念(模块可以具有您可以从桥的“另一侧”调用的方法)。所有UI都是在桥的基础上构建的(处理生成视图的主要“本地”模块称为“UIManager”)。可以直接使用桥,唯一的限制是通信必须是异步的。

您可以从JAVA代码中调用JavaScript函数。参见此链接以获取文档。


1
是的,那就是我最终所做的。很遗憾它没有包含在核心API中。 - andri
4
嗨 @andri,你能否友好地分享gist中的代码片段?如果你有一个参考的代码库会更好。 :D - holyxiaoxin

12

当然可以。实际上,现在完全可以使用JS(无需编写原生代码)通过React Native QueueReact Native Background Task在跨平台上实现这个功能。

但是有一些限制。后台任务最小时间间隔大约为15分钟(如果甚至触发了定时任务,其定时不保证准确 - iOS/Android调度程序是一个黑匣子,它考虑电池寿命、当前CPU负载等因素来确定何时触发已安排的任务)。此外,任务的执行时间限制为30秒。

我写了一篇关于如何设置所有这些的教程,点击此处阅读

如果您在安装和运行中遇到任何困难,请告诉我。


10

在无界面任务中调用本地模块的方法是否可行?由于React Bridge在一段时间后处于“休眠”状态(待机模式),因此JS中的本地调用似乎会挂起,直到设备唤醒。在我的情况下,当我的本地播放器完成前一个曲目时,我想要开始播放播放列表的下一个曲目(Javascript端)。我使用一个无界面任务来通知JS尝试从我的本地模块调用“play(nextSong)”。但是,本地函数直到我唤醒设备才会执行。 - Paul Wasson

3
在我的情况下,我使用react-native-background-job库来运行后台服务。即使杀掉应用程序,它也可以正常工作。 https://github.com/vikeri/react-native-background-job
import BackgroundJob from "react-native-background-job";

const regularJobKey = "regularJobKey";

BackgroundJob.register({
  jobKey: regularJobKey,
  job: () => {
    
    console.log('Background Service Call!');

  }
});

<TouchableHighlight
  onPress={() => {
    BackgroundJob.schedule({
      jobKey: regularJobKey,
      period: 2000
    });
  }}
>
  <Text>Schedule regular job</Text>
</TouchableHighlight>

示例在此处:https://github.com/vikeri/react-native-background-job/blob/master/example/index.android.js

我想调用Web服务,如何在当前视图中设置数据? - Kirit Modi
嗨,当手机锁屏时它会运行吗? - Mohd Shahid

0

尝试使用react-native-background-actions,它是一个非常棒的服务,即使对于iOS也是如此,并且他们还提供了ProgressBar功能。

yarn add react-native-background-actions

or npm:

npm install --save react-native-background-actions

一个简短的代码片段,展示如何使用它。
import BackgroundService from 'react-native-background-actions';
 
// You can do anything in your task such as network requests, timers and so on,
// as long as it doesn't touch UI. Once your task completes (i.e. the promise is resolved),
// React Native will go into "paused" mode (unless there are other tasks running,
// or there is a foreground app).
const veryIntensiveTask = async (taskDataArguments) => {
    // Example of an infinite loop task
    const { delay } = taskDataArguments;
    await new Promise((resolve) => {
        for (let i = 0; BackgroundService.isRunning(); i++) {
            console.log(i);
            await sleep(delay);
        }
    });
};
 
const options = {
    taskName: 'Example',
    taskTitle: 'ExampleTask title',
    taskDesc: 'ExampleTask description',
    taskIcon: {
        name: 'ic_launcher',
        type: 'mipmap',
    },
    color: '#ff00ff',
    linkingURI: 'yourSchemeHere://chat/jane', // See Deep Linking for more info
    parameters: {
        delay: 1000,
    },
};
 
 
await BackgroundService.start(veryIntensiveTask, options);
await BackgroundService.updateNotification({taskDesc: 'New ExampleTask description'}); // Only Android, iOS will ignore this call
// iOS will also run everything here in the background until .stop() is called
await BackgroundService.stop();

如果你最小化应用程序或终止应用程序,这将无法正常工作。 - Hijas ajmal
是的,同样的问题。有什么解决办法吗? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接