SDKJava (Android) SDK

Runtime modes

Android Java SDK: Runtime modes

Current version · 2.0.0

Runtime modes

Choose one runtime mode after starting devices. Ordinary Android apps should use runBackground() and let an app worker coordinate UI and shutdown.

ModeCallApp responsibility
Background loopsdk.runBackground()requestStop, join, stop, disconnect when finished
Calling-thread loopsdk.runForever()Run on a dedicated worker and request stop from a control thread
Manual updatessdk.update()Honor task/wait results; do not busy-poll

Manual updates

ManualRuntime.run(...) advances Glove work for a fixed number of updates: it calls sleep() once after each update(), yields briefly when there is no scheduled work, then prints the latest target output. It takes the port, side, algorithm package and a positive update count.

import android.content.Context;
import com.qnbot.sdk.Sdk;
import com.qnbot.sdk.SdkConfig;
import com.qnbot.sdk.SleepResult;
import com.qnbot.sdk.android.SerialTransport;
import com.qnbot.sdk.channel.ReadChannel;
import com.qnbot.sdk.config.DeviceSelector;
import com.qnbot.sdk.config.SerialConnection;
import com.qnbot.sdk.config.Side;
import com.qnbot.sdk.config.TargetAlgorithm;
import com.qnbot.sdk.config.TargetConfig;
import com.qnbot.sdk.glove.Glove;
import com.qnbot.sdk.glove.GloveConfig;
import com.qnbot.sdk.glove.GloveDevice;
import com.qnbot.sdk.glove.HandJointCommand;

/**
 * Advances Glove work manually for a requested number of updates.
 *
 * <p>Pass the host {@link Context}, an authorized transport, the glove port and side, the installed
 * algorithm package, and a positive update count. Each step waits for scheduled work, yields
 * briefly when the SDK has none, then prints the latest retargeted output.
 */
public final class ManualRuntime {
  private ManualRuntime() {}

  public static void run(Context context, SerialTransport transport, String port, Side side,
      String packageId, int updates) throws InterruptedException {
    if (updates <= 0)
      throw new IllegalArgumentException("updates must be positive");
    SdkConfig config = SdkConfig.builder()
        .device(GloveConfig.builder()
                    .name("primary")
                    .side(side)
                    .connection(SerialConnection.port(port))
                    .build())
        .target(TargetConfig.builder()
                    .name("openxr_hand")
                    .side(side)
                    .source(new DeviceSelector("glove", "primary", side))
                    .algorithm(new TargetAlgorithm(packageId))
                    .build())
        .build();
    try (Sdk sdk = new Sdk(config, context, transport); Glove glove = sdk.glove()) {
      GloveDevice device = glove.device();
      ReadChannel<HandJointCommand> output = device.output("openxr_hand");
      glove.start();
      for (int step = 0; step < updates; step++) {
        SleepResult outcome = glove.update().sleep();
        if (outcome == SleepResult.STOPPED)
          break;
        if (outcome == SleepResult.NO_TASKS) {
          // Preparation or Capture still needs the caller; yield instead of spinning.
          Thread.sleep(10);
        }
        output.latest().ifPresent(sample
            -> System.out.println("retargeting sequence=" + sample.sequence
                + " target=" + sample.value.target + " joints=" + sample.value.joints));
      }
    }
  }
}

Call requestStop() from a control thread to finish. Call sleep() once after every update(). hasNextTask reports periodic deadlines only; event-driven work can still need a wait when it is false. READY continues the loop, STOPPED ends it, and NO_TASKS means there is currently nothing to wait on. The example pauses briefly only for NO_TASKS to avoid busy polling; do not replace the SDK wait with a fixed delay. After the loop returns, close the SDK if the session is over. Follow the lifecycle.

Background and async runtime

ForegroundRuntime streams target output on the calling thread with runForever(); see Reading retargeting data for its complete code. BackgroundRuntime runs on the SDK background thread for a fixed duration, then calls requestStop() and join().

