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 ?

James Campbell
  • 3,511
  • 4
  • 33
  • 50

4 Answers4

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.

Community
  • 1
  • 1
cYrixmorten
  • 7,110
  • 3
  • 25
  • 33
12
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        //execute code on main thread
    }
});
Lefteris
  • 14,550
  • 2
  • 56
  • 95
5

In C++:

Director::getInstance()->getScheduler()->performFunctionInCocosThread([]{
    // execute code on main thread
});
Dmytro
  • 1,290
  • 17
  • 21
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
 });
Domenico
  • 1,331
  • 18
  • 22