Run Callback On Main Thread
Asked Answered
P

4

24

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 ?

Pergolesi answered 14/10, 2013 at 18:2 Comment(0)
A
54

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.

Alkali answered 14/10, 2013 at 18:37 Comment(8)
You could also use the static Looper.getMainLooper() which "Returns the application's main looper, which lives in the main thread of the application.".Shayne
@Shayne Cool, did not know that, it has now been added to the answer :)Alkali
post doesn't exists anymore.Cinderella
@PredragManojlovic any reference? According to the documentation it does developer.android.com/reference/android/os/…Alkali
@Alkali My mistake. There is also Handler in another package so I've made wrong import. Up-voting this.Cinderella
@PredragManojlovic alright :) but thanks for the heads up anyways, if it was the case an update of the answer would be required.Alkali
@fnc12 I think it may be easier to have the Java code return control to cocos2d-x on the main thread rather than try to jump onto the main thread in C++Pergolesi
Perfect answer!Custos
S
12
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        //execute code on main thread
    }
});
Sandisandidge answered 14/10, 2013 at 18:47 Comment(1)
Also true but runOnUiThread is only available within Activity and Fragment classesAlkali
S
5

In C++:

Director::getInstance()->getScheduler()->performFunctionInCocosThread([]{
    // execute code on main thread
});
Submediant answered 31/7, 2015 at 9:22 Comment(0)
S
3

You can run code in the main thread in this 2 ways: (with Java 8's lambdas)

If you have an activity instance:

activity.runOnUiThread(() -> {
     // do your work on main thread
});

Otherwise use an Handler object and post a Runnable.

You can use the postDelayed version if you need some delay before executing the code.

 Handler handler = new Handler(Looper.getMainLooper());
 handler.post(() -> {
     // do your work on main thread
 });
Soloman answered 11/1, 2019 at 19:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.