import android.content.Context;
import com.qnbot.sdk.Sdk;
import com.qnbot.sdk.SdkConfig;
import com.qnbot.sdk.android.SerialTransport;
import com.qnbot.sdk.config.DeviceSelector;
import com.qnbot.sdk.config.SerialConnection;
import com.qnbot.sdk.config.Side;
import com.qnbot.sdk.config.TargetAlgorithm;
import com.qnbot.sdk.config.TargetConfig;
import com.qnbot.sdk.glove.Glove;
import com.qnbot.sdk.glove.GloveConfig;
import com.qnbot.sdk.glove.GloveDevice;

/**
 * Runs retargeting on the SDK background thread for a fixed duration.
 *
 * <p>Pass the host {@link Context}, an authorized transport, the glove port and side, the installed
 * algorithm package, and the positive run time. The target subscription prints commands; cleanup
 * requests stop and joins the runner.
 */
public final class BackgroundRuntime {
  private BackgroundRuntime() {}

  public static void run(Context context, SerialTransport transport, String port, Side side,
      String packageId, double seconds) throws InterruptedException {
    if (!Double.isFinite(seconds) || seconds <= 0)
      throw new IllegalArgumentException("seconds must be positive and finite");
    SdkConfig config = SdkConfig.builder()
        .device(GloveConfig.builder()
                    .name("primary")
                    .side(side)
                    .connection(SerialConnection.port(port))
                    .build())
        .target(TargetConfig.builder()
                    .name("openxr_hand")
                    .side(side)
                    .source(new DeviceSelector("glove", "primary", side))
                    .algorithm(new TargetAlgorithm(packageId))
                    .build())
        .build();
    try (Sdk sdk = new Sdk(config, context, transport); Glove glove = sdk.glove()) {
      GloveDevice device = glove.device();
      device.output("openxr_hand")
          .subscribe(sample
              -> System.out.println("retargeting sequence=" + sample.sequence
                  + " target=" + sample.value.target + " joints=" + sample.value.joints));
      glove.start();
      glove.runBackground();
      try {
        Thread.sleep((long) (seconds * 1_000));
      } finally {
        glove.requestStop();
        glove.join();
      }
    }
    System.out.println("background stopped");
  }
}

AsyncRuntime performs one asynchronous read and a continuous Flow.Publisher read, cancelling waits through interruption.

import android.content.Context;
import com.qnbot.sdk.Sdk;
import com.qnbot.sdk.SdkConfig;
import com.qnbot.sdk.android.SerialTransport;
import com.qnbot.sdk.channel.ReadChannel;
import com.qnbot.sdk.channel.Sample;
import com.qnbot.sdk.config.DeviceSelector;
import com.qnbot.sdk.config.SerialConnection;
import com.qnbot.sdk.config.Side;
import com.qnbot.sdk.config.TargetAlgorithm;
import com.qnbot.sdk.config.TargetConfig;
import com.qnbot.sdk.glove.Glove;
import com.qnbot.sdk.glove.GloveConfig;
import com.qnbot.sdk.glove.GloveDevice;
import com.qnbot.sdk.glove.HandJointCommand;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Flow;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Reads one retargeted sample with next(), then a bounded Flow stream.
 *
 * <p>Pass the host {@link Context}, an authorized transport, the glove port and side, the installed
 * algorithm package, and a positive sample count. The SDK background thread advances work; the
 * caller awaits the asynchronous reads and runner termination, then requests stop and joins during
 * cleanup. Interrupting the worker cancels the wait.
 */
public final class AsyncRuntime {
  private AsyncRuntime() {}

  /** Waits for either side; a failed runner stays the primary error. */
  private static void await(CompletableFuture<?> result, CompletableFuture<Void> runner)
      throws Exception {
    try {
      CompletableFuture.anyOf(result, runner).get();
    } catch (ExecutionException error) {
      if (runner.isCompletedExceptionally())
        runner.get();
      throw error;
    }
  }

