Android studio java delay

Android Studio Delay inside Loop

I want to make a loop, the times the user wants but with a delay of 3 seconds.

This is the code:

The variable i is the one that the user sets. The problem is that the toast doesn’t show up every 3 seconds, it just do like a normal loop without delay. I thought it was because of the time of the toast but if i set the time to 20 secs still being the same. Someone knows how to make a proper delay inside a loop.

2 Answers 2

The problem you have is that your loop creates many handlers at once that delay for 3 seconds and then show a toast. They do not wait for each other, and because they are created within milliseconds of each other they will show the toast at the same time.

I’m not sure what you are trying to accomplish, and a loop is probably not what you want. However this is a way to get the toast to display after 3 seconds and every 3 seconds after for a number of times.

For this we will use recursion because it will make it so that you are not blocked on the main thread.

  1. Call doSomething (the recursive function) from where you need the function to start (remember that the second variable is the number of times you want it to run, and 0 is just required as a counter)
  1. create doSomething

Источник

Add a delay timer in Android Studio

FaceView.java is to display the different facial expressions in the canvas. The NormalFace.java and HappyFace.java are the UI of the different facial expressions. I want to add a delay timer in FaceView.java so that the display of the normal face can be change to a happy face after the timer had finished counting down.

3 Answers 3

Use this: ms is delay in millisecond

You can use Handler class for this in android.Handler has a method postDelayed() ,you can use this method for the delay,read about handler from here

and then call this method like this after 5 sec

It will post your code to be run after 5 sec

You can use Handler to delay your next task

30000 is the value of delay in milli seconds which makes it 30 secs

Not the answer you’re looking for? Browse other questions tagged java android timer or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Как вызвать метод после задержки в Android

Я хочу иметь возможность вызывать следующий метод после указанной задержки. В цели c было что-то вроде:

Есть ли эквивалент этого метода в Android с Java? Например, мне нужно иметь возможность вызывать метод через 5 секунд.

Котлин

Я не мог использовать другие ответы в моем случае. Я использовал нативный таймер Java вместо этого.

Читайте также:  Add jar file android studio

Примечание. Этот ответ был дан, когда в вопросе не был указан Android в качестве контекста. Ответ на вопрос, касающийся темы пользовательского интерфейса Android, можно найти здесь.

Похоже, что API Mac OS позволяет текущему потоку продолжить и планирует выполнение задачи асинхронно. В Java эквивалентная функция предоставляется java.util.concurrent пакетом. Я не уверен, какие ограничения может наложить Android.

Для выполнения чего-либо в потоке пользовательского интерфейса через 5 секунд:

Вы можете использовать Handler внутри UIThread:

Спасибо за все отличные ответы, я нашел решение, которое наилучшим образом соответствует моим потребностям.

Kotlin И Java много способов

1. Использование Handler

2. Использование TimerTask

Или даже короче

Или самый короткий будет

3. Использование Executors

На яве

1. Использование Handler

2. Использование Timer

3. Использование ScheduledExecutorService

Смотрите это демо:

Если вам нужно использовать обработчик, но вы находитесь в другом потоке, вы можете использовать его runonuithread для запуска обработчика в потоке пользовательского интерфейса. Это избавит вас от исключений, брошенных с просьбой позвонить Looper.Prepare()

Выглядит довольно грязно, но это один из способов.

Я предпочитаю использовать View.postDelayed() метод, простой код ниже:

Вот мое самое короткое решение:

Если вы используете Android Studio 3.0 и выше, вы можете использовать лямбда-выражения. Метод callMyMethod() вызывается через 2 секунды:

Если вам нужно отменить отложенный запуск, используйте это:

Я предлагаю Таймер , он позволяет запланировать вызов метода на очень определенный интервал. Это не заблокирует ваш пользовательский интерфейс и не оставит ваше приложение отзывчивым во время выполнения метода.

Другой вариант — это wait (); метод, это заблокирует текущий поток на указанный промежуток времени. Это заставит ваш пользовательский интерфейс перестать отвечать, если вы сделаете это в потоке пользовательского интерфейса.

Для простой строки Handle Post delay вы можете сделать следующее:

надеюсь, это поможет

Вы можете использовать это для простейшего решения:

