来自Expo&Forum的论坛交叉发布:
我一直在尝试让Headless JS任务在一个独立的ExpoKit项目(SDK25)上执行时遇到问题。我已经使用React Native文档来执行此操作。
我有一个广播接收器
public class MessageReceivedReceiver extends BroadcastReceiver {
private static final String TAG = "MessageReceivedReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive");
if (!isAppOnForeground((context))) {
Log.i(TAG, "Not in foreground");
/**
We will start our service and send extra info about
network connections
**/
Intent serviceIntent = new Intent(context, JSBackgroundService.class);
serviceIntent.putExtras(intent.getExtras());
context.startService(serviceIntent);
HeadlessJsTaskService.acquireWakeLockNow(context);
}
}
...
HeadlessJS任务服务:
public class JSBackgroundService extends HeadlessJsTaskService {
final static String TAG = "JSBackgroundService";
@Override
protected @Nullable
HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
Log.i(TAG, String.format("getTaskConfig: %s", extras));
if (extras != null) {
return new HeadlessJsTaskConfig(
"Test",
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;
}
}
我的MainApplication实现了ReactApplication:
public class MainApplication extends ExpoApplication implements ReactApplication {
private static final String TAG = MainApplication.class.getSimpleName();
private List<ReactPackage> packages = Arrays.<ReactPackage>asList(
// new MainReactPackage(),
new MyReactPackage()
);
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return packages;
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
…
在App.js中我有:
…
import JSBackgroundService from ‘./services/jsbackgroundservice’;
AppRegistry.registerHeadlessTask(‘Test’, () => {console.log(“Got it”); return JSBackgroundService; });
export default class App extends React.Component {
…
和JsBackgroundService:
module.exports = async (e) => {
// do stuff
console.log("Running the background service");
console.log(e);
};
基于日志我知道getTaskConfig已执行但由于某种原因,我在控制台日志中看不到任何内容,看起来javascript永远不会被执行。我已经尝试在前台运行Headless JS以进行测试,但无济于事。
有没有人有任何想法我可能做错了什么?
感谢任何帮助:)