  public static void run(Context context, SerialTransport transport, String port, Side side,
      String packageId, int samples) throws Exception {
    if (samples <= 0)
      throw new IllegalArgumentException("samples must be positive");
    SdkConfig config = SdkConfig.builder()
        .device(GloveConfig.builder()
                    .name("primary")
                    .side(side)
                    .connection(SerialConnection.port(port))
                    .build())
        .target(TargetConfig.builder()
                    .name("openxr_hand")
                    .side(side)
                    .source(new DeviceSelector("glove", "primary", side))
                    .algorithm(new TargetAlgorithm(packageId))
                    .build())
        .build();
    try (Sdk sdk = new Sdk(config, context, transport); Glove glove = sdk.glove()) {
      GloveDevice device = glove.device();
      ReadChannel<HandJointCommand> output = device.output("openxr_hand");
      CompletableFuture<Void> streamed = new CompletableFuture<>();
      AtomicReference<Flow.Subscription> active = new AtomicReference<>();
      var subscriber = new Flow.Subscriber<Sample<HandJointCommand>>() {
        private Flow.Subscription subscription;
        private int received;

        @Override
        public void onSubscribe(Flow.Subscription subscription) {
          this.subscription = subscription;
          active.set(subscription);
          subscription.request(1);
        }

        @Override
        public void onNext(Sample<HandJointCommand> sample) {
          try {
            System.out.println("stream retargeting sequence=" + sample.sequence
                + " target=" + sample.value.target + " joints=" + sample.value.joints);
            if (++received == samples)
              streamed.complete(null);
            else
              subscription.request(1);
          } catch (RuntimeException error) {
            streamed.completeExceptionally(error);
          }
        }

        @Override
        public void onError(Throwable error) {
          streamed.completeExceptionally(error);
        }

        @Override
        public void onComplete() {
          streamed.complete(null);
        }
      };
      glove.start();
      glove.runBackground();
      CompletableFuture<Void> runner = CompletableFuture.runAsync(glove::join);
      CompletableFuture<Sample<HandJointCommand>> next = output.next().toCompletableFuture();
      try {
        await(next, runner);
        if (runner.isCompletedExceptionally())
          runner.get();
        if (!next.isDone())
          throw new IllegalStateException("Background run ended before the first output sample");
        Sample<HandJointCommand> first = next.get();
        System.out.println("next retargeting sequence=" + first.sequence
            + " target=" + first.value.target + " joints=" + first.value.joints);

        output.publisher().subscribe(subscriber);
        await(streamed, runner);
        if (runner.isCompletedExceptionally())
          runner.get();
        if (!streamed.isDone())
          throw new IllegalStateException(
              "Background run ended before output consumption finished");
        streamed.get();
      } finally {
        next.cancel(false);
        Flow.Subscription subscription = active.get();
        if (subscription != null)
          subscription.cancel();
        // Stop only while the background join is still running, then observe its result.
        if (!runner.isDone())
          glove.requestStop();
        runner.join();
      }
    }
  }
}

External frames

For custom input or operation without a physical glove, set GloveConfig.connection to ExternalConnection.INSTANCE, configure and select the device, then call device.pushFrame(frame). See Capture for the page-level explanation of prompts and confirmation.

ExternalInputManualUpdate pushes app-owned frames and advances manually, handling capture prompts inside the frame loop:

import android.content.Context;
import com.qnbot.sdk.Sdk;
import com.qnbot.sdk.SdkConfig;
import com.qnbot.sdk.SleepResult;
import com.qnbot.sdk.android.SerialTransport;
import com.qnbot.sdk.channel.ReadChannel;
import com.qnbot.sdk.config.AlgorithmsConfig;
import com.qnbot.sdk.config.DeviceSelector;
import com.qnbot.sdk.config.Side;
import com.qnbot.sdk.config.TargetAlgorithm;
import com.qnbot.sdk.config.TargetConfig;
import com.qnbot.sdk.glove.ExternalConnection;
import com.qnbot.sdk.glove.ExternalGloveFrame;
import com.qnbot.sdk.glove.Glove;
import com.qnbot.sdk.glove.GloveConfig;
import com.qnbot.sdk.glove.GloveDevice;
import com.qnbot.sdk.glove.GloveNodePose;
import com.qnbot.sdk.glove.calibration.CalibrationJobState;
import com.qnbot.sdk.glove.calibration.CalibrationProgress;
import com.qnbot.sdk.glove.capture.CaptureConfig;
import com.qnbot.sdk.glove.capture.CaptureControl;
import com.qnbot.sdk.glove.capture.CaptureInteractionMode;
import com.qnbot.sdk.glove.capture.CaptureProgress;
import com.qnbot.sdk.glove.capture.CaptureSessionState;
import com.qnbot.sdk.glove.capture.CaptureStageState;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Pushes application-owned glove frames while the caller advances the SDK manually, then prints
 * the first retargeting output.
 *
 * <p>Supply the Android Context, transport, side, package ID, Capture interaction and confirm
 * callback. Pass null frames for the built-in synthetic input; the loop ends after 60 seconds,
 * on cancellation, or when the frame supplier returns null.
 */
