react-native android上的后台服务

deikduxw  于 2023-05-27  发布在  Android
关注(0)|答案(5)|浏览(255)

有没有办法在android上用react-native创建一个后台服务?我想一些定时器,唤醒每小时左右排序,并启动一个简单的javascript任务。

vmdwslir

vmdwslir1#

是的,可以做到。
React native在native(java/Objc)到JS桥的基础上运行,它有一个“native”和JS模块的概念(模块可以有你可以从桥的“另一”端调用的方法)。所有的UI内容都构建在桥的顶部(处理生成视图的主要“本机”模块称为“UIManager”)。可以直接使用网桥,唯一的限制是通信必须是异步的。
您可以从JAVA代码调用javascript函数。Check this link的文档。

6psbrbz9

6psbrbz92#

当然。事实上,现在完全用JS(不需要编写本机代码)跨平台使用react本机队列和react native background task很容易实现这一点。
有一些限制。后台任务将仅以最小的间隔大约每15分钟触发一次(并且即使它甚至触发,也不能保证时间是完美的-iOS/Android调度程序是一种黑盒子,在确定何时触发计划任务时,它会查看电池寿命,当前CPU负载等)。此外,任务的执行时间限制为30秒。
I've written a tutorial on how to set all this up here
让我知道如果你有任何困难得到它和运行。

li9yvcax

li9yvcax4#

在我的例子中,使用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

sg2wtvxw

sg2wtvxw5#

尝试使用**react-native-background-actions,**这是非常棒的服务,即使是iOS,他们也提供了ProgressBar功能。

yarn add react-native-background-actions

或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();

相关问题