Android studio sleep function

Sleep () в java (Android)

Я следую этому руководству, чтобы иметь экран загрузки в моей программе. В учебном пособии говорится, что моя активность должна Sleep () с помощью команды Sleep (), однако она не распознает функцию Sleep () как функцию и предоставляет мне ошибку, спрашивая, хочу ли я создать метод Sleep ().

Вот ссылка на учебник:

Вот пример кода:

Вы можете использовать один из следующих методов:

SystemClock.sleep(milliseconds) – это функция утилиты, очень похожая на Thread.sleep(milliseconds) , но игнорирует InterruptedException . Используйте эту функцию для задержек, если вы не используете Thread.interrupt() , так как она сохранит прерванное состояние потока.

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

Код, который вы опубликовали, ужасен. Не используйте это на реальном устройстве. Вы получите ошибку «Приложение не отвечает», если вы запустите что-то похожее на это.

Если вы используете Handlers, имейте в виду, что обработчик создается в потоке, где он выполняется . Поэтому вызов new Handler().post(. в потоке пользовательского интерфейса будет выполнять runnable в потоке пользовательского интерфейса, включая эту «длительную операцию». Преимущество заключается в том, что вы можете создать обработчик для потока пользовательского интерфейса, который вы можете использовать Позже, как показано ниже.

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

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

Источник

Как приостановить / спать поток или процесс в Android?

Я хочу сделать паузу между двумя строками кода, позвольте мне объяснить немного:

-> пользователь нажимает кнопку (фактически карту), и я показываю ее, изменяя фон этой кнопки:

-> после, скажем, 1 секунды, мне нужно вернуться к предыдущему состоянию кнопки, изменив ее фон:

-> Я пытался приостановить поток между этими двумя строками кода с помощью:

Однако это не работает. Может быть, мне нужно приостановить процесс, а не поток?

Я также пытался (но это не работает):

Как я могу приостановить / спать поток или процесс?

Одним из решений этой проблемы является использование метода Handler.postDelayed () . Некоторые учебные материалы Google предлагают такое же решение.

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

Более сложное решение , которое позволяет избежать утечек памяти подкласса Handler и Runnable со статическими внутренними классами внутри деятельности , так как статические внутренних классы не занимающим неявную ссылки на их внешний класс:

Обратите внимание, что Runnable используется WeakReference для Activity, что необходимо в статическом классе, которому требуется доступ к пользовательскому интерфейсу.

Источник

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

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

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

Котлин

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

Примечание. Этот ответ был дан, когда в вопросе не был указан 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 секунды:

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

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

Читайте также:  Acer liquid android modem

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

Android Sleep API Tutorial: Getting Started

Learn how to use the Android Sleep API in your Kotlin apps to track when the user is asleep, awake, how long they slept, and the confidence of the results.

Version

  • Kotlin 1.4, Android 10.0, Android Studio 4.2

In this tutorial, you’ll learn how to interact with the Android Sleep API and react to the stream of events sent by the system. The Android Sleep API collects information such as surrounding brightness and device movement to make assumptions about when the user is asleep or awake.

This API is handy for tracking users’ sleep patterns to help them improve their sleep habits.

While building a simple sleep tracking app, you’ll how to:

  • Request Activity Recognition permissions for your app.
  • Register a Sleep Receiver to filter and analyze the different events sensed by the device.

With that, it’s time to jump right in! Try not to fall asleep. ;]

Getting Started

Click Download Materials at the top or bottom of this tutorial to download the sample project.

Import the starter project in Android Studio. Build and run it. You’ll see a classic sample screen:

You won’t interact with the UI much in this tutorial, so building and running the app is more about checking the code’s correctness.

Using the Android Sleep API

To use this API, you’ll need two pieces of code:

  1. The ActivityRecognition client that lets you subscribe to sleep updates.
  2. A BrodcastReceiver , to receive the updates from the ActivityRecognition client.

Additionally, you need to ask the user for permission to listen to their sleep data, which they grant outside the app, in the Settings screen.

This API will provide two sets of information:

  • The confidence level that your user is sleeping, which the API reports periodically a few minutes after the previous emission.
  • The daily sleep segment the API emits once the device detects the user is awake.

