1

I have code for an android app within android studio to run a method after a 1 second delay:

    new java.util.Timer().schedule(
            new java.util.TimerTask() {
                @Override
                public void run() {
                    loginClicked();
                }
            },
            1000
    );

However, it produces this error every time it executes:

java.lang.IllegalThreadStateException: A Looper must be associated with this thread.

I've basically grabbed it from this, so I don't really know what's up.

compsciman
  • 349
  • 3
  • 17

1 Answers1

2

You better to use Handler on Android at these situations.

TimerTask is pure java and you can see the differences & the other important info in here: https://stackoverflow.com/a/40339630/4409113

Some of reported problems with TimerTask include:

  • Can't update the UI thread
  • Memory leaks
  • Unreliable (doesn't always work)
  • Long running tasks can interfere with the next scheduled event

However, you can use the following codes:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //Do your things after 1000ms
     loginClicked();
  }
}, 1000);
ʍѳђઽ૯ท
  • 16,646
  • 7
  • 53
  • 108