Java Question Method cannot be called from Main thread

Jim Brown

Active Member
Licensed User
Longtime User
I was hoping to create a small library which sends key strokes and touch input. While the library compiles and the B4a example code runs, as soon as I tried to use the methods I get:

"This method cannot be called from the main thread"

Here is the Java code. Can anyone help with me with regards to the error? I can only assume the code has to be run on another thread but I have got no idea how to do this.
B4X:
package com.android.jim;

import android.app.Instrumentation;
import android.os.SystemClock;
import android.view.MotionEvent;
import anywheresoftware.b4a.BA.ShortName;

@ShortName("SendInput")
public class SendInput {
    Instrumentation m=new Instrumentation();
    /**
    * Send a single keystroke
    */
    public void SendKeyPress(int Keycode){
        m.sendKeyDownUpSync(Keycode);
    }
    /**
    * Send a touch action to location <b>X</b> , <b>Y</b>.
    * <b>Action</b> should be one of the following:
    *        <b>ACTION_DOWN</b>    - Send the touch down action
    *        <b>ACTION_UP</b> - Send the touch up action
    *        <b>ACTION_MOVE</b> - Send the touch move action
    */
    public void SendTouchAction(int Action,float X,float Y){
        final long millis = SystemClock.uptimeMillis();
        m.sendPointerSync(MotionEvent.obtain(millis,millis,Action,X,Y,0));
    }
};
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
You know that you cannot use it with other apps, right?

You can use something like:
B4X:
public void SendTouchAction(final BA ba, final int Action,final float X,final float Y){
ba.submitRunnable(new Runnable() {

               @Override
               public void run() {
  
final long millis = SystemClock.uptimeMillis();
 m.sendPointerSync(MotionEvent.obtain(millis,millis,Action,X,Y,0));
  });
}
 
Top