【问题标题】:Background service on react-native androidreact-native android上的后台服务
【发布时间】:2016-01-08 22:56:37
【问题描述】:

有什么方法可以在 android 上使用 react-native 创建后台服务? 我想要某种计时器,它每隔一小时左右醒来一次,并启动一个简单的 JavaScript 任务。

【问题讨论】:

  • 你找到解决办法了吗?
  • 我也想知道:你找到解决办法了吗?
  • 不,但我有一个解决方法。我用java创建了后台服务,它又用reactContext.getJSModule(...).emit('javascript_event_name', params)调用了一些javascript代码。遗憾的是react-native API中没有直接可用的服务。
  • @andri 但是如果主要的反应应用程序被关闭,你如何调用 javascript 代码?
  • @delboud 在下面查看我的答案以获取仅限 JS 的解决方案。

标签: android react-native


【解决方案1】:

是的,可以的。

React native 在原生 (java/Objc) 到 JS 桥之上运行,具有“原生”和 JS 模块的概念(模块可以具有您可以从桥的“另一端”调用的方法)。所有的 UI 东西都建立在桥的顶部(处理生成视图的主要“本机”模块称为“UIManager”)。可以直接使用bridge,唯一的限制是通信必须是异步的。

您可以从 JAVA 代码中调用 javascript 函数。 Check this link 获取文档。

【讨论】:

  • 是的。这就是我结束做的事情。可惜它没有包含在核心 API 中。
  • 嗨@andri,你能分享一下sn-ps的要点吗?或者如果你有一个回购参考更好。 :D
【解决方案2】:

当然。事实上,现在用react native queuereact native background task 完全在JS(无需编写本机代码)跨平台实现这一点非常容易。

有一些限制。后台任务只会以最小的间隔大约每 15 分钟触发一次(并且即使完全触发,也不能保证时间是完美的 - iOS/Android 调度程序是一种查看电池寿命的黑匣子,当前确定何时触发计划任务时的 CPU 负载等)。此外,该任务的执行时间限制为 30 秒。

I've written a tutorial on how to set all this up here.

如果您在启动和运行它时遇到任何困难,请告诉我。

【讨论】:

    【解决方案3】:

    发布 v0.36 支持 headless-js,目前仅支持 Android。

    https://facebook.github.io/react-native/docs/headless-js-android.html

    【讨论】:

    • 是否可以在无头任务中调用本机模块的方法?由于在拔掉电源(打瞌睡模式)一段时间后反应桥“休眠”了,因此来自 JS 的本机调用似乎一直挂起,直到设备唤醒。就我而言,当我的本地播放器完成上一个播放列表时,我想开始播放播放列表的下一首曲目(Javascript 端)。我正在使用无头任务来通知尝试从我的本机模块调用“play(nextSong)”的 JS。但是在我唤醒设备之前不会执行本机功能。
    【解决方案4】:

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

    【讨论】:

    • 我要调用网络服务,怎么可能在当前视图中也设置数据。
    • 你好,手机锁屏时会运行吗?
    【解决方案5】:

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

    yarn add react-native-background-actions
    

    或 npm:

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

    如何使用它的简短代码sn-p。

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

    【讨论】:

      猜你喜欢
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多