What is alarms in android

Android Tutorials for Beginners

Learn Android very Easily and Step by Step with this blog.

10 Tips to Increase Windows 10 Performnace

Friday, May 31, 2013

Android Alarm Manager

AlarmManager

The Alarm Manager holds a CPU wake lock as long as the alarm receiver’s onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes. If your alarm receiver called Context.startService() , it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.

Android AlarmManager Example

In the example I will schedule an alarm to send SMS at a particular time in future.
We have two classes
1: MainAcitvity: in this class, we will schedule the alarm to be triggered at particular time .
2: AlarmReciever: when the alarm triggers at scheduled time , this class will receive the alarm, and send the SMS.

AlarmReciever class extends BroadcastReceiver and overrides onRecieve() method. inside onReceive() you can start an activity or service depending on your need like you can start an activity to vibrate phone or to ring the phone

Permission Required
we need permission to use the AlarmManger in our application, so do not forget to declare the permission in manifest file

AndroidManifest file

main.xml

android:layout_width=»fill_parent»
android:layout_height=»fill_parent»
android:orientation=»vertical»
android:gravity=»center_vertical»
xmlns:android=»http://schemas.android.com/apk/res/android»>

android:id=»@+id/textView1″
android:gravity=»center_horizontal»
android:layout_width=»fill_parent»
android:layout_height=»wrap_content»
android:text=»Alarm Manager Example»
android:textAppearance=»?android:attr/textAppearanceLarge»/>

MainActivity.java

public class MainActivity extends Activity
<
@Override
public void onCreate(Bundle savedInstanceState)
<
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
>

public void scheduleAlarm(View V)
<
// time at which alarm will be scheduled here alarm is scheduled at 1 day from current time,
// we fetch the current time in milliseconds and added 1 day time
// i.e. 24*60*60*1000= 86,400,000 milliseconds in a day
Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000;

// create an Intent and set the class which will execute when Alarm triggers, here we have
// given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
// alarm triggers and
//we will write the code to send SMS inside onRecieve() method pf Alarmreciever class
Intent intentAlarm = new Intent(this, AlarmReciever.class);

// create the object
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, «Alarm Scheduled for Tommrrow», Toast.LENGTH_LONG).show();

AlarmReciever.java

public class AlarmReciever extends BroadcastReceiver
<
@Override
public void onReceive(Context context, Intent intent)
<
// TODO Auto-generated method stub

// here you can start an activity or service depending on your need
// for ex you can start an activity to vibrate phone or to ring the phone

String phoneNumberReciver=»9718202185″; // phone number to which SMS to be send
String message=»Hi I will be there later, See You soon»; // message to send
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumberReciver, null, message, null, null);
// Show the toast like in above screen shot
Toast.makeText(context, «Alarm Triggered and SMS Sent», Toast.LENGTH_LONG).show();
>

>

Advance Android Topics Customizing Android Views

Источник

Alarm Service — сигнализация

2-й курс/Закрытая зона

Теория

Служба Alarm Service используется для отправки пользователю разовых или повторяющихся сообщений в заданное время. Таким образом вы сможете создавать различные планировщики, будильники, реализовать выполнение регулярных сетевых запросов, запуска трудоёмких или дорогих операций, запланированных на определенное время и другие приложения, которые должны срабатывать по расписанию.

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

Читайте также:  Как сделать прошивку андроид планшет

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

Сигнализация в Android остается активной даже тогда, когда устройство находится в режиме ожидания и при необходимости может его «пробудить», однако она отменяется каждый раз, когда устройство перезагружается.

Менеджер оповещений AlarmManager

Доступ к службе Alarm Service осуществляется при помощи объекта AlarmManager следующим образом:

Методы

  • cancel() — удаляет все сигнализации
  • setTime() — устанавливает системное время
  • setTimeZone() — устанавливает временную зону
  • set() — задаёт одноразовую сигнализацию
  • setExact() — в API 19 (Kitkat) метод set() заменили на новый метод с теми же параметрами
  • setRepeating() — задаёт повторяющиеся сигнализации с фиксированным временным интервалом
  • setInexactRepeating() — устанавливает повторяющиеся сигнализации без строгого требования к точности периода повторения. Этот метод является предпочтительнее предыдущего для экономии ресурсов системы

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

Параметры

