android headless模式,Headless JS(后台任务)

2023-05-16

Headless JS 是一种使用 js 在后台执行任务的方法。它可以用来在后台同步数据、处理推送通知或是播放音乐等等。

JS 端的 API#

首先我们要通过AppRegistry来注册一个异步函数,这个函数我们称之为“任务”。注册方式类似在 index.js 中注册 RN 应用:

import{AppRegistry}from'react-native';

AppRegistry.registerHeadlessTask('SomeTaskName',()=>

require('SomeTaskName')

);Copy

然后创建 require 中引用的SomeTaskName.js文件:

module.exports=asynctaskData=>{

// 要做的任务

};Copy

你可以在任务中处理任何事情(网络请求、定时器等等),但唯独不要涉及用户界面!在任务完成后(例如在 promise 中调用 resolve),RN 会进入一个“暂停”模式,直到有新任务需要执行或者是应用回到前台。

Java 端的 API#

没错,我们还需要一些原生代码,但是请放心并不麻烦。首先需要像下面这样继承HeadlessJsTaskService,然后覆盖getTaskConfig方法的实现:

package com.your_application_name;

import android.content.Intent;

import android.os.Bundle;

import com.facebook.react.HeadlessJsTaskService;

import com.facebook.react.bridge.Arguments;

import com.facebook.react.jstasks.HeadlessJsTaskConfig;

import javax.annotation.Nullable;

public class MyTaskService extends HeadlessJsTaskService {

@Override

protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {

Bundle extras = intent.getExtras();

if (extras != null) {

return new HeadlessJsTaskConfig(

"SomeTaskName",

Arguments.fromBundle(extras),

5000, // 任务的超时时间

false // 可选参数:是否允许任务在前台运行,默认为false

);

}

return null;

}

}Copy

然后记得把服务添加到AndroidManifest文件里:

Copy

好了,现在当你启动服务时(例如一个周期性的任务或是响应一些系统事件/广播),JS 任务就会开始执行。例如:

Intent service = new Intent(getApplicationContext(), MyTaskService.class);

Bundle bundle = new Bundle();

bundle.putString("foo", "bar");

service.putExtras(bundle);

getApplicationContext().startService(service);Copy

重试#

By default, the headless JS task will not perform any retries. In order to do so, you need to create a HeadlessJsRetryPolicy and throw a specfic Error.

LinearCountingRetryPolicy is an implementation of HeadlessJsRetryPolicy that allows you to specify a maximum number of retries with a fixed delay between each attempt. If that does not suit your needs then you can easily implement your own HeadlessJsRetryPolicy. These policies can simply be passed as an extra argument to the HeadlessJsTaskConfig constructor, e.g.

HeadlessJsRetryPolicy retryPolicy = new LinearCountingRetryPolicy(

3, // Max number of retry attempts

1000 // Delay between each retry attempt

);

return new HeadlessJsTaskConfig(

'SomeTaskName',

Arguments.fromBundle(extras),

5000,

false,

retryPolicy

);Copy

A retry attempt will only be made when a specific Error is thrown. Inside a headless JS task, you can import the error and throw it when a retry attempt is required.

Example:

import{HeadlessJsTaskError}from'HeadlessJsTask';

module.exports=async(taskData)=>{

constcondition=...;

if(!condition){

thrownewHeadlessJsTaskError();

}

};Copy

If you wish all errors to cause a retry attempt, you will need to catch them and throw the above error.

注意事项#The function passed to setTimeout does not always behave as expected. Instead the function is called only when the application is launched again. If you just need to wait, use the retry functionality.默认情况下,如果应用正在前台运行时尝试执行任务,那么应用会崩溃。这是为了防止开发者在任务中处理太多逻辑而拖慢用户界面。如果你必须要这么做,那么可以设置第四个参数为false来更改这一限制。

如果你是通过BroadcastReceiver来启动的服务,那么谨记在从onReceive()返回之前要调用HeadlessJsTaskService.acquireWakeLockNow()。

示例#