public final class ExternalInputManualUpdate {
  private ExternalInputManualUpdate() {}

  /**
   * confirm must return promptly: true confirms the displayed action, false leaves it pending.
   * cancelled stops the loop before output is published; both callbacks run on the caller thread.
   */
  public static void run(Context context, SerialTransport transport, Side side, String packageId,
      CaptureConfig captureConfig, Supplier<ExternalGloveFrame> frames, Predicate<String> confirm,
      BooleanSupplier cancelled) throws Exception {
    SdkConfig config = SdkConfig.builder()
                           .device(GloveConfig.builder()
                                       .name("primary")
                                       .side(side)
                                       .connection(ExternalConnection.INSTANCE)
                                       .build())
                           .algorithms(new AlgorithmsConfig(null, captureConfig))
                           .target(TargetConfig.builder()
                                       .name("openxr_hand")
                                       .side(side)
                                       .source(new DeviceSelector("glove", "primary", side))
                                       .algorithm(new TargetAlgorithm(packageId))
                                       .build())
                           .build();
    try (Sdk sdk = new Sdk(config, context, transport); Glove glove = sdk.glove()) {
      GloveDevice device = glove.device();
      var output = device.output("openxr_hand");
      ReadChannel<CaptureProgress> captureProgress = device.captureProgress();
      ReadChannel<CalibrationProgress> calibrationProgress =
          device.calibrationProgress("openxr_hand");
      CaptureControl captureControl = device.captureControl();
      Set<String> handledRequestIds = new HashSet<>();
      glove.start();
      long deadline = System.nanoTime() + 60_000_000_000L;
      int step = 1;
      while (!cancelled.getAsBoolean() && System.nanoTime() < deadline
          && output.latest().isEmpty()) {
        failIfPreparationFailed(captureProgress, calibrationProgress);
        ExternalGloveFrame input = frames == null ? frame(step++) : frames.get();
        if (input == null) {
          break;
        }
        device.pushFrame(input);
        var update = glove.update();
        if (captureConfig.interaction == CaptureInteractionMode.EXTERNAL) {
          handleCapturePrompt(captureProgress, captureControl, handledRequestIds, confirm,
              device.name());
        }
        if (!update.hasNextTask) {
          Thread.sleep(10);
        } else if (update.sleep() == SleepResult.STOPPED) {
          break;
        }
      }
      if (cancelled.getAsBoolean()) {
        return;
      }
      var sample = output.latest().orElseThrow(
          ()
              -> new IllegalStateException("External input did not publish retargeting output "
                  + "before input ended or timed out"));
      System.out.println("latest retargeting output sequence=" + sample.sequence
          + " target=" + sample.value.target + " joints=" + sample.value.joints);
    }
    System.out.println("external manual input complete");
  }

  private static void failIfPreparationFailed(ReadChannel<CaptureProgress> captureProgress,
      ReadChannel<CalibrationProgress> calibrationProgress) {
    captureProgress.latest().ifPresent(sample -> {
      var progress = sample.value;
      if (progress.sessionState == CaptureSessionState.FAILED
          || progress.sessionState == CaptureSessionState.CANCELLED) {
        throw new IllegalStateException(
            progress.failure == null ? "Capture stopped" : progress.failure.message);
      }
    });
    calibrationProgress.latest().ifPresent(sample -> {
      if (sample.value.job.state == CalibrationJobState.FAILED) {
        throw new IllegalStateException(sample.value.job.failure == null
                ? "Calibration stopped"
                : sample.value.job.failure.message);
      }
    });
  }