Еще, ниже может быть еще одно чистое полезное решение:

Вы можете сделать это намного чище, используя недавно введенные лямбда-выражения:

Так что здесь есть несколько вещей, которые нужно учитывать, так как есть много способов снять шкуру с этой кошки. Хотя ответы уже все были выбраны и выбраны. Я думаю, что важно, чтобы это было пересмотрено с надлежащими руководящими принципами кодирования, чтобы никто не шел в неправильном направлении только из-за «простого ответа большинства».

Итак, сначала давайте обсудим простой ответ с задержкой после публикации, который является ответом, выбранным победителем в целом в этой теме.

Несколько вещей для рассмотрения. После задержки вы можете столкнуться с утечками памяти, мертвыми объектами, ушедшими жизненными циклами и многим другим. Поэтому правильное обращение с ним также важно. Вы можете сделать это несколькими способами.

Ради современного развития я поставлю в КОТЛИН

Вот простой пример использования потока пользовательского интерфейса при обратном вызове и подтверждение того, что ваша активность все еще жива, когда вы нажимаете на обратный вызов.

Тем не менее, это все еще не идеально, поскольку нет никаких причин, чтобы ответить на ваш обратный вызов, если активность ушла. так что лучшим способом было бы сохранить ссылку на него и удалить его обратные вызовы, как это.

и, конечно же, очистка onPause, чтобы он не попадал в обратный вызов.

Теперь, когда мы обсудили очевидное, давайте поговорим о более чистом варианте с современными сопрограммами и котлином :). Если вы еще не используете их, вы действительно пропустите.

или если вы хотите всегда запускать пользовательский интерфейс для этого метода, вы можете просто сделать:

Конечно, точно так же, как PostDelayed, вы должны убедиться, что обрабатываете отмену, чтобы вы могли либо выполнять проверки активности после задержки вызова, либо вы можете отменить ее в onPause, как и другой маршрут.

Если вы поместите запуск (UI) в сигнатуру метода, задание может быть назначено в вызывающей строке кода.

Таким образом, мораль этой истории заключается в том, чтобы быть в безопасности с вашими отложенными действиями, убедитесь, что вы удалили свои обратные вызовы, или отменили свою работу, и, конечно, подтвердите, что у вас есть правильный жизненный цикл, чтобы коснуться элементов в вашем обратном обратном вызове. Coroutines также предлагает отменяемые действия.

Читайте также:  Настройка устройств андроид что это

Также стоит отметить, что вы обычно должны обрабатывать различные исключения, которые могут возникнуть с сопрограммами. Например, отмена, исключение, тайм-аут, все, что вы решите использовать. Вот более сложный пример, если вы решите действительно использовать сопрограммы.

Источник

How to set delay in android?

I want to set a delay between the command between changing background. I tried using a thread timer and tried using run and catch. But it isn’t working. I tried this

But it is only getting changed to black.

9 Answers 9

You can use CountDownTimer which is much more efficient than any other solution posted. You can also produce regular notifications on intervals along the way using its onTick(long) method

Have a look at this example showing a 30seconds countdown

If you use delay frequently in your app, use this utility class

Using the Thread.sleep(millis) method.

If you want to do something in the UI on regular time intervals very good option is to use CountDownTimer:

Handler answer in Kotlin :

1 — Create a top-level function inside a file (for example a file that contains all your top-level functions) :

2 — Then call it anywhere you needed it :

You can use this:

and for the delay itself, add:

where the delay variable is in milliseconds; for example set delay to 5000 for a 5-second delay.

Here’s an example where I change the background image from one to another with a 2 second alpha fade delay both ways — 2s fadeout of the original image into a 2s fadein into the 2nd image.

I think the easiest and most stable and the most useful way as of 2020 is using delay function of Coroutines instead of Runnable. Coroutines is a good concept to handle asynchronous jobs and its delay component will be this answer’s focus.

WARNING: Coroutines need Kotlin language and I didn’t convert the codes to Kotlin but I think everybody can understand the main concept..

Just add the Coroutines on your build.gradle :

Add a job to your class (activity, fragment or something) which you will use coroutines in it:

And you can use Coroutines anywhere on the class by using launch body. So you can write your code like this:

