Question

Is there any way to call an activity from something that doesnt extend Activity? without running it on UI-tread. I want toast-messages in my game, like in candy crush. But I have no idea how to call the toast-activity in an efficient way during real-time.

I know you can use context and get activity from that but it does not run very smoothly. Does anyone have experience with how to do this?

Was it helpful?

Solution

Toasts as well as other components that manipulates the user interface must not be used outside of the UI thread.

What you could do in order to solve your issue, is to design a messaging system between the thread managing you game, and your UI thread. In order to do so, you can use a Handler and its messaging facilities (sendMessage, post, postDelayed ...) to send messages or even Runnables to be run on your main thread.

If you create a Handler in the main thread, it will automatically associate itself with your main thread's event loop, thus making every work sent to it be executed in the main thread.

A basic example of what you could do would be :

class MainActivity extends Activity {

    // The handler is associated with your Activity's thread
    private Handler _handler = new Handler();
    // ...

    private Thread _worker = new Thread() {

        @Override
        public void run() {
          _handler.post(new Runnable() {
             @Override
             public void run() {
                Toast.makeText(MainActivity.this, "Some text", Toast.LENGTH_SHORT).show();
             }
          });
        }
    };
};

As a shorthand, you could also use Activity.runOnUiThread(Runnable r) that executes the given runnable in the UI thread by default.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top