我期待将我的应用程序从本机切换为rect-native。即使应用程序关闭,我也有一个跟踪用户GPS位置的应用程序。我怎样才能以原生的方式实现这一目标。
我查看了Headless JS并尝试了以下内容并且无法正常工作
<application>
...
<service android:name="com.BackgroundService" />
...
</application>
index.android.js
AppRegistry.registerComponent('geolocation', () => geolocation);
AppRegistry.registerHeadlessTask('SomeTaskName', () => require('./SomeTaskName'));
SomeTaskName.js
import SocketIOClient from 'socket.io-client';
module.exports = async (taskData) => {
// do stuff
var socket = SocketIOClient('http://xxx.xx.xx.xx:4000');
socket.emit("test");
}
BackgroundService.java
package com;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.facebook.react.HeadlessJsTaskService;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.jstasks.HeadlessJsTaskConfig;
public class BackgroundService extends HeadlessJsTaskService {
@Override
protected @Nullable
HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"SomeTaskName",
Arguments.fromBundle(extras),
5000);
}
return null;
}
}
MainActivity.java
package com.geolocation;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import com.BackgroundService;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
Intent service = new Intent(getApplicationContext(), BackgroundService.class);
this.startService(service);
}
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "geolocation";
}
}