Dont’t forget that launch<> function is asynchronous and the for loop will not wait for delay function to finish if you write like this:

So, launch < >should cover the for loop if you want all the for loop to wait for delay .

Another benefit of launch < >is that you are making the for loop asynchronous, which means it is not gonna block the main UI thread of the application on heavy processes.

Источник

How to call a method after a delay in Android

I want to be able to call the following method after a specified delay. In objective c there was something like:

Is there an equivalent of this method in android with java? For example I need to be able to call a method after 5 seconds.

33 Answers 33

Kotlin

I couldn’t use any of the other answers in my case. I used the native java Timer instead.

Note: This answer was given when the question didn’t specify Android as the context. For an answer specific to the Android UI thread look here.

It looks like the Mac OS API lets the current thread continue, and schedules the task to run asynchronously. In the Java, the equivalent function is provided by the java.util.concurrent package. I’m not sure what limitations Android might impose.

For executing something in the UI Thread after 5 seconds:

you can use Handler inside UIThread:

Kotlin & Java Many Ways

1. Using Handler

2. Using TimerTask

Or even shorter

Or shortest would be

3. Using Executors

In Java

1. Using Handler

2. Using Timer

3. Using ScheduledExecutorService

Thanks for all the great answers, I found a solution that best suits my needs.

If you have to use the Handler, but you are into another thread, you can use runonuithread to run the handler in UI thread. This will save you from Exceptions thrown asking to call Looper.Prepare()

Читайте также:  Sms to excel android

Looks quite messy, but this is one of the way.

I prefer to use View.postDelayed() method, simple code below:

Here is my shortest solution:

If you are using Android Studio 3.0 and above you can use lambda expressions. The method callMyMethod() is called after 2 seconds:

In case you need to cancel the delayed runnable use this:

More Safety — With Kotlin Coroutine

Most of the answers use Handler but I give a different solution to delay in activity, fragment, view model with Android Lifecycle ext. This way will auto cancel when the lifecycle begins destroyed — avoid leaking the memory or crashed app

In Activity or Fragment:

In ViewModel:

In suspend function: (Kotlin Coroutine)

If you get an error with the lifecycleScope not found — import to gradle file:

I suggest the Timer, it allows you to schedule a method to be called on a very specific interval. This will not block your UI, and keep your app resonsive while the method is being executed.

The other option, is the wait(); method, this will block the current thread for the specified length of time. This will cause your UI to stop responding if you do this on the UI thread.

So there are a few things to consider here as there are so many ways to skin this cat. Although answers have all already been given selected and chosen. I think it’s important that this gets revisited with proper coding guidelines to avoid anyone going the wrong direction just because of «majority selected simple answer».

So first let’s discuss the simple Post Delayed answer that is the winner selected answer overall in this thread.

A couple of things to consider. After the post delay, you can encounter memory leaks, dead objects, life cycles that have gone away, and more. So handling it properly is important as well. You can do this in a couple of ways.

For sake of modern development, I’ll supply in KOTLIN

Here is a simple example of using the UI thread on a callback and confirming that your activity is still alive and well when you hit your callback.

However, this is still not perfect as there is no reason to hit your callback if the activity has gone away. so a better way would be to keep a reference to it and remove it’s callbacks like this.

and of course handle cleanup on the onPause so it doesn’t hit the callback.

Now that we have talked through the obvious, let’s talk about a cleaner option with modern day coroutines and kotlin :). If you aren’t using these yet, you are really missing out.

or if you want to always do a UI launch on that method you can simply do:

Of course just like the PostDelayed you have to make sure you handle canceling so you can either do the activity checks after the delay call or you can cancel it in the onPause just like the other route.

If you put the launch(UI) into the method signature the job can be assigned in the calling line of code.

so moral of the story is to be safe with your delayed actions, make sure you remove your callbacks, or cancel your jobs and of course confirm you have the right life cycle to touch items on your delay callback complete. The Coroutines also offers cancelable actions.

Also worth noting that you should typically handle the various exceptions that can come with coroutines. For example, a cancelation, an exception, a timeout, whatever you decide to use. Here is a more advanced example if you decide to really start utilizing coroutines.

Источник

Оцените статью