Методы set(), setRepeating(), setInexactRepeating() используют следующие параметры:

  • typeOne — тип используемого времени (системное или всемирное время UTC), который определяется константами
    • ELAPSED_REALTIME — запускает ожидающее намерение, основываясь на времени, которое прошло с момента загрузки устройства, но не с момента выхода из режима ожидания. Это время включает любой временной промежуток, в котором устройство находилось в данном режиме. Обратите внимание, что прошедшее время вычисляется на основании того, когда устройство было загружено. Используется системное время
    • ELAPSED_REALTIME_WAKEUP — по прошествии указанного промежутка времени с момента загрузки выводит устройство из спящего режима и запускает ожидающее намерение. Используется системное время
    • RTC — запускает ожидающее намерение в указанное время, но не выводит устройство из режима ожидания. Используется всемирное время UTC
    • RTC_WAKEUP — выводит устройство из режима ожидания для запуска ожидающего намерения в указанное время. Используется всемирное время UTC
  • triggerTime — время работы оповещения
  • interval — интервал между отправкой повторных сигнализаций в миллисекундах. Также можно использовать константы
    • INTERVAL_DAY
    • INTERVAL_HALF_DAY
    • INTERVAL_HOUR
    • INTERVAL_HALF_HOUR
    • INTERVAL_FIFTEEN_MINUTES
  • operation — объект PendingIntent, определяющий действие, выполняемое при запуске сигнализации. Можно получить через специальные методы:
    • PendingIntent.getActivities(Context, int, Intent[], int)
    • PendingIntent.getActivity(Context, int, Intent, int)
    • PendingIntent.getService(Context, int, Intent, int)
    • PendingIntent.getBroadcast(Context, int, Intent, int)

Служба

Для установки сигнализации вам придётся создать собственную службу, наследуясь от базового класса Service (либо через приёмник BroadcastReceiver):

Запуск и управление службой происходит при помощи объекта Intent.

Установка времени для сигнализаций

Для задания времени работы оповещения необходимо установить его время запуска и добавить к нему длительность работы этого оповещения. Например, нам необходимо, чтобы оповещение отрабатывало 5 секунд после запуска:

Также можно использовать объект Calendar. Например, мы хотим, чтобы продолжительность сигнала оповещения была 10 секунд, а период повторения оповещения был один час:

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

Источник

Using AlarmManager like a pro

Feb 2, 2019 · 3 min read

All of us must have used AlarmManager in some way in our projects but there a lot of times when our alarms get cancelled or there are bugs in the implementation. Today we will learn what all measures we should take to make sure that all our alarms are set correctly. We will also understand what all scenarios we should consider whenever we are using the AlarmManager.

Firstly let’s get the basics righ t . There are two types of alarms that you can set. You can either set a one time alarm or a repeating alarm. Let’s quickly have a look at both of these alarms.

For non repeating alarms we just have to specify at what time we need the alarm. The following alarm will fire after 1 min.

For repeating alarms, we have to first set at what time we need the alarm and then the duration after which the alarm should repeat itself. The following alarm will fire everyday. AlarmManager.INTERVAL_DAY is nothing but the time in milliseconds for a day, instead you can also specify any time of your choice in milliseconds.

So it is very easy to set these alarms but now let’s discuss the cases when these alarms get cancelled or behave in an unusual manner.

All alarms get cancelled when the phone reboots

By default all alarms get cancelled when a device shuts down. To tackle this we need to set the alarms again when the user restarts their device. Let’s have a look how this is done.

Читайте также:  Addonbackstackchangedlistener android что это

The above permission needs to be added in the manifest so that the app can receive the ACTION_BOOT_COMPLETED broadcast after the system finishes booting.

Don’t forget to add the receiver in the manifest with the action BOOT_COMPLETED. If you are wondering what android:enabled=”false” is it simply means that the receiver will not be called unless it is explicitly enabled in the app.

The above code enables the receiver. You should preferably add it in the first activity of your app.

The BroadcastReceiver above gets called whenever the user reboots their device. Here we will set the alarm again but the important thing is we can’t use the values passed through the intent to set the alarm. This is because these values will be null when the system reboots. We need to pass values from a permanent source of memory like a SQL database.

All alarms get cancelled when the system time is changed

Another case when the Alarms get cancelled is when the user changes their system time or date from the settings. Let’s see what we can do to tackle this situation.

Firstly we need to register a receiver in the manifest with the action TIME_SET.

The following BroadcastReceiver will get called every time the user changes the system time. You just have to set the alarms again in the onReceive.

All past Alarms are fired immediately

When we are setting our alarms it is very important to check that the time that we are setting the alarm is not of the past because these alarms will get fired as soon as they are set. A simple check such as the following will ensure that no past alarms are fired.

These were some of the points that you should keep in mind if you are using the AlarmManager to set alarms for may be showing periodic notifications once a day.

Here is the link of the sample project that I made for this story. Feel free to check it out.

Thanks for reading! If you enjoyed this story, please click the 👏 button and share to help others! Feel free to leave a comment 💬 below. Have feedback? Let’s connect on Twitter .

Источник

10 best alarm clock apps for Android

Read more:

Alarm Clock for Heavy Sleepers

Price: Free / $1.99

