我需要在我的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" />
请帮助解决此问题。
答案 0 :(得分:1)
你必须注册无头任务。因此,请替换以下代码:
AppRegistry.registerComponent('SomeTaskName', () => SomeTaskName);
使用:
AppRegistry.registerHeadlessTask('SomeTaskName', () => SomeTaskName);
您需要从服务中调用该任务,因此请替换:
if (extras != null) {
return new HeadlessJsTaskConfig(
"MyTaskService",
Arguments.fromBundle(extras),
5000);
}
return null;
with:
// 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);