无头 JS
Headless JS 是一种在应用处于后台时在 JavaScript 中运行任务的方法。例如,它可用于同步新数据、处理推送通知或播放音乐。
¥Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.
JS API
任务是你在 AppRegistry
上注册的异步函数,类似于注册 React 应用:
¥A task is an async function that you register on AppRegistry
, similar to registering React applications:
import {AppRegistry} from 'react-native';
AppRegistry.registerHeadlessTask('SomeTaskName', () =>
require('SomeTaskName'),
);
那么,在 SomeTaskName.js
中:
¥Then, in SomeTaskName.js
:
module.exports = async taskData => {
// do stuff
};
你可以在任务中执行任何操作,例如网络请求、计时器等,只要不涉及 UI。一旦你的任务完成(即 promise 得到解决),React Native 将进入 "paused" 模式(除非有其他任务正在运行,或者有前台应用)。
¥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).
平台 API
¥The Platform API
是的,这仍然需要一些原生代码,但它非常薄。你需要扩展 HeadlessJsTaskService
并覆盖 getTaskConfig
,例如:
¥Yes, this does still require some native code, but it's pretty thin. You need to extend HeadlessJsTaskService
and override getTaskConfig
, e.g.:
- Java
- Kotlin
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, // timeout in milliseconds for the task
false // optional: defines whether or not the task is allowed in foreground. Default is false
);
}
return null;
}
}
package com.your_application_name;
import android.content.Intent
import com.facebook.react.HeadlessJsTaskService
import com.facebook.react.bridge.Arguments
import com.facebook.react.jstasks.HeadlessJsTaskConfig
class MyTaskService : HeadlessJsTaskService() {
override fun getTaskConfig(intent: Intent): HeadlessJsTaskConfig? {
return intent.extras?.let {
HeadlessJsTaskConfig(
"SomeTaskName",
Arguments.fromBundle(it),
5000, // timeout for the task
false // optional: defines whether or not the task is allowed in foreground.
// Default is false
)
}
}
}
然后将该服务添加到 AndroidManifest.xml
文件的 application
标记内:
¥Then add the service to your AndroidManifest.xml
file inside the application
tag:
<service android:name="com.example.MyTaskService" />
现在,每当你 开始你的服务 时,例如 作为周期性任务或响应某些系统事件/广播,JS 将启动,运行你的任务,然后停止运行。
¥Now, whenever you start your service, e.g. as a periodic task or in response to some system event / broadcast, JS will spin up, run your task, then spin down.
示例:
¥Example:
- Java
- Kotlin
Intent service = new Intent(getApplicationContext(), MyTaskService.class);
Bundle bundle = new Bundle();
bundle.putString("foo", "bar");
service.putExtras(bundle);
getApplicationContext().startForegroundService(service);
val service = Intent(applicationContext, MyTaskService::class.java)
val bundle = Bundle()
bundle.putString("foo", "bar")
service.putExtras(bundle)
applicationContext.startForegroundService(service)
重试
¥Retries
默认情况下,headless JS 任务不会执行任何重试。为此,你需要创建一个 HeadlessJsRetryPolicy
并抛出一个特定的 Error
。
¥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 specific Error
.
LinearCountingRetryPolicy
是 HeadlessJsRetryPolicy
的实现,允许你指定最大重试次数,并在每次尝试之间有固定的延迟。如果这不能满足你的需求,那么你可以实现你自己的 HeadlessJsRetryPolicy
。这些策略可以作为额外参数传递给 HeadlessJsTaskConfig
构造函数,例如
¥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 implement your own HeadlessJsRetryPolicy
. These policies can be passed as an extra argument to the HeadlessJsTaskConfig
constructor, e.g.
- Java
- Kotlin
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
);
val retryPolicy: HeadlessJsTaskRetryPolicy =
LinearCountingRetryPolicy(
3, // Max number of retry attempts
1000 // Delay between each retry attempt
)
return HeadlessJsTaskConfig("SomeTaskName", Arguments.fromBundle(extras), 5000, false, retryPolicy)
仅当抛出特定 Error
时才会进行重试尝试。在无头 JS 任务中,你可以导入错误并在需要重试时抛出它。
¥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 => {
const condition = ...;
if (!condition) {
throw new HeadlessJsTaskError();
}
};
如果你希望所有错误都导致重试尝试,则需要捕获它们并抛出上述错误。
¥If you wish all errors to cause a retry attempt, you will need to catch them and throw the above error.
注意事项
¥Caveats
-
默认情况下,如果你尝试在应用位于前台时运行任务,你的应用将会崩溃。这是为了防止开发者在一项任务中做大量工作并减慢 UI,从而搬起石头砸自己的脚。你可以传递第四个
boolean
参数来控制此行为。¥By default, your app will crash if you try to run a task while the app is in the foreground. This is to prevent developers from shooting themselves in the foot by doing a lot of work in a task and slowing the UI. You can pass a fourth
boolean
argument to control this behaviour. -
如果你从
BroadcastReceiver
开始服务,请确保在从onReceive()
返回之前致电HeadlessJsTaskService.acquireWakeLockNow()
。¥If you start your service from a
BroadcastReceiver
, make sure to callHeadlessJsTaskService.acquireWakeLockNow()
before returning fromonReceive()
.
用法示例
¥Example Usage
可以从 Java API 启动服务。首先,你需要决定何时启动服务并相应地实现你的解决方案。这是一个对网络连接更改做出反应的示例。
¥Service can be started from Java API. First you need to decide when the service should be started and implement your solution accordingly. Here is an example that reacts to network connection change.
以下几行显示了用于注册广播接收器的 Android 清单文件的一部分。
¥Following lines shows part of Android manifest file for registering broadcast receiver.
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
然后,广播接收器处理在 onReceive 函数中广播的意图。这是检查你的应用是否位于前台的好地方。如果应用不在前台,我们可以准备启动意图,而无需使用 putExtra
打包任何信息或附加信息(请记住,打包包只能处理可分割的值)。最后启动服务并获取唤醒锁。
¥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.
- Java
- Kotlin
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;
import com.facebook.react.HeadlessJsTaskService;
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
/**
This part will be called every time network connection is changed
e.g. Connected -> Not Connected
**/
if (!isAppOnForeground((context))) {
/**
We will start our service and send extra info about
network connections
**/
boolean hasInternet = isNetworkAvailable(context);
Intent serviceIntent = new Intent(context, MyTaskService.class);
serviceIntent.putExtra("hasInternet", hasInternet);
context.startForegroundService(serviceIntent);
HeadlessJsTaskService.acquireWakeLockNow(context);
}
}
private boolean isAppOnForeground(Context context) {
/**
We need to check if app is in foreground otherwise the app will crash.
https://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not
**/
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> 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);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network networkCapabilities = cm.getActiveNetwork();
if(networkCapabilities == null) {
return false;
}
NetworkCapabilities actNw = cm.getNetworkCapabilities(networkCapabilities);
if(actNw == null) {
return false;
}
if(actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
return true;
}
return false;
}
// deprecated in API level 29
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}
}
import android.app.ActivityManager
import android.app.ActivityManager.RunningAppProcessInfo
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import com.facebook.react.HeadlessJsTaskService
class NetworkChangeReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
/**
* This part will be called every time network connection is changed e.g. Connected -> Not
* Connected
*/
if (!isAppOnForeground(context)) {
/** We will start our service and send extra info about network connections */
val hasInternet = isNetworkAvailable(context)
val serviceIntent = Intent(context, MyTaskService::class.java)
serviceIntent.putExtra("hasInternet", hasInternet)
context.startForegroundService(serviceIntent)
HeadlessJsTaskService.acquireWakeLockNow(context)
}
}
private fun isAppOnForeground(context: Context): Boolean {
/**
* We need to check if app is in foreground otherwise the app will crash.
* https://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not
*/
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val appProcesses = activityManager.runningAppProcesses ?: return false
val packageName: String = context.getPackageName()
for (appProcess in appProcesses) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
appProcess.processName == packageName
) {
return true
}
}
return false
}
companion object {
fun isNetworkAvailable(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
var result = false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = cm.activeNetwork ?: return false
val actNw = cm.getNetworkCapabilities(networkCapabilities) ?: return false
result =
when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
return result
} else {
cm.run {
// deprecated in API level 29
cm.activeNetworkInfo?.run {
result =
when (type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
ConnectivityManager.TYPE_ETHERNET -> true
else -> false
}
}
}
}
return result
}
}
}