To use this API, you first need to include the dependencies. Open app ‣ build.gradle and add the following line in the dependencies block:

Now you’re all set to start writing some code.

Listening for Sleep Data

Before you can do anything else, you need to receive sleep data. The component that provides this information is the BroadcastReceiver .

Open SleepReceiver.kt. Notice SleepReceiver already extends BroadcastReceiver with an empty onReceive . This method is where you’ll add the logic that filters the data.

Читайте также:  Контакты pro для андроид

Open AndroidManifest.xml. You’ll see SleepReceiver is already declared inside, right below MainActivity . It looks like this:

You need to declare SleepReceiver in AndroidManifest.xml so the system knows BroadcastReceiver is available in your app.

Now that you have SleepReceiver set up, it’s time to write the logic that will filter the events coming from the Intent .

Filtering Sleep Data

Open SleepReceiver. Add the following statement inside onReceive() :

Here, you check whether the Intent contains SleepSegmentEvents or SleepClassifyEvents .

Next, add the following companion object to the bottom of the class:

You’ll use this tag to log events to the console and filter the text you’ll show in a few lines.

Now, to focus on the first branch of the if statement!

Right below the if line, add:

In case the Intent you receive contains a SleepSegmentEvent , you extract it and print its starting and ending timestamps and its status to the console. This represents the UNIX timestamp when the device detected the user began sleeping, woke up and a status code that indicates if the system succeeded in collecting sleep data, respectively.

Now you can get the sleep segments, but you also want to classify the events. You can do this in the statement’s else branch by adding:

Once again, you need to extract the information about the event and print its data to the console, highlighting the confidence level of the classification, light quantity and value of the motion.

At this point, if you build and run the app, you won’t see any output in the console. You still need to take a few more steps before you can get the data!

Requesting Activity Recognition Permissions

To get the sleep data, you need to have permission from your user to access it. It’s not as straightforward as with other permissions since you need to open the settings for the data, and the user needs to grant your app the Activity Recognition permissions. But it’s not that complicated either.

First, open AndroidManifest.xml and add the following permission within manifest :

Next, you need to create a method inside MainActivity.kt that will open the settings screen. Open MainActivity and add the following, importing android.provider.Settings :

Here you create the Settings Intent , adding the Activity Recognition action and your app package extra. You then run the Intent .

Now, since you need to request permissions, you can leverage the ActivityResultContracts API, which will help reduce the boilerplate to listen for the activity result.

Start by adding the activity ktx library to app ‣ build.gradle:

Sync your gradle file. This adds ActivityResultContracts and ActivityResultLauncher to your project.

Then, add this property to MainActivity :

Here, you create an object that will listen for the Activity result from your permission request and pass it to you once this object parses it.

It’s not time to build and run your app yet. If you try, it still won’t show any data. But it will soon!

Subscribing to Sleep Data Updates

Next, you’ll subscribe to sleep data updates. To do so, you need to create a new class. Create SleepRequestsManager in the same package as MainActivity. The class declaration should look like:

This class will manage subscribing and unsubscribing from the update. At first, you’ll only take care of subscribing. To do so, you need to pass in the Context as a constructor parameter.

Next, you’ll add a method that will let you subscribe to the updates for the sleep data. Add this method to your new class:

Now you have a place to add your subscription.

Open SleepReceiver and scroll down to the TAG constant declaration inside the companion object. Inside the companion object, paste this code which will create a PendingIntent from a Context , passed as a parameter:

To subscribe to the updates, you create a PendingIntent from a BroadcastReceiver that will get the updates. You already created that receiver, but you still need the PendingIntent .

At this point, you have everything you need to create the subscription logic. Head back to SleepRequestManager and create the Pending Intent right between the class constructor and the empty subscribeToSleepUpdates() :

This Pending Intent is what you’ll use in the next step to subscribe to updates.

Now, you have everything you need to subscribe to the updates, and you can ask the API to send the data down to your receiver. Inside subscribeToSleepUpdates() , add:

In this code, you invoke the ActivityRecognition client and request updates about the sleep segments with a default request.

Before you can subscribe, however, you still need to check that the permission is in place. After all, your user can always remove it.

