Run in "background" thread (not in main thread)?

I have this in my extension code:

  public KeyPressEvent(ComponentContainer container) {
    super(container.$form());
  }
  @SimpleFunction( description = "key event code input")
  public void KeyEventEscape() {
    Instrumentation inst = new Instrumentation();
    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_ESCAPE);
  }

builds OK, but I get an error telling me it cannot run in the main thread. How do I fix this ?

Also, how do I set a variable for where "KEYCODE_ESCAPE" is, my IDE won't allow it ?

    new Thread(new Runnable() {
      @Override
      public void run() {
        // your code here
      }
    }).start();
1 Like

Why dosent it allow it? What error you get? I suppose it is an Int.

I will try as an int, I tried it as a string....

1 Like

Not working either:

image

I dont get what you are trying to do with it?

Are you trying to pass a dynamic non-constant value for inst.sendKeyDownUpSync()

Yes, so I can pass any "KEYCODE" from the method block

1 Like

Back to first question, like so ?

  public KeyPressEvent(ComponentContainer container) {
    super(container.$form());
  }

  @SimpleFunction(description = "key event code input")
  public void KeyEventEscape() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        Instrumentation inst = new Instrumentation();
        inst.sendKeyDownUpSync(KeyEvent.KEYCODE_ESCAPE);
      }
    }).start();
  }
}

1 Like
@SimpleFunction( description = "key event code input")
  public void KeyEventEscape() {
    Instrumentation inst = new Instrumentation();
    try {
      Field field = KeyEvent.class.getField("KEYCODE_ANY_HERE");
      int value = (int) field.get(null); // its a static reference
      inst.sendKeyDownUpSync(value);
    } catch (NoSuchFieldException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      // do not merge, java 6+
      throw new RuntimeException(e);
    }
  }

OK I see, what about the background thread ?

  @SimpleFunction( description = "key event code input")
  public void KeyEventEscape() {
    final int value;
    try {
      Field field = KeyEvent.class.getField("KEYCODE_ANY_HERE");
      value = (int) field.get(null); // its a static reference
    } catch (NoSuchFieldException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      // do not merge, java 6+
      throw new RuntimeException(e);
    }
    
    new Thread(new Runnable() {
      @Override
      public void run() {
        Instrumentation inst = new Instrumentation();
        inst.sendKeyDownUpSync(value);
      }
    }).start();
  }
1 Like

Many thanks, I have have learnt a lot in five minutes
:smiley:

Off to test this out....

1 Like

hmmm, crashes companion on testing, will try compiled.....

Send me the apk in pm

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.