Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

If you want to hold up the entire thread- sleep. But do not do this on the main thread, as it will freeze the UI of your app/the phone.

If you want to do something in the future but not hold up the app, for a few seconds you can post a delayed message to a Handler.

If you want to do something in the more distant future, set an alarm via AlarmManager.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top