【问题标题】:React-Native Headless doubtsReact-Native Headless 疑惑
【发布时间】:2018-03-22 05:29:38
【问题描述】:

我是 React Native 的新手。

我试图按照官方documentation 和其他链接(如this)进行无头工作。

思路如下: Headless Task 每隔一秒将 1 增加到 Storage 中的一个值。 UI 将每 3 秒读取一次存储的值并将其显示给用户。 我在物理设备上运行它没有成功。

似乎没有任何任务正在运行或调用。我不知道。

感谢您的时间和合作!

步骤

1-我使用 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 --------- 系统开始 --------- 崩溃开始 --------- main 开头 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

【问题讨论】:

  • 这里可以提供adb日志吗?在设备上运行应用程序并使用 $ adb logcat *:S ReactNative:V ReactNativeJS:V BackgroundTask:V
  • 嗨,HDevan,我在描述中添加了日志

标签: javascript android reactjs react-native headless


【解决方案1】:

终于,我可以解决问题了

如果有人需要,我已经为该项目创建了一个 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);   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-02
    • 2021-10-28
    • 2017-02-16
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多