How to Have the Code Pause for a Couple of Seconds in Android

How do you have the code pause for a couple of seconds in android?

Learning to think in terms of events is indeed the key here. You can do it. :)

The first rule is: never stall the UI thread. The UI thread is responsible for keeping your app feeling responsive. Any work you do there should not block; do what you need to do and return as quickly as possible. Definitely avoid doing I/O on the UI thread. (There are some places where you can't really help it due to lifecycle requirements, for example saving app state in onPause.) If you ever call Thread.sleep on the UI thread you are doing it wrong.

Android enforces this with the "Application not responding" (or "ANR") error that the user sees. Whenever you see this in an Android app it means the developer did something that caused the UI thread to stall for too long. If the device is really bogged down for some reason this error might not actually be the app developer's fault, but usually it means the app is doing something wrong.

You can use this model to your advantage by posting your own events. This gives you an easy way to tell your app, "do this later." In Android the key to posting your own events is in the Handler class. The method postDelayed lets you schedule a Runnable that will be executed after a certain number of milliseconds.

If you have an Activity that looks something like this:

public class MyActivity extends Activity {
private Handler mHandler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler.postDelayed(new Runnable() {
public void run() {
doStuff();
}
}, 5000);
}

private void doStuff() {
Toast.makeText(this, "Delayed Toast!", Toast.LENGTH_SHORT).show();
}
}

Then 5 seconds after the activity is created you will see the toast created in doStuff.

If you're writing a custom View it's even easier. Views have their own postDelayed method that will get everything posted to the correct Handler and you don't need to create your own.

The second rule is: Views should only be modified on the UI thread. Those exceptions you're getting and ignoring mean something went wrong and if you ignore them your app will probably start misbehaving in interesting ways. If your app does most of its work in other threads you can post events directly to the view you want to modify so that the modifications will run correctly.

If you have a reference to your Activity from that part of your code you can also use Activity#runOnUIThread, which does exactly what the name implies. You might prefer this approach if posting to a single view doesn't really make sense in context.

As for updates to views not appearing until you hit a button, what kind of views are these? Are they custom views that are drawing these updates? If so, are you remembering to call invalidate after data changes to trigger the redraw? Views only redraw themselves after they have been invalidated.

How to delay code execution (draw the path) for few seconds?

A handler would do the job very easily.You won't need a separate thread or AsyncTask().

Use a Handler in your Activity to delay events such as calling the method drawPath() in your case:

private RefreshHandler mRedrawHandler = new RefreshHandler(); 
private RefreshHandler mRedrawHandler = new RefreshHandler();

class RefreshHandler extends Handler {
@Override
public void handleMessage(Message msg) {
drawPath();
}

public void sleep(long delayMillis) {
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
};

In your onCreate() of Activity (or In onClick() of any button, whenever you want to start a delay), call mRedrawHandler.sleep(3000); , drawPath(); is a method where you are starting the draw.

Wait for 5 seconds

just add one-liner with lambda

(new Handler()).postDelayed(this::yourMethod, 5000);

edit for clarification: yourMethod refers to the method which you want to execute after 5000 milliseconds.

Getting App To Wait A Few Seconds Java

The sleep method should work correctly if used in the following way.

Thread.sleep();

The parameter is the time in milliseconds.

For example:

Thread.sleep(5000);
//This pauses or "sleeps" for 5 seconds

How to pause for 5 seconds before drawing the next thing on Android?

Don't wait in onDraw method it's called in the UI thread and you'll block it. Use flags to handle which line will be drawn

boolean shouldDrawSecondLine = false;

public void setDrawSecondLine(boolean flag) {
shouldDrawSecondLine = flag;
}

public void onDraw(Canvas canvas) {
int w = canvas.getWidth();
int h = canvas.getHeight();
canvas.drawLine(w/2, 0, w/2, h-1, paint);
if (shouldDrawSecondLine) {
canvas.drawLine(0, h/2, w-1, h/2, paint);
}
}

Than use it in your code like this

final View view;
// initialize the instance to your view
// when it's drawn the second line will not be drawn

// start async task to wait for 5 second that update the view
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
return null;
}

@Override
protected void onPostExecute(Void result) {
view.setDrawSecondLine(true);
view.invalidate();
// invalidate cause your view to be redrawn it should be called in the UI thread
}
};
task.execute((Void[])null);

How to call a method after a delay in Android

Kotlin

Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
}, 100)

Java

final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);

The class to import is android.os.handler.

Execute function after 5 seconds in Android

You can use the Handler to add some delay.Call the method displayData() as below so that it will be executed after 5 seconds.

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
displayData();
}
}, 5000);

Note : Do not use the threads like Thread.sleep(5000); because it will block your UI and and makes it irresponsive.

How do you tell a function to wait a few seconds in Kotlin?

You can use Handler,

Handler().postDelayed(Runnable { 
//anything you want to start after 3s
}, 3000)

How do I make a delay in Java?

If you want to pause then use java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

To sleep for one second or

TimeUnit.MINUTES.sleep(1);

To sleep for a minute.

As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep.

Further, sleep isn't very flexible when it comes to control.

For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService and either scheduleAtFixedRate or scheduleWithFixedDelay.

For example, to run the method myTask every second (Java 8):

public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
System.out.println("Running");
}

And in Java 7:

public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
myTask();
}
}, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
System.out.println("Running");
}

How to make an Android program 'wait'

OK, first of all, never implement a delay with a busy loop as you're doing. I can see where that comes from -- I'm guessing that the palm pilot was a single-process device with no built-in sleep() function, but on a multi-process device, a busy loop like that just brings the entire processor to its knees. It kills your battery, prevents normal system tasks from running properly, slows down other programs or stops them completely, makes the device unresponsive, and can even cause it to get hot in your hands.

The call you're looking for is Thread.sleep(). You'll need to set up to catch any interrupt exceptions that occur while you're sleeping.

Second, with event-based user interfaces such as Android (or pretty much any modern GUI system), you never want to sleep in the UI thread. That will also freeze up the entire device and result in an ANR (Activity Not Responding) crash, as other posters have mentioned. Most importantly, those little freezes totally ruin the user experience.

(Exception: if you're sleeping for short enough intervals that the user probably won't notice, you can get away with it. 1/4 second is probably ok, although it can make the application janky depending on the situation.)

Unfortunately, there's no clean and elegant way to do what you want if what you're doing is porting a loop-based application to an event-based system.

That said, the proper procedure is to create a handler in your UI thread and send delayed messages to it. The delayed messages will "wake up" your application and trigger it to perform whatever it was going to do after the delay.

Something like this:

View gameBoard;     // the view containing the main part of the game
int gameState = 0; // starting
Handler myHandler;

public void onCreate(Bundle oldState) {
super.onCreate(oldState);
...
gameBoard = findViewById(R.layout.gameboard);
myHandler = new Handler();
...
}

public void onResume() {
super.onResume();
displayStartingScreen();
myHandler.postDelayed(new Runnable() {
gotoState1();
}, 250);
}

private void gotoState1() {
// It's now 1/4 second since onResume() was called
displayNextScreen();
myHandler.postDelayed(new Runnable() {
gotoState2();
}, 250);
}
...


Related Topics



Leave a reply



Submit