  private static void handleCapturePrompt(ReadChannel<CaptureProgress> captureProgress,
      CaptureControl captureControl, Set<String> handledRequestIds, Predicate<String> confirm,
      String sourceName) {
    captureProgress.latest().ifPresent(sample -> {
      var stage = sample.value.stage;
      if (stage.state == CaptureStageState.AWAITING_CONFIRMATION && stage.requestId != null
          && !handledRequestIds.contains(stage.requestId)
          && confirm.test(sourceName + " " + stage.prompt)) {
        captureControl.confirm(stage.requestId);
        handledRequestIds.add(stage.requestId);
      }
    });
  }

  private static ExternalGloveFrame frame(int step) {
    double offset = step * 0.001;
    return new ExternalGloveFrame(node(0.01 + offset, 0.02, 0.03), node(0.02 + offset, 0.03, 0.04),
        node(0.03 + offset, 0.04, 0.05), node(0.04 + offset, 0.05, 0.06),
        node(0.05 + offset, 0.06, 0.07), step * 10.0);
  }

  private static GloveNodePose node(double x, double y, double z) {
    return GloveNodePose.of(List.of(x, y, z), List.of(0.0, 0.0, 0.0, 1.0));
  }
}

ExternalInputRunBackground advances with the SDK background runtime and reuses the same prompt handling:

import android.content.Context;
import com.qnbot.sdk.Sdk;
import com.qnbot.sdk.SdkConfig;
import com.qnbot.sdk.android.SerialTransport;
import com.qnbot.sdk.channel.ReadChannel;
import com.qnbot.sdk.config.AlgorithmsConfig;
import com.qnbot.sdk.config.DeviceSelector;
import com.qnbot.sdk.config.Side;
import com.qnbot.sdk.config.TargetAlgorithm;
import com.qnbot.sdk.config.TargetConfig;
import com.qnbot.sdk.glove.ExternalConnection;
import com.qnbot.sdk.glove.ExternalGloveFrame;
import com.qnbot.sdk.glove.Glove;
import com.qnbot.sdk.glove.GloveConfig;
import com.qnbot.sdk.glove.GloveDevice;
import com.qnbot.sdk.glove.GloveNodePose;
import com.qnbot.sdk.glove.calibration.CalibrationJobState;
import com.qnbot.sdk.glove.calibration.CalibrationProgress;
import com.qnbot.sdk.glove.capture.CaptureConfig;
import com.qnbot.sdk.glove.capture.CaptureControl;
import com.qnbot.sdk.glove.capture.CaptureInteractionMode;
import com.qnbot.sdk.glove.capture.CaptureProgress;
import com.qnbot.sdk.glove.capture.CaptureSessionState;
import com.qnbot.sdk.glove.capture.CaptureStageState;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Pushes application-owned glove frames while the SDK runs in the background, then prints the
 * first retargeting output.
 *
 * <p>Supply the Android Context, transport, side, package ID, Capture interaction and confirm
 * callback. Pass null frames for the built-in synthetic input; the loop ends after 60 seconds,
 * on cancellation, or when the frame supplier returns null.
 */
public final class ExternalInputRunBackground {
  private ExternalInputRunBackground() {}

