Search code examples
androidmultithreadingmyo

How to run Myo SDK Listener in specific thread


I am developing Smart Home control application which uses Myo armband. I am using their SDK, but I run on problem which I am not sure how to solve.

I have Background Service, which is listening for Myo poses, but even the SDK and the Device Listener is initialized inside background thread, its events (for example onPose) are raised inside main thread.

Is there any way how to force the SDK to raise events on that Background thread?

Service code:

    public class ListeningService extends Service {

    @Override
    public void onCreate() {
        HandlerThread thread = new HandlerThread("MyoListener",
                Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper, this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {   
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        mServiceHandler.sendMessage(msg);

        return START_STICKY;
    }

    private final class ServiceHandler extends Handler {

        private Context context;

        public ServiceHandler(Looper looper, Context context) {
            super(looper);
            this.context = context;
        }

        @Override
        public void handleMessage(Message msg) {
            Hub hub = Hub.getInstance();
            if (!hub.init(context, getPackageName())) {
                showToast("Couldn't initialize Hub");
                stopSelf();
                return;
            }

            mListener = new MyoListener(context);
            hub.addListener(mListener);
        }
    }
}

Solution

  • Hmm so I found out what was the issue.

    If you want to specify on which Thread your Listener should run, you have to initialize the Hub on that Thread (for completely first time in run time of the app).

    I was using ScanActivity for connecting Myo and I had it in UI part of app (which is running in Main thread) and since before you use ScanActivity you have to initialize Hub, I had it initialized in Main thread first and therefore the Listener events were raised also in Main thread...