我是React Native的新手。
我试图按照官方documentation和this等其他链接进行无头工作。
这个想法如下: 每一秒,无头任务将1增加到存储中的值。 UI每隔3秒读取一次该存储的值并将其显示给用户。 我在我的物理设备上运行它没有成功。
这些任务似乎都没有工作或被调用。我不知道。
感谢您的时间和合作!
STEPS
1-I使用 react-native-cli 创建了一个应用 react-native init monitorService
2 - 在根目录中,我创建了一个文件 SomeTaskName.js
3-在android / app / src / main / java / com / monitorService文件夹中我创建了一个文件 MyTaskService.java
4 - 更改 AndroidManifest.xml 以包含服务
5 - 更改 App.js 以包含逻辑。
6 - 更改 Index.js 以调用服务
"按步骤命令或命令"
1 - react-native init monitorService
2- SomeTaskName.js
const internalWritting = null;
export default async (taskData) => {
// do stuff
console.log("TASK REGISTER DATA", taskData);
this.intervalWritting = setInterval(async () => {
await AsyncStorage.getItem(SuperStoreServerConfig)
.then(success => JSON.parse(success))
.then((storedItem) => {
if (storedItem) {
AsyncStorage.setItem(SuperStoreServerConfig, JSON.stringify(storedItem + 1))
.catch(err => {console.log(`error setting local storage ${err}`)});
return true;
} else {
AsyncStorage.setItem(SuperStoreServerConfig, JSON.stringify(1))
.catch(err => {console.log(`error setting local storage ${err}`)});
return true;
}
return false;
})
.catch(err => {console.log(`error ${err}`)});
}, 1000);
};
3- MyTaskService.java
package com.monitorservice;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.jstasks.HeadlessJsTaskConfig;
import com.facebook.react.HeadlessJsTaskService;
import java.util.concurrent.TimeUnit;
public class MyTaskService extends HeadlessJsTaskService {
private static final String TASK_NAME = "SomeTaskName";
@Override
protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
WritableMap data = extras != null ? Arguments.fromBundle(extras) : Arguments.createMap();
// WritableMap data = Arguments.createMap();
int timeout = 30; //extras.getInt("timeout");
Log.d(TASK_NAME, String.format("Returning HeadlessJsTaskConfig, timeout=%s ms", timeout));
return new HeadlessJsTaskConfig(TASK_NAME, data, TimeUnit.SECONDS.toMillis(timeout)
);
}
}
4-的的AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.monitorservice">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:allowBackup="false"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.monitorservice.MyTaskService" android:enabled="true" />
</application>
</manifest>
-5-的 App.js
export const SuperStoreServerConfig = '@monitorService:serverConfig';
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
AsyncStorage
} from 'react-native';
class App extends Component {
constructor(props) {
super(props);
this.state = { value: 0 };
}
componentDidMount(){
this.interval = setInterval(async () => {
await AsyncStorage.getItem(SuperStoreServerConfig)
.then(success => JSON.parse(success))
.then((storedItem) => {
if (storedItem) {
this.setState({ value: storedItem });
return true;
}
return false;
})
.catch(err => {console.log(`error ${err}`)});
}, 3000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
const msg = `To get started, edit App.js - ${this.state.value}`;
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Value readed from local storage!
</Text>
<Text style={styles.instructions}>
{msg}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
export default App;
6- index.js
import { AppRegistry } from 'react-native';
import App from './App';
import SomeTask from '../monitorService/SomeTaskName';
AppRegistry.registerComponent('monitorService', () => App);
AppRegistry.registerHeadlessTask('SomeTaskName', () => SomeTask);
// The intention of this second headless task is just logging.
AppRegistry.registerHeadlessTask('OtherTaskName', () => console.log('other task log'));
adb logCat
$ adb logcat *:S ReactNative:V ReactNativeJS:V BackgroundTask:V ---------系统的开头 ---------崩溃的开始 ---------主要的开始 03-22 17:24:04.614 9128 9128? SENTINEL_TAG:SENTINEL_MSG_LIBCUTILS 03-22 17:24:04.614 9128 9128? SENTINEL_TAG:SENTINEL_MSG_LIBLOG 03-22 17:54:50.388 10492 10492? SENTINEL_TAG:SENTINEL_MSG_LIBCUTILS 03-22 17:54:50.388 10492 10492? SENTINEL_TAG:SENTINEL_MSG_LIBLOG 03-22 18:31:04.408 14318 14381? SENTINEL_TAG:SENTINEL_MSG_LIBCUTILS 03-22 18:31:04.408 14318 14381? SENTINEL_TAG:SENTINEL_MSG_LIBLOG 03-22 18:32:52.652 15188 15188? SENTINEL_TAG:SENTINEL_MSG_LIBCUTILS 03-22 18:32:52.652 15188 15188? SENTINEL_TAG:SENTINEL_MSG_LIBLOG 03-22 18:33:47.819 15674 15722? SENTINEL_TAG:SENTINEL_MSG_LIBCUTILS 03-22 18:33:47.819 15674 15722? SENTINEL_TAG:SENTINEL_MSG_LIBLOG 03-22 18:33:47.868 15699 15699 D ReactNative:ReactInstanceManager.ctor() 03-22 18:33:47.913 15699 15699 D ReactNative:ReactInstanceManager.createReactContextInBackground() 03-22 18:33:47.913 15699 15699 D ReactNative:ReactInstanceManager.recreateReactContextInBackgroundInner() 03-22 18:33:47.955 15699 15699 D ReactNative:ReactInstanceManager.onReloadWithJSDebugger() 03-22 18:33:47.955 15699 15699 D ReactNative:ReactInstanceManager.recreateReactContextInBackground() 03-22 18:33:47.956 15699 15699 D ReactNative:ReactInstanceManager.runCreateReactContextOnNewThread() 03-22 18:33:51.118 15699 15699 D ReactNative:ReactInstanceManager.onReloadWithJSDebugger() 03-22 18:33:51.118 15699 15699 D ReactNative:ReactInstanceManager.recreateReactContextInBackground() 03-22 18:33:53.639 16011 16011 D ReactNative:ReactInstanceManager.ctor() 03-22 18:33:53.670 16011 16011 D ReactNative:ReactInstanceManager.createReactContextInBackground() 03-22 18:33:53.670 16011 16011 D ReactNative:ReactInstanceManager.recreateReactContextInBackgroundInner() 03-22 18:33:53.709 16011 16011 D ReactNative:ReactInstanceManager.onReloadWithJSDebugger() 03-22 18:33:53.710 16011 16011 D ReactNative:ReactInstanceManager.recreateReactContextInBackground() 03-22 18:33:53.711 16011 16011 D ReactNative:ReactInstanceManager.runCreateReactContextOnNewThread() 03-22 18:33:58.824 16011 16092 D ReactNative:ReactInstanceManager.createReactContext() 03-22 18:33:58.992 16011 16092 D ReactNative:初始化React Xplat Bridge。 03-22 18:33:58.995 16011 16092 D ReactNative:在initializeBridge之前初始化React Xplat Bridge 03-22 18:33:59.010 16011 16092 D ReactNative:在initializeBridge之后初始化React Xplat Bridge 03-22 18:33:59.010 16011 16092 D ReactNative:CatalystInstanceImpl.runJSBundle() 03-22 18:33:59.011 16011 16140 D ReactNative:ReactInstanceManager.setupReactContext() 03-22 18:33:59.011 16011 16140 D ReactNative:CatalystInstanceImpl.initialize() 03-22 18:33:59.012 16011 16140 D ReactNative:ReactInstanceManager.attachRootViewToInstance() 03-22 18:39:37.859 16877 16877? SENTINEL_TAG:SENTINEL_MSG_LIBCUTILS 03-22 18:39:37.859 16877 16877? SENTINEL_TAG:SENTINEL_MSG_LIBLOG
答案 0 :(得分:0)
最后,我可以解决问题。
如果有人需要,我已经为项目创建了一个GitHub仓库。 https://github.com/Iltony/monitorService
谢谢!
SomeTaskName.js
// I have to add this references to have the project running (not // necessary to run the service) import { AsyncStorage } from 'react-native'; export const SuperStoreServerConfig = '@monitorService:serverConfig';
<强>的AndroidManifest.xml 强>
// Added this permission (not necessary to run the service) <uses-permission android:name="android.permission.WAKE_LOCK" />
<强> MainApplication.java 强>
// The key is in this method, on the create I forget to start the // service @Override public void onCreate() { super.onCreate(); ** Intent myIntent = new Intent(getApplicationContext(), MyTaskService.class); getApplicationContext().startService(myIntent); HeadlessJsTaskService.acquireWakeLockNow(getApplicationContext()); SoLoader.init(this, false); }