1

I have followed this tutorial to launch a url on android through jni call. It runs successfully.
In the same way I want to display a toast message from my cocos2dx layer like this:

public static void openURL(String url) {
  Toast.makeText(me,url,Toast.LENGTH_LONG).show();
}

But its crashing with error: Can't create handler with thread. Do you know how can I display it correctly?

Keppil
  • 45,603
  • 8
  • 97
  • 119
  • maybe [this post](http://stackoverflow.com/questions/3614663/cant-create-handler-inside-thread-that-has-not-called-looper-prepare-inside-a) could help you. – cosmincalistru Jul 23 '12 at 07:22

3 Answers3

2

Try below code this will definately work for you.

  • First Create one Runnable interface in your class file like this,

    Runnable runnable = new Runnable() {    
    
    @Override
    
    public void run() {
     // TODO Auto-generated method stub
    Toast.makeText(MainActivity.this, "Your url string...",Toast.LENGTH_SHORT).show();
    }};
    
  • Then create one Handler object and call that runnable interface like below,

    Create Handler object like,
    
    Handler handler;
    
    initialize it like,
    
    onCreate(){
        .................
        handler = new Handler();
        .................
    }
    
    then call runnable whenever you want like,
    
    handler.post(runnable);
    
0

You can't run UI stuffs on a background thread. You should use an AsyncTask and put that code in the on pre/post execute or if your just displaying a toast you can run it on the UI thread

runOnUiThread(new Runnable() {
}
Slickelito
  • 1,786
  • 20
  • 28
0

So this was from 2012.

I guess not a lot people use cocos2d-x. Ok this how you do this on cocos2d-x.

Edit the AppActivity.java

    public class AppActivity extends Cocos2dxActivity
    {
    private Activity activity;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.activity = this;
        showToast();
    }

    public void showToast()
    {
        activity.runOnUiThread(new Runnable()
        {

            @Override
            public void run()
            {
                // TODO Auto-generated method stub
                Toast.makeText(activity, "Hello :D", 10).show();
            }
        });
    }

    }

This works very nice in cocos2d-x version 3.x I test it. Of course JNI just will call the method and this must work.

OscarLeif
  • 894
  • 1
  • 9
  • 17