Run Callback On Main Thread

29,921

Solution 1

As long as you have a Context, you can do something like this:

Handler mainHandler = new Handler(context.getMainLooper());

And to run code on UI thread:

mainHandler.post(new Runnable() {

    @Override
    public void run() {
        // run code
    }
});

As suggested by kaka:

You could also use the static Looper.getMainLooper() which

Returns the application's main looper, which lives in the main thread of the application.

Solution 2

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        //execute code on main thread
    }
});

Solution 3

In C++:

Director::getInstance()->getScheduler()->performFunctionInCocosThread([]{
    // execute code on main thread
});
Share:
29,921
James Campbell
Author by

James Campbell

 Wizard for supmenow.com Co-Founder hackcancer.co. Loves changing the world and making people's lives better.

Updated on July 19, 2022

Comments

  • James Campbell
    James Campbell almost 2 years

    I have some code that interacts with the Android Facebook SDK, Asynchronously. Unfortunately this means when it returns it is in a background thread.

    Cocos-2dx prefers me to interact with it in the Main Thread, especially when doing things like telling the Director to switch scenes (As it involves Open GL)

    Is there any way to get some code to run on the Main thread ?