Run Callback On Main Thread

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-29 05:30:37
cYrixmorten

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.

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

In C++:

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

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