在主线程上运行回调

问题描述 投票:22回答:4

我有一些与Android Facebook SDK交互的代码,异步。不幸的是,这意味着当它返回时它在后台线程中。

Cocos-2dx更喜欢我在主线程中与它进行交互,特别是当告诉Director切换场景时(因为它涉及Open GL)

有没有办法让一些代码在主线程上运行?

android cocos2d-x
4个回答
49
投票

只要你有一个Context,就可以这样做:

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

并在UI线程上运行代码:

mainHandler.post(new Runnable() {

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

正如kaka所建议的那样:

你也可以使用静态Looper.getMainLooper()

返回应用程序的主循环器,它位于应用程序的主线程中。


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

5
投票

在C ++中:

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

0
投票

您可以通过以下两种方式在主线程中运行代码:(使用Java 8的lambdas)

如果您有活动实例:

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

否则使用Handler对象并发布Runnable。

如果在执行代码之前需要一些延迟,可以使用postDelayed版本。

 Handler handler = new Handler(Looper.getMainLooper());
 handler.post(() -> {
     // do your work on main thread
 });
© www.soinside.com 2019 - 2024. All rights reserved.