  /**
   * confirm must return promptly: true confirms the displayed action, false leaves it pending.
   * cancelled stops the frame loop; both callbacks run on the caller thread.
   */
  public static void run(Context context, SerialTransport transport, Side side, String packageId,
      CaptureConfig captureConfig, Supplier<ExternalGloveFrame> frames, Predicate<String> confirm,
      BooleanSupplier cancelled) throws Exception {
    SdkConfig config = SdkConfig.builder()
                           .device(GloveConfig.builder()
                                       .name("primary")
                                       .side(side)
                                       .connection(ExternalConnection.INSTANCE)
                                       .build())
                           .algorithms(new AlgorithmsConfig(null, captureConfig))
                           .target(TargetConfig.builder()
                                       .name("openxr_hand")
                                       .side(side)
                                       .source(new DeviceSelector("glove", "primary", side))
                                       .algorithm(new TargetAlgorithm(packageId))
                                       .build())
                           .build();
    try (Sdk sdk = new Sdk(config, context, transport); Glove glove = sdk.glove()) {
      GloveDevice device = glove.device();
      var output = device.output("openxr_hand");
      ReadChannel<CaptureProgress> captureProgress = device.captureProgress();
      ReadChannel<CalibrationProgress> calibrationProgress =
          device.calibrationProgress("openxr_hand");
      CaptureControl captureControl = device.captureControl();
      Set<String> handledRequestIds = new HashSet<>();
      glove.start();
      glove.runBackground();
      try {
        long deadline = System.nanoTime() + 60_000_000_000L;
        int step = 1;
        while (!cancelled.getAsBoolean() && System.nanoTime() < deadline
            && output.latest().isEmpty()) {
          failIfPreparationFailed(captureProgress, calibrationProgress);
          ExternalGloveFrame input = frames == null ? frame(step++) : frames.get();
          if (input == null) {
            break;
          }
          device.pushFrame(input);
          if (captureConfig.interaction == CaptureInteractionMode.EXTERNAL) {
            handleCapturePrompt(captureProgress, captureControl, handledRequestIds, confirm,
                device.name());
          }
          Thread.sleep(10);
        }
        if (cancelled.getAsBoolean()) {
          return;
        }
        var sample = output.latest().orElseThrow(
            ()
                -> new IllegalStateException("External input did not publish retargeting output "
                    + "before input ended or timed out"));
        System.out.println("latest retargeting output sequence=" + sample.sequence);
      } finally {
        glove.requestStop();
        glove.join();
      }
    }
    System.out.println("external background input complete");
  }

  private static void failIfPreparationFailed(ReadChannel<CaptureProgress> captureProgress,
      ReadChannel<CalibrationProgress> calibrationProgress) {
    captureProgress.latest().ifPresent(sample -> {
      var progress = sample.value;
      if (progress.sessionState == CaptureSessionState.FAILED
          || progress.sessionState == CaptureSessionState.CANCELLED) {
        throw new IllegalStateException(
            progress.failure == null ? "Capture stopped" : progress.failure.message);
      }
    });
    calibrationProgress.latest().ifPresent(sample -> {
      if (sample.value.job.state == CalibrationJobState.FAILED) {
        throw new IllegalStateException(sample.value.job.failure == null
                ? "Calibration stopped"
                : sample.value.job.failure.message);
      }
    });
  }

  private static void handleCapturePrompt(ReadChannel<CaptureProgress> captureProgress,
      CaptureControl captureControl, Set<String> handledRequestIds, Predicate<String> confirm,
      String sourceName) {
    captureProgress.latest().ifPresent(sample -> {
      var stage = sample.value.stage;
      if (stage.state == CaptureStageState.AWAITING_CONFIRMATION && stage.requestId != null
          && !handledRequestIds.contains(stage.requestId)
          && confirm.test(sourceName + " " + stage.prompt)) {
        captureControl.confirm(stage.requestId);
        handledRequestIds.add(stage.requestId);
      }
    });
  }

  private static ExternalGloveFrame frame(int step) {
    double offset = step * 0.001;
    return new ExternalGloveFrame(node(0.01 + offset, 0.02, 0.03), node(0.02 + offset, 0.03, 0.04),
        node(0.03 + offset, 0.04, 0.05), node(0.04 + offset, 0.05, 0.06),
        node(0.05 + offset, 0.06, 0.07), step * 10.0);
  }

  private static GloveNodePose node(double x, double y, double z) {
    return GloveNodePose.of(List.of(x, y, z), List.of(0.0, 0.0, 0.0, 1.0));
  }
}

ExternalGloveFrame requires thumb, index, middle, ring and pinky GloveNodePose values with three-dimensional positions and four-dimensional xyzw quaternions. Quaternions must not be all zero. Optional timestampMs must be finite when present. Construct each finger with GloveNodePose.of(position, quaternionXyzw).

In manual mode, submit input and advance with update(). Supply external frames from another thread while this loop runs; NO_TASKS does not mean external input or calibration is complete. In background mode, keep the background loop running and do not also call update().