我们可以使用 Java API 来开启一个 service。. First you need to decide when the service should be started and implement your solution accordingly. Here is a simple example that reacts to network connection change.

Following lines shows part of Android manifest file for registering broadcast receiver.

Copy

Broadcast receiver then handles intent that was broadcasted in onReceive function. This is a great place to check whether your app is on foreground or not. If app is not on foreground we can prepare our intent to be started, with no information or additional information bundled using putExtra (keep in mind bundle can handle only parcelable values). In the end service is started and wakelock is acquired.

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override

public void onReceive(final Context context, final Intent intent) {

/**

这部分代码会在每次网络状态变化时调用,比如掉线的时候

**/

if (!isAppOnForeground((context))) {

/**

启动服务并发送当前的网络状态信息

**/

boolean hasInternet = isNetworkAvailable(context);

Intent serviceIntent = new Intent(context, MyTaskService.class);

serviceIntent.putExtra("hasInternet", hasInternet);

context.startService(serviceIntent);

HeadlessJsTaskService.acquireWakeLockNow(context);

}

}

private boolean isAppOnForeground(Context context) {

/**

我们需要先检查应用当前是否在前台运行,否则应用会崩溃。

http://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not

**/

ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

List appProcesses =

activityManager.getRunningAppProcesses();

if (appProcesses == null) {

return false;

}

final String packageName = context.getPackageName();

for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {

if (appProcess.importance ==

ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&

appProcess.processName.equals(packageName)) {

return true;

}

}

return false;

}

public static boolean isNetworkAvailable(Context context) {

ConnectivityManager cm = (ConnectivityManager)

context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo netInfo = cm.getActiveNetworkInfo();

return (netInfo != null && netInfo.isConnected());

}

}Copy

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

android headless模式,Headless JS(后台任务) 的相关文章

