Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using toast inside timertask

Tags:

android

Found someone has similar issue online here.

This doesn't work:

Timer t = new Timer(false);
t.schedule(new TimerTask() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "msg", Toast.LENGTH_LONG).show();
}
}, 5000);

But if I instantiate the toast outside the timertask then show it inside run,it works.

I think it may relate to the so-called UI thread,

but how exactly ?

like image 474
new_perl Avatar asked Feb 18 '26 01:02

new_perl


2 Answers

try this

Timer t = new Timer(false);
t.schedule(new TimerTask() {
@Override
public void run() {
       runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(), "msg", Toast.LENGTH_LONG).show();
            }
        });

    }
}, 5000);
like image 117
silly Avatar answered Feb 19 '26 14:02

silly


Using Timer starts a new thread, I suppose that thread does not have access to getApplicationContext. The proper way to do it is to use Handler and call the postDelayed method of the Handler - which does not start a new thread.

Read about this: http://developer.android.com/resources/articles/timed-ui-updates.html

The link you posted has a working example, which is the proper way to do it:

final Context ctx = this;
Handler mHandler = new Handler();

Runnable
makeToast = new Runnable() {
    public void run() {
        Toast.makeText(ctx, "msg", Toast.LENGTH_LONG).show();
    }
};
mHandler.postDelayed(makeToast, 1000);
like image 35
Simon Forsberg Avatar answered Feb 19 '26 13:02

Simon Forsberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!