Run Callback On Main Thread

蓝咒 提交于 2019-11-27 23:22:50

问题


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 ?


回答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.




回答2:


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



回答3:


In C++:

Director::getInstance()->getScheduler()->performFunctionInCocosThread([]{
    // execute code on main thread
});



回答4:


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
 });


来源:https://stackoverflow.com/questions/19366301/run-callback-on-main-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!