JS API
任务是一个简单的异步函数,您可以在AppRegistry上注册,类似于注册React应用程序:
AppRegistry.registerHeadlessTask('SomeTaskName', () => require('SomeTaskName'));
然后, 在 SomeTaskName.js中:
module.exports = async (taskData) => {
// do stuff
};
只要不触及用户界面,您可以在任务中执行任何操作:网络请求,定时器等等。 一旦您的任务完成(即承诺已解决),React Native将进入“已暂停”模式(除非有其他任务正在运行,或者有前台应用程序)。
Java API
是的,这仍然需要一些本地代码,但它非常简单。 您需要扩展HeadlessJsTaskService并覆盖getTaskConfig,例如:
public class MyTaskService extends HeadlessJsTaskService {
protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"SomeTaskName",
Arguments.fromBundle(extras),
5000, // timeout for the task
false // optional: defines whether or not the task is allowed in foreground. Default is false
);
}
return null;
}
}
然后在你的AndroidManifest.xml file中添加服务:
<service android:name="com.example.MyTaskService" />
现在,每当你开始你的服务,例如 作为一个周期性的任务,或者是为了响应一些系统事件/广播,JS会旋转起来,运行你的任务,然后停下来。
例:
Intent service = new Intent(getApplicationContext(), MyTaskService.class);
Bundle bundle = new Bundle();
bundle.putString("foo", "bar");
service.putExtras(bundle);
getApplicationContext().startService(service);
注意事项
1.默认情况下,如果您尝试在应用程序处于前台时运行任务,您的应用程序将崩溃。 这是为了防止开发人员在一个任务中做了大量的工作,放慢了用户界面的开发速度。 您可以传递第四个布尔参数来控制此行为。
2.如果您从BroadcastReceiver开始您的服务,请务必在从onReceive()返回之前调用HeadlessJsTaskService.acquireWakeLockNow()。
用法示例
服务可以从Java API启动。 首先,您需要决定何时启动服务并相应地实施您的解决方案。 这是一个简单的例子,对网络连接变化作出反应。
下面的行显示了用于注册广播接收机的Android清单文件的一部分。
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
广播接收机然后处理在onReceive函数中播放的意图。 这是检查您的应用程序是否在前台的好地方。 如果应用程序不在前台,我们可以准备启动的意图,没有使用putExtra捆绑的信息或附加信息(请记住bundle只能处理parcelable值)。 最后,服务启动,并获得了唤醒锁。
public class NetworkChangeReceiver extends BroadcastReceiver {
public void onReceive(final Context context, final Intent intent) {
/**
This part will be called everytime 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.startService(serviceIntent);
HeadlessJsTaskService.acquireWakeLockNow(context);
}
}
private boolean isAppOnForeground(Context context) {
/**
We need to check if app is in foreground otherwise the app will crash.
http://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);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}
}