Using toast inside timertask

前端 未结 4 640
迷失自我
迷失自我 2021-01-20 08:35

Found someone has similar issue online here.

This doesn\'t work:

Timer t = new Timer(false);
t.schedule(new TimerTask() {
@Override
public void run()         


        
相关标签:
4条回答
  • 2021-01-20 09:10

    Everytime you start an application, it starts on the UI Thread (also called the Main Thread).

    Whenever you create a new Thread, or Timer, or AsyncTask, by definition, they're creating new Threads. Threads that aren't the main thread simply don't have permission to modify the UI.

    0 讨论(0)
  • 2021-01-20 09:20

    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);
    
    0 讨论(0)
  • 2021-01-20 09:23

    Toast use on UIThread. You can by Handler or runOnUiThread

    0 讨论(0)
  • 2021-01-20 09:31

    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);
    
    0 讨论(0)
提交回复
热议问题