4

In my Android app I am trying to execute a task every 5 seconds.

I tried doing something like this:

@Override
public void onCreate() {
   //standard initialization code

    letsChange();           //method name

    try{
        wait(1000);
    } catch(Exception e) {
        e.printstackstrace();
    }
}

But I get the following error message:

java.lang.IllegalMonitorStateException: object not locked by thread before wait()

What do I do to stop this?

2

1 Answer 1

2

When you call wait() inside a class, you are actually calling wait() on the current instance of that class. To do that, it requires a lock on that instance. If another thread has the lock, you will not be able to wait.

Adding synchronized to onCreate() will acquire the lock (the current instance of the Activity) and let you call wait() inside, but this is definitely not want you want to do as it will block the main/UI thread and cause your app to be non-responsive.

What you probably want instead is the following inside your activity:

private boolean isTerminationConditionMet = false;

@Override
public void onCreate() {
    //standard Android onCreate code 

    final Handler handler = new Handler();
    final Runnable task = new Runnable() {
        @Override
        public void run() {
            //code you want to run every second
            if (!isTerminationConditionMet()) {
                handler.postDelayed(task, 1000);
            }
        }
    }
    handler.postDelayed(task, 1000);
}

This will cause the code inside run() to be run after the desired delay (1000ms) and then every 1000 ms until your termination condition is met.

2
  • But this thing ll run this code after specific time just for once. I want it to run my code every 5 seconds till i say stop. So can i use for loop for this?
    – g33k
    Commented Nov 4, 2016 at 6:33
  • Well then you can add logic to the Runnable to loop. Something like if (!conditionMet()) handler.postDelayed(....). You will, of course have to make the Handler final to access it from within the Runnable Commented Nov 4, 2016 at 6:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.