简体   繁体   中英

Launch Android Intent from Libgdx render method

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM