cosc 4730

Download cosc  4730

Post on 25-Feb-2016




0 download

Embed Size (px)


cosc 4730. Android App Widgets. App Widgets. App Widgets are miniature application views that can be embedded in other applications (such as the Home screen and lock screen) and receive periodic updates. - PowerPoint PPT Presentation


cosc 4755

cosc 4730Android App WidgetsApp WidgetsApp Widgets are miniature application views that can be embedded in other applications (such as the Home screen and lock screen) and receive periodic updates. These views are referred to as Widgets in the user interface, and you can publish one with an App Widget provider. An application component that is able to hold other App Widgets is called an App Widget host. Example: Music App Widget.

BasicsYou need the following:AppWidgetProviderInfo objectDescribes the metadata for an App Widget, such as the App Widget's layout, update frequency, and the AppWidgetProvider class. Defined in XML.View layoutDefines the initial layout for the App Widget, defined in XMLAppWidgetProvider class implementationDefines the basic methods that allow you to programmatically interface with the App Widget, based on broadcast events. This is a BroadcastReceiver.An Optional Activity, that can be used to configure the app. Note its required (as far as I can) in 4.2 or the widget will not work.Basics (2)The AppWidgetProvider implements the onRecieve() method of the BroadcastReceiver and then calls:OnEnabled() when first instance is added to homescreenonDisabled() when last instance removed from homescreenonDelete() when the widget is removed from homescreenonUpdate() called for every update of the widget.

A note, your widget can be added to the homescreen more then once.Basics(3)BroadcastReceiverregistered to receive system messages and Intents.A BroadcastReceiver will get notified by the Android system, if the specified situation happens. For example a BroadcastReceiver could get called once the Android system completed the boot process or if a phone call is received. In the case of app widgets, an example is a click eventServices (for advanced, but good place to define it)perform background tasks without providing a user interface. They can notify the user via the notification framework in Android. Manifestfile.xmlIn the application section, we will have the activity and we need to add the broadcastreceiver and intent-filter

widget_info is the xml file that describes the widget in xml.Note widget_info is just a file name and your file can have different names. (or more then one if you have multiple widgets).AppWidgetProviderInfo My file is called widget_info.xml in res/xml directoryeclipse created the xml directory for me

AppWidgetProviderInfo (2)Attributes:minWidth and minHeight is minimum space an App widget uses by default.1 cell is 40 dp, 2 is 110dp, 3 cells are 180dp, 4 celss are 250dp. It recommended you dont use more then 4x4 as default, because of screen size.both height and widthSee to determine size.AppWidgetProviderInfo (3)updatePeriodMillisHow often an update to this widget is made.A note, it can wake up every couple of minutes, but this will really drain the battery. This wakeup will happen even when the phone is asleep.Google recommends no more lower then 30 minutes and prefers an hour.Setting to 0, means it will not update without user interventation.AppWidgetProviderInfo (4)initialLayout points to layout resource the widget uses.Configure points to the activity the app uses to configure it self on launch (optional)Example: edu.cs4730.widgetdemo.confActivityThe rest of for v3.0+ and aboveminResizeWidth and minResizeHeight are how small it can be resized toandroid:resizeMode="horizontal|vertical" allows the widget to be resized in both"keyguard|home_screen" allows the widget to on the homescreen and the lockscreen.There are a couple more as well for previews and other stuff.View layout.There will be in two pieces.widget layout and the background layoutThe layout in the app is a RemoteViews and has limited support for widgets and layouts FrameLayout, LinearLayout, and RelativeLayoutAnalogClock, Button, Chronometer, ImageButton, ImageView, ProgressBar, and TextViewv3.0+ added: GridLayout, ViewFlipper, ListView, GridView, StackView, and AdapterViewFlipperThe adapter is for a collection view widget.

Example layout

This is the background xml, that well createnext.Other then the background, then standard layout file


In /res/drawable/myshape.xmlSee For more information on shapes.App TutorialThis is a very simple widget.Its a button that displays a random numberIt will update every thirty minutes1800000 millisecondsAlso registers a OnClickListener so random number updates when the user clicks on it.

AppWidgetProviderBecause the app is simple enough we will only use the onUpdate method

Remember our widget can be placed on the homescreen multiple times, so have to deal with all of themA note, I cant seem to find how to just update one of them.AppWidgetProvider (2)public class Example extends AppWidgetProvider {

@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {// Get all idsComponentName thisWidget = new ComponentName(context, Example.class);int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);for (int widgetId : allWidgetIds) { // Create some random data int number = (new Random().nextInt(100)); RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.example); // Set the text remoteViews.setTextViewText(, String.valueOf(number));//next set the listener.AppWidgetProvider (3) // Register an onClickListener Intent intent = new Intent(context, Example.class);

intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(, pendingIntent); appWidgetManager.updateAppWidget(widgetId, remoteViews); } }

Config activityThe activity that is launched at the time the widget is put on the homescreen.Its intended to configure the widget.This is a normal activity with one exceptionIt must use setResult(RESULT_OK, result value) and finish() or the widget will not be installed on the homescreen.In the AppWidgetProviderInfo the following line is needed:android:configure="edu.cs4730.widgetdemo2.Widgetd2Config Widgetd2Conf is the activity now and the rest is the package. is provided as an example.This functions as the lecture has explained. But the configuration uses sharedPreferences, so no matter how many widgets are placed on the screen, they use the same info and all update when one of them is clicked.

If at some point, I can figure out how to get widget controlled separately, Ill post and the preferences will be changed as well.AdvancedA BroadcastReceiver must finish the onReceive() in 5 seconds or less.So for long actions (network access as example)So we create a service to run in the background from the onUpdate(), which can then update the widget (and take as long as needed as well).See the for how to integrate the service into the provider.ReferencesSee and .zip on the handout pages for source code.