在主线程上运行回调

Jam*_*ell 22 android cocos2d-x

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

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

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

cYr*_*ten 50

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

Handler mainHandler = new Handler(context.getMainLooper());
Run Code Online (Sandbox Code Playgroud)

并在UI线程上运行代码:

mainHandler.post(new Runnable() {

    @Override
    public void run() {
        // run code
    }
});
Run Code Online (Sandbox Code Playgroud)

正如卡卡所说:

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

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

  • 您还可以使用静态[Looper.getMainLooper()](http://developer.android.com/reference/android/os/Looper.html#getMainLooper()),其中_"返回应用程序的主要循环程序,它位于应用程序的主要线程."_. (7认同)

Lef*_*ris 11

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        //execute code on main thread
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 也是如此,但runOnUiThread仅在Activity和Fragment类中可用 (2认同)

dim*_*4eg 5

在C++中:

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