{"id":54,"date":"2013-06-04T03:09:43","date_gmt":"2013-06-04T03:09:43","guid":{"rendered":"https:\/\/code4reference.com\/?p=54"},"modified":"2013-06-04T03:09:43","modified_gmt":"2013-06-04T03:09:43","slug":"code4referencetutorial-on-android-widget-with-alarmmanager","status":"publish","type":"post","link":"https:\/\/code4reference.com\/?p=54","title":{"rendered":"Code4ReferenceTutorial on Android widget with Alarmmanager"},"content":{"rendered":"<p>This is a follow up tutorial on\u00a0<a href=\"http:\/\/code4reference.com\/2012\/07\/android-widget-tutorial\/\">Android widget<\/a>. If you haven\u2019t read it till now then please go through \u00a0 \u00a0it before starting this tutorial. You may be aware that AppWidgetProvider\u2019s lowest interval is 30 mins. In this tutorial we will learn \u00a0to create widget with update interval less than 30 mins using AlarmManager.<\/p>\n<p>In Android 4.1, a new feature has been introduced\u00a0for Homescreen widget\u00a0which enables widget to\u00a0reorganize\u00a0its view when resized.\u00a0To support this feature a\u00a0new method <strong><em>onAppWidgetOptionsChanged()<\/em><\/strong> has been introduced in AppWidgetProvider class. This method gets called in response\u00a0to the <strong><em>ACTION_APPWIDGET_OPTIONS_CHANGED<\/em><\/strong> broadcast when this widget has been layed out at a new size.\u00a0<\/p>\n<p><strong>Project Information:<\/strong>\u00a0 Meta-information about the project.<\/p>\n<p><strong>Platform Version :<\/strong> Android API Level 16.<br \/>\n<strong>IDE :<\/strong> Eclipse Helios Service Release 2<br \/>\n<strong>Emulator:<\/strong> Android 4.1<\/p>\n<p><strong>Prerequisite:<\/strong>\u00a0Preliminary\u00a0knowledge of Android application framework, Intent Broadcast receiver and AlarmManager.<\/p>\n<h4>Example with fixed update interval less than 30 mins.<\/h4>\n<p>In this tutorial we will create time widget which shows current time. This widget will get updated every second and we will be using AlarmManager for it. Here, repeating alarm is set for one second interval. But in real world scenario, it is not recommended to use one second repeating alarm because it drains the battery fast. You have to follow the similar steps mentioned in previous widget tutorial \u00a0to write widget layout file. But this time we are introducing a TextView field in the layout which will display the time. The content of the <strong>\u201ctime_widget_layout.xml\u201d<\/strong> is given below.<\/p>\n<pre>\n\n\n     \n\n\n<\/pre>\n<p>Follow the same procedure to create the AppWidgetProvider metadata file. The content of metadata file<em>\u00a0\u201dwidget_metadata.xml\u201d<\/em> is given below.<\/p>\n<pre>\n\n\n<\/pre>\n<p>In this tutorial, onEnabled(), onDsiabled(), onUpdate() and onAppWidgetOptionsChanged() have been defined unlike the previous <a href=\"http:\/\/code4reference.com\/2012\/07\/android-widget-tutorial\/\">widget tutorial<\/a> where only onUpdate() was defined.<\/p>\n<ul>\n<li><strong>onEnabled():<\/strong> An instance of AlarmManager is created here to start the repeating timer and register the intent with the AlarmManager.\u00a0\u00a0As this method gets called at the very first instance of widget installation, it helps to set repeating alarm\u00a0\u00a0only once.<\/li>\n<li><strong>onDisabled():<\/strong>\u00a0In this method, alarm is canceled because this method gets called as soon as the very last instance of widget is removed\/uninstalled and we don\u2019t want to leave the registered alarm even when it\u2019s not being used.<\/li>\n<li><strong>onUpdate():<\/strong> This method updates the time on remote TextView.<\/li>\n<li><strong>onAppWidgetOptionsChanged():<\/strong> This method gets called when the widget is resized.<\/li>\n<\/ul>\n<pre>\npackage com.rakesh.widgetalarmmanagerexample;\n\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.appwidget.AppWidgetManager;\nimport android.appwidget.AppWidgetProvider;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.widget.RemoteViews;\nimport android.widget.Toast;\n\npublic class TimeWidgetProvider extends AppWidgetProvider {\n\n @Override\n public void onDeleted(Context context, int[] appWidgetIds) {\n  Toast.makeText(context, \"TimeWidgetRemoved id(s):\"+appWidgetIds, Toast.LENGTH_SHORT).show();\n  super.onDeleted(context, appWidgetIds);\n }\n\n @Override\n public void onDisabled(Context context) {\n  Toast.makeText(context, \"onDisabled():last widget instance removed\", Toast.LENGTH_SHORT).show();\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  super.onDisabled(context);\n }\n\n @Override\n public void onEnabled(Context context) {\n  super.onEnabled(context);\n  AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);\n  Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);\n  PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);\n  \/\/After after 3 seconds\n  am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ 1000 * 3, 1000 , pi);\n }\n\n @Override\n public void onUpdate(Context context, AppWidgetManager appWidgetManager,\n   int[] appWidgetIds) {\n  ComponentName thisWidget = new ComponentName(context,\n    TimeWidgetProvider.class);\n\n  for (int widgetId : appWidgetManager.getAppWidgetIds(thisWidget)) {\n\n   \/\/Get the remote views\n   RemoteViews remoteViews = new RemoteViews(context.getPackageName(),\n     R.layout.time_widget_layout);\n   \/\/ Set the text with the current time.\n   remoteViews.setTextViewText(R.id.tvTime, Utility.getCurrentTime(\"hh:mm:ss a\"));\n   appWidgetManager.updateAppWidget(widgetId, remoteViews);\n  }\n }\n\n @Override\n public void onAppWidgetOptionsChanged(Context context,\n   AppWidgetManager appWidgetManager, int appWidgetId,\n   Bundle newOptions) {\n  \/\/Do some operation here, once you see that the widget has change its size or position.\n  Toast.makeText(context, \"onAppWidgetOptionsChanged() called\", Toast.LENGTH_SHORT).show();\n }\n}\n<\/pre>\n<p>Broadcast receiver is defined to handle the intent registered with alarm. This broadcast receiver gets called every second because repeating alarm has been set in the AppWidgetProvider classs for 1 second. Here, onReceive() method has been defined which updates the widget with the current time and getCurrentTime() has been used to get the current time.<\/p>\n<pre>\npackage com.rakesh.widgetalarmmanagerexample;\n\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.appwidget.AppWidgetManager;\nimport android.content.BroadcastReceiver;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.PowerManager;\nimport android.widget.RemoteViews;\nimport android.widget.Toast;\n\npublic class AlarmManagerBroadcastReceiver extends BroadcastReceiver {\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 update the widget\/remote views.\n  RemoteViews remoteViews = new RemoteViews(context.getPackageName(),\n    R.layout.time_widget_layout);\n  remoteViews.setTextViewText(R.id.tvTime, Utility.getCurrentTime(\"hh:mm:ss a\"));\n  ComponentName thiswidget = new ComponentName(context, TimeWidgetProvider.class);\n  AppWidgetManager manager = AppWidgetManager.getInstance(context);\n  manager.updateAppWidget(thiswidget, remoteViews);\n  \/\/Release the lock\n  wl.release();\n }\n}\n<\/pre>\n<p>It\u2019s always a good idea to keep utility methods in some utility class which can be accessed from other packages. getCurrentTime() has been defined in the Uitility class. This method is used in AppWidgetProvider and BroadcastReciever classes.<\/p>\n<pre>\npackage com.rakesh.widgetalarmmanagerexample;\n\nimport java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\npublic class Utility {\n  public static String getCurrentTime(String timeformat){\n      Format formatter = new SimpleDateFormat(timeformat);\n         return formatter.format(new Date());\n     }\n}\n\n<\/pre>\n<p>In Android manifest file, we need to include WAKE_LOCK permission because wake lock is used in broadcast receiver. AlarmManagerBroadcastReceiver has been registered as broadcast receiver. Remaining part is simple to understand.<\/p>\n<pre>\n\n  \n    \n\n\n    \n        \n            \n                \n                \n            \n        \n        \n            \n                \n            \n            \n        \n        \n    \n\n<\/pre>\n<p>Once the code is executed, the widget gets registered. When you install widget on homescreen, it appears as shown below.<\/p>\n<p><a href=\"http:\/\/3.bp.blogspot.com\/-8Phd-Ro6JkI\/T_j6kIyysrI\/AAAAAAAAAi8\/xaHFhyvrB3U%20like\/s1600\/Android-homescreen-widget-alarmmanager.png\"><img alt='android-homescreen-widget-alarmmanager-7267442' src='https:\/\/code4reference.com\/wp-content\/uploads\/2013\/06\/Android-homescreen-widget-alarmmanager-7267442.png' \/><\/a><\/p>\n<p>you can download source code from <a href=\"http:\/\/github.com\/rakeshcusat\/Code4Reference\/tree\/master\/AndroidProjects\/WidgetAlarmManagerExample\">here<\/a>.<\/p>\n<h4>Related tutorial:<\/h4>\n<ul>\n<li><a href=\"http:\/\/code4reference.com\/2012\/07\/android-widget-tutorial\/\">Tutorial on Homescreen widget<\/a><\/li>\n<li><a href=\"http:\/\/code4reference.com\/2012\/07\/tutorial-on-android-alarammanager\/\">Tutorial on Android AlarmManager<\/a><\/li>\n<\/ul>\n<p>Your valuable comments are always welcomed. It will help to improve my post and understanding.<\/p>\n<p><em>\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<\/em><br \/>\nBy : Confucius<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This is a follow up tutorial on\u00a0Android widget. If you haven\u2019t read it till now then please go through \u00a0 \u00a0it before starting this tutorial. You may be aware that AppWidgetProvider\u2019s lowest interval is 30 mins. In this tutorial we will learn \u00a0to create widget with update interval less than 30 mins using AlarmManager. In [&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-54","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/54","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=54"}],"version-history":[{"count":0,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/54\/revisions"}],"wp:attachment":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=54"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=54"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=54"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}