Launch Android Intent from Libgdx render method

断了今生、忘了曾经 提交于 2019-12-11 19:22:41

问题


I'm trying to launch an Intent from the render method in libgdx but I am getting a "Can't create handler inside thread that has not called Looper.prepare()" error.

I have implemented the Interface from here http://code.google.com/p/libgdx-users/wiki/IntegratingAndroidNativeUiElements3TierProjectSetup

I have used the Toast implementaion and that works okay.

This is my Android implementation

 @Override
public void launchPlayerRoom() {
    Intent intent = new Intent(appContext, RoomViewActivity.class);
    intent.putExtras(selectPlayerRoom());
    startActivity(intent);
}

and calling from Libgdx render

if (health_amount <= 0){
            actionResolver.launchPlayerRoom();
        }

The Intent needs to be called from render as it depends on a value that is decremented in render. I understand that the problem is calling a UI thread from a render thread(I think!) but I don't know how to solve it. I have tried from this post Can't create handler inside thread that has not called Looper.prepare()

 @Override
public void launchPlayerRoom() {
    final Intent intent = new Intent(appContext, RoomViewActivity.class);
    intent.putExtras(selectPlayerRoom());
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            startActivity(intent);
        }
    });

But this makes no difference.

Any help would be most appreciated.


回答1:


The Libgdx "render" thread is not the Android "UI" thread, so when you invoke code in the Android back-end that requires the Android UI thread context you have to jump through some hoops.

In general, the solution is to create a Handler in the context of the UI thread and then post Runnables to that object. This is what the wiki page on integrating android UI elements is doing.

If you have the Toast implementation working correctly, then the Intent code should also work (both have the same requirement to be run on the Android UI thread context).

Perhaps there is some other problem with the Handler you're creating (is it not being created during the Libgdx create callback? (Its implicitly associated with the thread that created it.) Or are you invoking this code too early in your setup? A full backtrace might provide more details.




回答2:


I have now got it sorted. It turned out I needed to interrupt the render thread then I could launch the intent. I changed implementaion slightly as I call an AlertDialog and launch the intent from there. I have accepted the answer as it got me thinking along the right lines.



来源:https://stackoverflow.com/questions/18854050/launch-android-intent-from-libgdx-render-method

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