React-Native Headless 疑惑

Ant*_*uez 5 javascript android headless reactjs react-native

我是 React Native 的新手。

我试图按照官方文档和其他类似链接进行无头工作。

这个想法如下: Headless Task 每隔一秒就会将存储中的值递增 1。每 3 秒 UI 就会读取这个存储的值并将其显示给用户。我在我的物理设备上运行它但没有成功。

似乎没有一个任务正在工作或被调用。我不知道。

感谢您的时间和合作!

脚步

1-我使用react-native-clireact -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);
};
Run Code Online (Sandbox Code Playgroud)

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)
        );
    }
  }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

5-应用程序.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;
Run Code Online (Sandbox Code Playgroud)

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'));
Run Code Online (Sandbox Code Playgroud)

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:4 7.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-2 2 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: React InstanceManager.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: ReactInstance Manager.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 160 11 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 桥。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反应原生: 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:3 3: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

Ant*_*uez 4

最后,我可以解决这个问题

如果有人需要,我已经为该项目创建了一个 GitHub 存储库。 https://github.com/Iltony/monitorService

谢谢!

一些任务名称.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';
Run Code Online (Sandbox Code Playgroud)

AndroidManifest.xml

// Added this permission (not necessary to run the service)
<uses-permission android:name="android.permission.WAKE_LOCK" />
Run Code Online (Sandbox Code Playgroud)

主应用程序.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);   
}
Run Code Online (Sandbox Code Playgroud)