Alarm Clock for Heavy Sleepers is a simple, but effect app. You can set an unlimited number of alarms. Additionally, the app does countdown alarms, recurring alarms, and one-time alarms. It even supports Android Wear, sleep stats, and more. Each one can have a challenge mode that tries to wake you up enough to not fall back asleep. That includes alarms for bed time so that you can get enough sleep. The free version and the paid version are virtually identical. The paid version does remove ads, though.

AlarmMon

Price: Free / Up to $16.99

AlarmMon is a decent alarm clock app. It does the basics and you can set multiple alarms if needed. In addition, you can set the alarm tone and snooze instructions. However, there are some extras with this one. You get some cartoon characters to help get you out of slumber easier along with some other little things that make you use your brain before it can go back to sleep. The app is free and you can download extras at a price.

Alarmy

Price: Free / Up to $26.99

Alarmy calls itself the world’s most annoying alarm clock. This one has a unique premise. You set alarms and they go off just like they normally do. However, Alarmy also makes you add an image of something in your house. You then have to get out of bed, go to the same spot, and take a picture of the same thing to get the alarm to stop. Usually, once you’re out of bed, you’re up for the day so that’s the philosophy with this one. You can also make it ask you random math questions, shake the device to dismiss the alarm, and more. The phone can even prevent you from turning your phone off while the alarm is ringing. It’s a good alarm for heavy sleepers especially. This one is also free to use if you subscribe to Google Play Pass.

Challenges Alarm Clock

Price: Free / $0.99

Challenges Alarm Clock is another alarm clock that tries to trick your brain into waking up. It works well as a standard alarm. You can set your own tones, set multiple alarms, and set snooze instructions. Additionally, the app has puzzles, games, and even a photo mechanic to try to get you all the way awake before you hit the snooze button. There is also a soft wake feature so you’re not jarring yourself awake every day. It’s a decent solution and it’s fairly cheap.

Читайте также:  Lust epidemic android сохранения

Early Bird Alarm Clock

Price: Free / $1.99

Early Bird Alarm Clock is one of the basic alarm clock apps. It has the basic features like an almost infinite number of alarms. It also includes themes, alarm challenges, weather, and more. The alarm challenges are pretty decent as well. The app can also automatically change your alarm tone every day. That is definitely among its best features. It’s simple and it (usually) just works. The free version has advertising while the paid version does not. Otherwise both work the same way.

See more:

Google Assistant

Price: Free

Google Assistant can double as an alarm clock. You simply ask it to set an alarm for you. The alarm then goes off as scheduled. It also supports countdown timers, reminders, and it can add things to your calendar. It always goes through the stock alarm clock app. That may or may not be a good thing. After all, you’re here looking for a new one, right? In any case, Google Assistant can set alarms quickly and you can also set stuff like timers or reminders to go off at certain times. It’s a few different ways to set an alarm for something and some of them are for things other than sleep as well. It’s a decent option if you already use Google Assistant.

I Can’t Wake Up

Price: Free / $2.99

I Can’t Wake Up does what the title suggests. It is for those who have trouble waking up in the morning. The app includes eight wake-up challenges to turn the alarm off. The idea being to make you coherent enough to get up before you hit the snooze button. It also has various alarm styles, some customization features, and some convenience features. This is definitely not your regular stock alarm clock. However, it does feel a little cleaner than some of the other options on the list. The free version and pro version are almost identical. The $2.99 pro version does remove ads.

Loud Alarm Clock

Price: Free / $3.99

Loud Alarm Clock is, well, one loud alarm clock. It uses an audio booster to make your alarm tones as loud as they can be. It works mostly like a normal alarm clock app. You set alarms, set the snooze, and you can set the alarm tone or leave it random if you want to. There are also some themes for some extra fun if you care about that stuff. Be careful because super loud sounds may damage your phone over time. If you worry about such things, you might want to skip this one.

Sleep as Android

Price: Free trial / Up to $9.99

Sleep as Android is among the most popular sleep tracking apps. The app studies you while you sleep. It then tries to analyze how well you’re sleeping. It does require you to sleep with your phone in the bed. The app also integrates with Google Fit, Samsung S Health, Galaxy Gear, Android Wear, Pebble (RIP), and Spotify. The app can even guess if you have sleep apnea. However, we don’t recommend that you use this as a diagnostic tool. Always consult a doctor! It’s a great way to get some insight into how you sleep and it comes with plenty of alarm clock functionality as well.

Sleepzy

Price: Free / Up to $39.99

Sleepzy (formerly Good Morning Alarm Clock) is one of the relatively newer clock apps. It also tries to track your sleep as well as wake you up. Of course, that means sleeping with your phone in your bed. Aside from that, it works well. Some of the more unusual features include a white noise generator, weather update features, a nightstand mode, and more. The sleep tracking is a bit rudimentary, but it may work for some people.

Thank you for reading! Try these too:

If we missed any of the best alarm clock apps for Android, tell us about them in the comments!You can also click here to check out our latest Android app and game lists!

Источник

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