You need to check whether you can access the data and subscribe to the updates if you still can. If you can’t, you need to request permission.

First, add this code above subscribeToSleepUpdates() :

Here’s a code breakdown:

  1. The first thing you’ll notice is the requestPermission lambda parameter. This is the callback you need if you don’t have permission to get the data. You get it as a parameter since you need to register the callback inside the Activity anyway, so it’s easier to pass the lambda from outside the method.
  2. In the first line of the method, you use ContextCompat to check if you have the Activity Recognition permissions. If you do, you invoke the subscribeToSleepUpdates() to receive the updates. If not, you request the permission again.
Читайте также:  Драки андроид для двоих

Now, head back to MainActivity. Add a declaration for the SleepRequestManager you just created:

Now you have a SleepRequestManager in MainActivity to request sleep updates.

Scroll to the line where you see // Request goes here within permissionRequester , and replace it with a call to the subscription:

You invoke the update directly because the user granted your app permission, and you ended up in the else branch. So, in this specific case, you can run the update safely.

Finally, you need to run SleepRequestManager when the user opens the app. Scroll down to the line where you see // Your code at the bottom of onCreate() and add:

Here, you ask SleepRequestManager to request the updates, and you specify how it should behave if it doesn’t have permission to get the data.

Now, build and run. You’ll notice some events are starting to appear in the Logcat tab! Make sure you accept the permission first.

Unsubscribing From Updates

Right now, your app doesn’t stop listening to the sleep update events. However, you might need to unsubscribe to let your users start and stop the app when they wish.

To create the logic to unsubscribe from the updates, open SleepRequestManager and below subscribeToSleepUpdates add:

Here, you remove the subscription from the ActivityRecognition client.

Now, head back to MainActivity. Override onDestroy() and invoke the unsubcribe method:

This code ensures the app stops listening and printing the logs when the user exits.

Now, build and run. Notice it stops printing logs once you exit!

Handling Reboots

When the device reboots, the Android system will kill your app, and your software won’t run unless your user reopens it. This is an important consideration because you need to record user sleep patterns when your users are not awake, which is usually at night.

Unfortunately, night is also when most devices update, often followed by a reboot. These reboots could potentially lead to days without data if your app can’t run automatically when a reboot completes.

You can make your app run at two steps in the boot process:

  1. The first, Direct Boot mode, happens after the system reboots but before the user logs into their device.
  2. The other happens after the boot completes and the user unlocks their device.

For this tutorial, you’ll learn how to react to the user logging into their device after a reboot.

Listening to Reboot Events

If you want your app to listen to events after the device reboots, you must add another BroadcastReceiver . Open BootReceiver , and you notice it’s empty and ready for you to fill.

This receiver will run when the device reboots and register for sleep data updates. Right below onReceive() add a companion like this:

First, you declare another TAG String constant that you’ll use for the error logs. It’s different from the previous one distinguish it when filtering the output in Logcat.

Now, replace onReceive() with:

Here, you create a new instance of SleepRequestManager and invoke requestSleepUpdate() .

This time, you can’t ask the users for permission if they removed it because your app might be running before the user logs in. In that case, they wouldn’t be able to change any settings before unlocking the device. There’s not much you can do to prevent this situation, but you can log the error and perform retention strategies afterward.

To run at boot safely, you need to register your receiver in AndroidManifest.xml with some special flags that will let the system know it’s ok for your app to run as soon as the device boots. This is already in AndroidManifest.xml for you:

Note that you need to add the RECEIVE_BOOT_COMPLETED permission to the Receiver declaration. Otherwise, the Android system won’t notify your app when the boot completes, and it won’t run automatically.

Build and run. Congratulations! Now you can successfully track sleep data.

Where to Go From Here?

Now you know how to interact with the Android Sleep API and receive updates about the user’s sleep segments. You can download the final project using the download button below. To learn more about the Sleep API in the official documentation.

You might want to check more resources to improve the solution you just implemented.

First, check the Android Apprentice Book for a deep and complete understanding of how to create beautiful Android apps.

You could also check our tutorials for specific features you might want to implement, like storing the subscription status with a DataStore or using Room database to store the sleep events.

If you have any questions or comments, please join the forums below!

Источник

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