How to add time delay in java code in android

mremremre1 picture mremremre1 · Aug 19, 2013 · Viewed 9.6k times · Source

I am making an app and i want to add time delay to my code to make to delay an action . Is there something that you can set the delay in millis ? Please help.

I want to do something like :

for(int i=1;i<100;i++){
     Delay(1000); // I want to add a delay so that this wont happend instanlty
     Matrix matrix=new Matrix();
     matrix.postRotate((float) angle2,width, height);
     image.setImageMatrix(matrix);

Calling Thread.sleep() is causing ANR Is there something like the timers in Visual Basic in android ? Timer in vb is an element that runs seperatly from the main program an causes an event whose frequency is set by user.

Answer

William Morrison picture William Morrison · Aug 19, 2013

Thread.sleep in a separate thread would do that.

If you're not making use of AsyncTask for other things use that instead. It will simplify things for you. AsyncTask will make use of a a threadpool, so you needn't worry about creating a thread yourself.

Be sure not to sleep in an event callback for a button or equivalent as you'll be sleeping on the UI thread. That will make your app appear unresponsive and sluggish. Only sleep in some other thread, and invoke back to UI to update.

Edit based on updated Question:

Looks like you're performing some animation on the UI. A separate thread would be best for this as it looks to be a long running process.