随机推荐

  • Python:配置Jinja2模版引擎

    一 摘要 pip下载jinja2 更换模版引擎 指定模版文件的加载路径 新建jinja2模版引擎的环境文件 xff0c 并且自定义语法 将语法加载到jinja2模版引擎当中 二 步骤 1 pip下载jinja2 pip install ji
  • 【AWS入门】AWS CICD

    目录 一 TASK二 环境准备IAM创建存储库ec2 repoec2 wp 三 Code Deploy创建应用程序创建部署组创建管道部署后的ec2 wp 一 TASK 创建2台EC2实例 xff0c 一台名为 ec2 repo xff0c
  • 【AWS入门】将EC2的系统日志推送到CloudWatch

    创建一个 EC2 实例 xff0c 不附加任何 IAM profile 这里注意不要用23年最新版本的镜像 xff0c 该镜像不支持awslogs 选择旧版镜像可成功安装awslogs 开始创建一个 IAM profile 创建角色 xff
  • CAS单点登录详细流程

    一 CAS简介和整体流程 CAS 是 Yale 大学发起的一个开源项目 xff0c 旨在为 Web 应用系统提供一种可靠的单点登录方法 xff0c CAS 在 2004 年 12 月正式成为 JA SIG 的一个项目 CAS 具有以下特点
  • 【AWS入门】利用CloudWatch监控EC2的CPU负载情况

    创建一个 EC2 实例 User data 配置如下 span class token comment bin bash span sudo span class token operator span i amazon span clas
  • ORACLE查看一个视图是由哪些表而来

    核心sql explain plan for select from v1 select from table dbms xplan display SQL解析 dbms xplan display 相当于一个report xff0c 是由
  • Show Parameter 参数查询的两种方式

    假设你想查询包含con的参数 xff0c 但记不清全拼了 xff0c 可以按照如下方式进行查询 方式一 show parameter cont 方式二 select name from v parameter where UPPER nam
  • stm32 SPI/UART的配置

    一般来说配置USARTx RX和SPI MISO是需要配置上拉输入 xff0c 可实际使用过程中配置推完复用也可正常使用 xff0c 不必纠结 xff0c 若纠结 xff0c 可以配置自己理解的方式
  • stm32---08FreeRTOS实现多任务

    更新记录链接 https blog csdn net weixin 42162924 article details 124562037 前言 目标 FreeRTOS实现多任务 2颗LED以不同频率闪烁 一 准备工作 硬件平台 正点原子探索
  • 变结构PID与经典PID比较

    一 xff0e 普通PID调节器 使用普通PID控制PMSM 仿真时间0 3s xff0c 转速设定值10r s 设定转速 上升时间 ms 调节时间 ms 超调量 稳态误差 rps 10r s 1 5 5 6 0 13 由上图曲线以及图表可
  • linux bash 内容查找,Linux Bash-文件查找

    locate xff1a 作用 非实时模糊查询文件 xff0c 根据全系统文件数据库进行查询 使用updatedb命令手动生成文件数据库 xff0c 较为耗时 find xff1a 作用 实时精确查询文件 xff0c 通过遍历指定目录中的所
  • 使用STM32H757XI双核流水灯调试

    STM32H757XI双核流水灯调试 使用STM32H757XI流水灯调试环境准备硬件配置软件配置程序调试 使用STM32H757XI流水灯调试 环境准备 我采用的STM32CubeIDE集成开发环境调试 xff0c 非常方便 新建一个工程
  • Ubuntu下访问windows的共享文件遇到的问题以及解决办法(ubuntu版本20.04)

    前提 xff1a 今天ubutnu下面与windos共享的文件夹相互传文件时发现共享文件夹有如下症状 xff1a 1 xff09 使用命令vmware hgfsclient能看到我有个共享文件夹 2 xff09 从共享文件夹的目录进入的时候
  • 数据可视化组态编辑器—TopV

    图扑TopV 组态编辑器 xff0c 是一款应用于广泛物联网场景的数据可视化编辑器 软件前端界面采用标准 HTML5 开发 xff0c 支持图形组态 xff0c 支持 MQTT Kafka HTTP 数据接入 可与企业自有平台无缝整合 xf
  • 【深度学习】转载_目标识别损失函数

    转载自博客 人脸识别 MTCNN 43 Arcface全流程详解 Pytorch代码 损失函数发展 人脸识别介绍 MTCNN 实现人脸检测 xff0c 回答了 是不是人脸 和 人脸在哪 的问题 xff0c 接下来人脸识别要解决的就是 人脸是
  • 【ROS】关于 tf2_tools 的安装

    首先使用 rospack find tf2 tools 查看是否安装了 tf2 tools xff0c 如果没有则安装 但直接采用 sudo apt install tf2 tools 是无法安装成功的 xff0c 会显示 E 无法定位软件
  • Socket编程(C语言实现)——TCP协议(网络间通信AF_INET)的流式(SOCK_STREAM)+报式(SOCK_DGRAM)传输【多线程+循环监听】

    Socket编程 目前较为流行的网络编程模型是客户机 服务器通信模式 客户进程向服务器进程发出要求某种服务的请求 xff0c 服务器进程响应该请求 如图所示 xff0c 通常 xff0c 一个服务器进程会同时为多个客户端进程服务 xff0c
  • Git报错:reference broken

    为了pull最新的代码到本地虚拟环境 xff0c 在git pull的时候出现下面的错误 xff0c 最后解决了 xff0c 但是免不了下次出现类似的错误 xff0c 所谓好记性不如烂笔头 记录一下解决办法 问题现象 git pull报错
  • linux声音脚本,bash - 通过CLI使Linux中的音频静音的脚本有效,但需要帮助 - 堆栈内存溢出...

    我经常在工作时播放新闻 xff0c 并想在广告中使声音静音 xff0c 因此四处寻找 产生了一些好东西 xff0c 并产生了下面的脚本 xff0c 其工作原理像一个吊饰 xff1a 161 MM numid 61 16 iface 61 M
  • android headless模式,Headless JS(后台任务)

    Headless JS 是一种使用 js 在后台执行任务的方法 它可以用来在后台同步数据 处理推送通知或是播放音乐等等 JS 端的 API 首先我们要通过AppRegistry来注册一个异步函数 xff0c 这个函数我们称之为 任务 注册方