{"id":1878,"date":"2013-06-13T13:15:28","date_gmt":"2013-06-13T13:15:28","guid":{"rendered":"http:\/\/truelogic.org\/wordpress\/?p=1878"},"modified":"2013-06-13T13:15:28","modified_gmt":"2013-06-13T13:15:28","slug":"scheduling-task-run-repeatedly-android","status":"publish","type":"post","link":"https:\/\/truelogic.org\/wordpress\/2013\/06\/13\/scheduling-task-run-repeatedly-android\/","title":{"rendered":"Scheduling a Task to run repeatedly in Android"},"content":{"rendered":"            <script type=\"text\/javascript\" src=\"https:\/\/truelogic.org\/wordpress\/wp-content\/plugins\/wordpress-code-snippet\/scripts\/shBrushJava.js\"><\/script>\n<p><a href=\"https:\/\/truelogic.org\/wordpress\/wp-content\/uploads\/2013\/06\/pugg-wall-clock__13080_PE040801_S4.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"alignleft size-medium wp-image-1951\" alt=\"pugg-wall-clock__13080_PE040801_S4\" src=\"https:\/\/truelogic.org\/wordpress\/wp-content\/uploads\/2013\/06\/pugg-wall-clock__13080_PE040801_S4-300x300.jpg\" width=\"300\" height=\"300\" srcset=\"https:\/\/truelogic.org\/wordpress\/wp-content\/uploads\/2013\/06\/pugg-wall-clock__13080_PE040801_S4-300x300.jpg 300w, https:\/\/truelogic.org\/wordpress\/wp-content\/uploads\/2013\/06\/pugg-wall-clock__13080_PE040801_S4-150x150.jpg 150w, https:\/\/truelogic.org\/wordpress\/wp-content\/uploads\/2013\/06\/pugg-wall-clock__13080_PE040801_S4-110x110.jpg 110w, https:\/\/truelogic.org\/wordpress\/wp-content\/uploads\/2013\/06\/pugg-wall-clock__13080_PE040801_S4.jpg 500w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a>There are times when an app needs to run at specific times without user intervention. Something very similar to cronjobs in Linux and Scheduled Tasks in Windows.<\/p>\n<p>Android has a built-in AlarmManager class which makes scheduling tasks very easy.<\/p>\n<p>What we will do is to setup an Activity to be run at 00:01:00 every day i.e 1 minute past midnight.<\/p>\n<p>There are 3 steps to doing this:<\/p>\n<ol>\n<li>Check if the AlarmManager already has our schedule configured<\/li>\n<li>Set up the task in AlarmManager<\/li>\n<li>Write code which will get activated at the scheduled time<\/li>\n<\/ol>\n<p><strong>WHAT IS A PENDING INTENT<\/strong><\/p>\n<p>Assuming you are familiar with the concept of an Intent, a Pending Intent is granting another app the permission and rights to execute a piece of your own code. In other words, its like giving power of attorney. So if App A gives a Pending Intent to App B, then App B can execute the Pending Intent code, even if App A is not running.<\/p>\n<p>To schedule a task in AlarmManager requires creating a Pending Intent and passing it to the AlarmManager.<\/p>\n<p><strong>THE MAIN CODE<\/strong><\/p>\n<p>The sample code below checks if the task has been already scheduled. If not then it creates the task in AlarmManager.<\/p>\n<p><pre class=\"brush: java\">\t\t\t\t\/\/ check task is scheduled or not\r\n\t\tboolean alarmUp = (PendingIntent.getBroadcast(this, 0, \r\n\t\t        new Intent(&quot;com.example.dummy.AlarmReceiver&quot;), \r\n\t\t        PendingIntent.FLAG_NO_CREATE) != null);\r\n\t\t\r\n\t\tif (  !alarmUp) {\r\n\t\t\tIntent intent = new Intent(&quot;com.example.dummy.AlarmReceiver&quot;);\r\n\t\t\tintent.putExtra(&quot;activate&quot;, true);\r\n\t\t\tPendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, \r\n\t\t\t                                      intent, PendingIntent.FLAG_UPDATE_CURRENT);\r\n\t\t\t\r\n\t\t\tCalendar calendar = Calendar.getInstance();\r\n\t\t\tcalendar.setTimeInMillis(System.currentTimeMillis());\r\n\t\t\tcalendar.set(Calendar.HOUR_OF_DAY, 0);   \r\n\t\t\tcalendar.set(Calendar.MINUTE, 1);\r\n\t\t\tcalendar.set(Calendar.SECOND, 0);\r\n\r\n\t\t\tAlarmManager alarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE);\r\n\t\t\talarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);\r\n\t\t\t\r\n\t\t\tcalendar = Calendar.getInstance();\r\n\t\t\tcalendar.setTimeInMillis(System.currentTimeMillis());\r\n\t\t\tcalendar.set(Calendar.HOUR_OF_DAY, 7);   \r\n\t\t\tcalendar.set(Calendar.MINUTE, 0);\r\n\r\n\t\t\talarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE);\r\n\t\t\tPendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 1, \r\n                    intent, PendingIntent.FLAG_UPDATE_CURRENT);\r\n\t\t\talarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent2);\t\t\t\r\n\t\t\t\r\n\t\t}\r\n\t\t<\/pre><\/p>\n<p>So what we are doing above is , query for a PendingIntent which matches our Activity class name which will run at the scheduled time.\u00a0 The flag PendingIntent.FLAG_NO_CREATE is important otherwise if it does not find our class scheduled as a PendingIntent, it will automatically create it.\u00a0 If the task is not already scheduled, then we go ahead and create it.<\/p>\n<p>Note that the Activity in which we are querying for and creating the schedule IS NOT the same Activity which will be called on activation.\u00a0 So from Activity A we are creating a PendingIntent for Activity B.<\/p>\n<p>Below is the Activity which gets called by the AlarmManager. This Activity extends <em>BroadcastReceiver<\/em> and overrides the\u00a0<em> onReceive()<\/em> method . We also check if the String value\u00a0 &#8220;activate&#8221; has been passed in<em> getExtra() .\u00a0 <\/em>This is the signal that AlarmManager has activated the task.<\/p>\n<p><pre class=\"brush: java\">public class AlarmReceiver extends BroadcastReceiver { \r\n\t\r\n    @Override\r\n    public void onReceive(Context context, Intent intent) {\r\n    \t\r\n    \tif (!intent.hasExtra(&quot;activate&quot;)) {\r\n            \/\/ ignore this part\r\n    \t\t\r\n    \t}\r\n\t\t\t\t\r\n\t\t\/\/\/ your processing code comes here\r\n\r\n    }\r\n}<\/pre><\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>There are times when an app needs to run at specific times without user intervention. Something very similar to cronjobs in Linux and Scheduled Tasks <a class=\"mh-excerpt-more\" href=\"https:\/\/truelogic.org\/wordpress\/2013\/06\/13\/scheduling-task-run-repeatedly-android\/\" title=\"Scheduling a Task to run repeatedly in Android\">[&#8230;]<\/a><\/p>\n<\/div>","protected":false},"author":1,"featured_media":1951,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[295],"tags":[],"class_list":["post-1878","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android-dev"],"_links":{"self":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/1878","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/comments?post=1878"}],"version-history":[{"count":7,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/1878\/revisions"}],"predecessor-version":[{"id":1953,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/1878\/revisions\/1953"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/media\/1951"}],"wp:attachment":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/media?parent=1878"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/categories?post=1878"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/tags?post=1878"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}