{"id":127,"date":"2013-07-05T04:38:22","date_gmt":"2013-07-05T04:38:22","guid":{"rendered":"https:\/\/code4reference.com\/?p=127"},"modified":"2023-10-01T13:30:49","modified_gmt":"2023-10-01T13:30:49","slug":"code4referencetutorial-on-android-alarmmanager","status":"publish","type":"post","link":"https:\/\/code4reference.com\/?p=127","title":{"rendered":"Tutorial on Android AlarmManager"},"content":{"rendered":"<p>While writing an application, need arises to schedule execution of code in future. You may require AlarmManager to schedule your work at a specified time. AlarmManager\u00a0accesses to system alarm and schedules the execution of code even when the application is not running.<\/p>\n<p><b>Project Information:<\/b>\u00a0 Meta-information about the project.<\/p>\n<p>Platform Version : Android API Level 10.IDE : Eclipse Helios Service Release 2<\/p>\n<p>Emulator: Android 4.1<\/p>\n<p><b>Prerequisite:<\/b>\u00a0Preliminary\u00a0knowledge of Android application framework, and Intent Broadcast receiver.<\/p>\n<p>AlarmManager has access to the system alarm services. With the help of AlarmManager you can schedule execution of code in future. AlarmManager object can\u2019t\u00a0instantiate\u00a0directly however it can be retrieved by calling <i><b>Context.getSystemService(Context.ALARM_SERVICE)<\/b><\/i>. AlarmManager is always registered with intent. When an alarm goes off, the Intent which has been registered with AlarmManager, is broadcasted by the system automatically. This intent starts the target application if it is not \u00a0running. It is recommended to use AlarmManager when you want your application code to be run at a specific time, even if your application is not currently running. For other timing operation handler should be used because it is easy to use. Handler is covered in other tutorial.<\/p>\n<table>\n<tr>\n<th>Method<\/th>\n<th>Description<\/th>\n<\/tr>\n<tr>\n<td>set()<\/td>\n<td>Schedules an alarm for one time.<\/td>\n<\/tr>\n<tr>\n<td>setInexactRepeating()<\/td>\n<td>Schedules an alarm with inexact repeating. Trigger time doesn\u2019t follow any strict restriction.<\/td>\n<\/tr>\n<tr>\n<td>setRepeating()<\/td>\n<td>Schedules an alarm with exact repeating time.<\/td>\n<\/tr>\n<tr>\n<td>setTime()<\/td>\n<td>Sets the system\u2019s wall clock time.<\/td>\n<\/tr>\n<tr>\n<td>setTimeZone()<\/td>\n<td>Sets the system\u2019s default time zone.<\/td>\n<\/tr>\n<\/table>\n<p>Check out the <a href=\"http:\/\/developer.android.com\/reference\/android\/app\/AlarmManager.html\">AlarmManager documention<\/a> for more info.<\/p>\n<p>In this tutorial let\u2019s learn to create one-time timer and the repeating timer, and also to cancel the repeating timer. Here timer and alarm have been used\u00a0interchangeably, but in this tutorial context both of them have the same meaning.<\/p>\n<h4>Example Code:<\/h4>\n<p>Let\u2019s create three buttons <b><i>start repeating timer, cancel repeating timer<\/i><\/b>\u00a0and <b>one-time timer<\/b>\u00a0in the layout file. These buttons are attached with<b>\u00a0<\/b>methods i.e\u00a0startRepeatingTimer,\u00a0cancelRepeatingTimer and\u00a0onetimeTimer respecitively. These methods will be defined in the Activity class. The layout file is shown below(activity_alarm_manager.xml).<\/p>\n<pre>\n \n\n    \n    \n     \n   \n<\/pre>\n<p>We are going to define the BroadcastReciever which handles the intent registered with AlarmManager. In the given class onReceive() method has been defined. This method gets invoked as soon as intent is received. Once we receive the intent we try to get the extra parameter associated with this intent. This extra parameter is user-defined i.e ONE_TIME, basically indicates whether this intent was associated with one-time timer or the repeating one. Once the ONE_TIME parameter value has been extracted, Toast message is \u00a0displayed\u00a0accordingly. Helper methods have also been defined, which can be used from other places with the help of objects i.e\u00a0<b>setAlarm(), cancelAlarm() and onetimeTimer()<\/b> methods. These methods can also be defined\u00a0somewhere\u00a0else to \u00a0do operation on the timer i.e set, cancel, etc. To keep this tutorial simple, we have defined it in BroadcastReceiver.<\/p>\n<p>\n<b>setAlarm():<\/b>\u00a0This method sets the repeating alarm by use of setRepeating() method. setRepeating() method needs four arguments:<\/p>\n<ol>\n<li>type of alarm,\u00a0<\/li>\n<li>trigger time: set it to the current time<\/li>\n<li>interval in milliseconds: in this example we are passing 5 seconds ( 1000 * 5 milliseconds)<\/li>\n<li>pending intent: It will get registered with this alarm. When the alarm gets triggered the pendingIntent will be broadcasted.<\/li>\n<\/ol>\n<p><b>cancelAlarm()<\/b>: This method cancels the previously registered alarm by calling cancel() method. cancel() method takes pendingIntent as an argument. The pendingIntent should be matching one, only then the cancel() method can remove the alarm from the system.<\/p>\n<p><b>onetimeTimer():<\/b> This method creates an one-time alarm. This can be achieved by calling set() method. set() method takes three arguments:<\/p>\n<ol>\n<li>type of alarm<\/li>\n<li>trigger time\u00a0<\/li>\n<li>pending intent<\/li>\n<\/ol>\n<pre>\npackage com.rakesh.alarmmanagerexample;\n\nimport java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.os.PowerManager;\nimport android.widget.Toast;\n\npublic class AlarmManagerBroadcastReceiver extends BroadcastReceiver {\n\n final public static String ONE_TIME = \"onetime\";\n\n @Override\n public void onReceive(Context context, Intent intent) {\n   PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);\n         PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, \"YOUR TAG\");\n         \/\/Acquire the lock\n         wl.acquire();\n\n         \/\/You can do the processing here.\n         Bundle extras = intent.getExtras();\n         StringBuilder msgStr = new StringBuilder();\n         \n         if(extras != null &amp;&amp; extras.getBoolean(ONE_TIME, Boolean.FALSE)){\n          \/\/Make sure this intent has been sent by the one-time timer button.\n          msgStr.append(\"One time Timer : \");\n         }\n         Format formatter = new SimpleDateFormat(\"hh:mm:ss a\");\n         msgStr.append(formatter.format(new Date()));\n\n         Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();\n         \n         \/\/Release the lock\n         wl.release();\n }\n\n public void SetAlarm(Context context)\n    {\n        AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);\n        Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);\n        intent.putExtra(ONE_TIME, Boolean.FALSE);\n        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);\n        \/\/After after 5 seconds\n        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi); \n    }\n\n    public void CancelAlarm(Context context)\n    {\n        Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);\n        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);\n        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n        alarmManager.cancel(sender);\n    }\n\n    public void setOnetimeTimer(Context context){\n     AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);\n        Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);\n        intent.putExtra(ONE_TIME, Boolean.TRUE);\n        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);\n        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);\n    }\n}\n\n<\/pre>\n<p>Given below is the manifest file. Here, WAKE_LOCK permission is required because the wake lock is being used while processing in onReceive() method present in AlarmManagerBroadcastReceiver class. AlarmManagerBroadcastReceiver has been registered as broadcast receiver.<\/p>\n<pre>\n\n\n   \n   \n    \n        \n            \n                \n                \n          \n        \n        \n        \n    \n\n<\/pre>\n<p>Now let\u2019s define the activity class which defines some methods. These methods are going to handle the button clicks. Here in this class we create an instance of AlarmManagerBroadcastReciever which will help us to access setAlarm(), cancelAlarm() and setOnetime(). Rest of the code is easy to understand.<\/p>\n<pre>\npackage com.rakesh.alarmmanagerexample;\n\nimport com.rakesh.alarmmanagerexample.R;\nimport android.os.Bundle;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.Toast;\nimport android.support.v4.app.NavUtils;\n\npublic class AlarmManagerActivity extends Activity {\n\n private AlarmManagerBroadcastReceiver alarm;\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_alarm_manager);\n        alarm = new AlarmManagerBroadcastReceiver();\n    }\n    \n    @Override\n protected void onStart() {\n  super.onStart();\n }\n\n    public void startRepeatingTimer(View view) {\n     Context context = this.getApplicationContext();\n     if(alarm != null){\n      alarm.SetAlarm(context);\n     }else{\n      Toast.makeText(context, \"Alarm is null\", Toast.LENGTH_SHORT).show();\n     }\n    }\n    \n    public void cancelRepeatingTimer(View view){\n     Context context = this.getApplicationContext();\n     if(alarm != null){\n      alarm.CancelAlarm(context);\n     }else{\n      Toast.makeText(context, \"Alarm is null\", Toast.LENGTH_SHORT).show();\n     }\n    }\n    \n    public void onetimeTimer(View view){\n     Context context = this.getApplicationContext();\n     if(alarm != null){\n      alarm.setOnetimeTimer(context);\n     }else{\n      Toast.makeText(context, \"Alarm is null\", Toast.LENGTH_SHORT).show();\n     }\n    }\n    \n @Override\n    public boolean onCreateOptionsMenu(Menu menu) {\n        getMenuInflater().inflate(R.menu.activity_widget_alarm_manager, menu);\n        return true;\n    }\n}\n<\/pre>\n<p>Once you are done with the coding, just execute the project and you will find the similar kind of application running in your emulator.<\/p>\n<table>\n<tr>\n<td><a href=\"http:\/\/2.bp.blogspot.com\/-kZc22gg7VZ0\/T_cv2yc3sUI\/AAAAAAAAAiM\/g3d8P7E1rG0\/s1600\/alarm-manager-application.png\"><img alt='alarm-manager-application-5963574' src='https:\/\/code4reference.com\/wp-content\/uploads\/2013\/07\/alarm-manager-application-5963574.png' \/><\/a><\/td>\n<td><a href=\"http:\/\/4.bp.blogspot.com\/-NazLmX2i_t0\/T_cw07MITSI\/AAAAAAAAAic\/CVPIbUdMplY\/s1600\/onetime-timer-alarm-manager.png\"><img alt='onetime-timer-alarm-manager-8675606' src='https:\/\/code4reference.com\/wp-content\/uploads\/2013\/07\/onetime-timer-alarm-manager-8675606.png' \/><\/a><\/td>\n<\/tr>\n<\/table>\n<p>Please download <a href=\"http:\/\/github.com\/rakeshcusat\/Code4Reference\/tree\/master\/AndroidProjects\/AlarmManagerExample\">AlarmManagerExample code<\/a>, if you need reference code.<br \/>\nYour valuable comments are always welcomed. It will help to improve my post and understanding.<\/p>\n<p><i>\u201cBy three methods we may learn wisdom: First, by reflection, which is noblest; Second, by imitation, which is easiest; and third by experience, which is the bitterest.\u201d<\/i><br \/>\nBy : Confucius<\/p>\n","protected":false},"excerpt":{"rendered":"<p>While writing an application, need arises to schedule execution of code in future. You may require AlarmManager to schedule your work at a specified time. AlarmManager\u00a0accesses to system alarm and schedules the execution of code even when the application is not running. Project Information:\u00a0 Meta-information about the project. Platform Version : Android API Level 10.IDE [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-127","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/127","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=127"}],"version-history":[{"count":1,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/127\/revisions"}],"predecessor-version":[{"id":270,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/127\/revisions\/270"}],"wp:attachment":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=127"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=127"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=127"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}