-
Notifications
You must be signed in to change notification settings - Fork 1
HeadlessJsTaskService
罗坤 edited this page Mar 6, 2020
·
1 revision
在没有UI的情况下运行JS代码。通常,你只需要重写
#getTaskConfig
方法,每个#onStartCommand
都会调用此方法。结果(除了null之外)都会被用到JS任务中。如果您需要对任务的运行方式更细粒度的控制,你可以重写
#onStartCommand
并取决于您的自定义逻辑来调用#startTask
如果您是从
BroadcastReceiver
启动的HeadlessJsTaskService
(例如处理推送通知),请确保在从BroadcastReceiver#onReceive
返回之前先调用#acquireWakeLockNow
,以确保在启动服务之前设备不会进入睡眠状态。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
HeadlessJsTaskConfig taskConfig = getTaskConfig(intent);
if (taskConfig != null) {
startTask(taskConfig);
return START_REDELIVER_INTENT;
}
return START_NOT_STICKY;
}
在#onStartCommand
内调用此方法来创建一个HeadlessJsTaskConfig
- @param
Intent
详见#acquireWakeLockNow
- @return 和
#startTask
一起使用的HeadlessJsTaskConfig
或者null(@Nullable)
import java.util.concurrent.TimeUnit;
public class MyService extends HeadlessJsTaskService {
@Override
protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
// If extras have been passed to the intent, pass them on into the JS as taskData
// which can be accessed as the first param.
WritableMap data = /* extras != null ? Arguments.fromBundle(extras) : */ Arguments.createMap();
int timeout = extras.getInt("timeout",5);
return new HeadlessJsTaskConfig(
// The the task was registered with in JS - must match
"BackgroundTask",
data,
TimeUnit.SECONDS.toMillis(timeout)
)
}
}
Context context = getContext().getApplicationContext();
Intent service = new Intent(context, MyService.class);
service.putExtra("time", 5)
context.startService(service);
HeadlessJsTaskService.acquireWakeLockNow(context);
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
启动任务。如果需要,此方法将处理启动新的React实例。 必须在UI线程上调用。
- @param taskConfig描述来要启动的任务以及要传递给它的参数
protected void startTask(final HeadlessJsTaskConfig taskConfig) {
//...
invokeStartTask(reactContext, taskConfig);
}
private void invokeStartTask(ReactContext reactContext, final HeadlessJsTaskConfig taskConfig) {
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
int taskId = headlessJsTaskContext.startTask(taskConfig);
mActiveTasks.add(taskId);
}
}
);
}