Gio.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // SPDX-License-Identifier: Unlicense OR MIT
  2. package org.gioui;
  3. import android.content.ClipboardManager;
  4. import android.content.ClipData;
  5. import android.content.Context;
  6. import android.os.Handler;
  7. import android.os.Looper;
  8. import java.io.UnsupportedEncodingException;
  9. public final class Gio {
  10. private static final Object initLock = new Object();
  11. private static boolean jniLoaded;
  12. private static final Handler handler = new Handler(Looper.getMainLooper());
  13. /**
  14. * init loads and initializes the Go native library and runs
  15. * the Go main function.
  16. *
  17. * It is exported for use by Android apps that need to run Go code
  18. * outside the lifecycle of the Gio activity.
  19. */
  20. public static synchronized void init(Context appCtx) {
  21. synchronized (initLock) {
  22. if (jniLoaded) {
  23. return;
  24. }
  25. String dataDir = appCtx.getFilesDir().getAbsolutePath();
  26. byte[] dataDirUTF8;
  27. try {
  28. dataDirUTF8 = dataDir.getBytes("UTF-8");
  29. } catch (UnsupportedEncodingException e) {
  30. throw new RuntimeException(e);
  31. }
  32. System.loadLibrary("gio");
  33. runGoMain(dataDirUTF8, appCtx);
  34. jniLoaded = true;
  35. }
  36. }
  37. static private native void runGoMain(byte[] dataDir, Context context);
  38. static void writeClipboard(Context ctx, String s) {
  39. ClipboardManager m = (ClipboardManager)ctx.getSystemService(Context.CLIPBOARD_SERVICE);
  40. m.setPrimaryClip(ClipData.newPlainText(null, s));
  41. }
  42. static String readClipboard(Context ctx) {
  43. ClipboardManager m = (ClipboardManager)ctx.getSystemService(Context.CLIPBOARD_SERVICE);
  44. ClipData c = m.getPrimaryClip();
  45. if (c == null || c.getItemCount() < 1) {
  46. return null;
  47. }
  48. return c.getItemAt(0).coerceToText(ctx).toString();
  49. }
  50. static void wakeupMainThread() {
  51. handler.post(new Runnable() {
  52. @Override public void run() {
  53. scheduleMainFuncs();
  54. }
  55. });
  56. }
  57. static private native void scheduleMainFuncs();
  58. }