我需要在我的 React Native Android 应用程序中实现 Headless JS,但我遇到了以下问题:
这是我的代码:
index.android.js :
import React, { Component } from 'react';
import {AppRegistry} from 'react-native';
import SomeTaskName from './SomeTaskName'
AppRegistry.registerComponent('SomeTaskName', () => SomeTaskName);
SomeTaskName.js
module.exports = async (taskData) => {
alert('test');
}
MyTaskService.java
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;
public class MyTaskService extends HeadlessJsTaskService {
@Override
protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"MyTaskService",
Arguments.fromBundle(extras),
5000);
}
return null;
}
}
并在AndroidManifest.xml中添加服务
<service android:name=".MyTaskService" android:enabled="true" android:label="MyTaskService" />
请,任何人帮助解决这个问题。
请您参考如下方法:
您必须注册一个 headless 任务。所以替换下面的代码:
AppRegistry.registerComponent('SomeTaskName', () => SomeTaskName);
与:
AppRegistry.registerHeadlessTask('SomeTaskName', () => SomeTaskName);
并且您需要从您的服务中调用任务,因此替换:
if (extras != null) {
return new HeadlessJsTaskConfig(
"MyTaskService",
Arguments.fromBundle(extras),
5000);
}
return null;
与:
// Following line just to be sure it does not silently fail
WritableMap data = extras != null ? Arguments.fromBundle(extras) : null;
return new HeadlessJsTaskConfig(
"SomeTaskName", // Use the registered headless Task here
data,
5000);