android="
android:
minWidth="294dp"
--density-independentpixels-->
android:
minHeight="72dp"
android:
updatePeriodMillis="86400000"
--onceperday-->
android:
initialLayout="@layout/example_appwidget"
android:
configure="com.example.android.ExampleAppWidgetConfigure">
Here'sasummaryoftheattributes:
•ThevaluesfortheminWidthandminHeightattributesspecifytheminimumarearequiredbytheAppWidget'slayout.
ThedefaultHomescreenpositionsAppWidgetsinitswindowbasedonagridofcellsthathaveadefinedheightandwidth.IfthevaluesforanAppWidget'sminimumwidthorheightdon'tmatchthedimensionsofthecells,thentheAppWidgetdimensionsrounduptothenearestcellsize.(SeetheAppWidgetDesignGuidelinesformoreinformationontheHomescreencellsizes.)
BecausetheHomescreen'slayoutorientation(andthus,thecellsizes)canchange,asaruleofthumb,youshouldassumetheworst-casecellsizeof74pixelsfortheheightandwidthofacell.However,youmustsubtract2fromthefinaldimensiontoaccountforanyintegerroundingerrorsthatoccurinthepixelcount.Tofindyourminimumwidthandheightindensity-independentpixels(dp),usethisformula:
(numberofcells*74)–2
Followingthisformula,youshoulduse72dpforaheightofonecell,294dpandforawidthoffourcells.
•TheupdatePeriodMillisattributedefineshowoftentheAppWidgetframeworkshouldrequestanupdatefromtheAppWidgetProviderbycallingtheonUpdate()method.Theactualupdateisnotguaranteedtooccurexactlyontimewiththisvalueandwesuggestupdatingasinfrequentlyaspossible—perhapsnomorethanonceanhourtoconservethebattery.Youmightalsoallowtheusertoadjustthefrequencyinaconfiguration—somepeoplemightwantastocktickertoupdateevery15minutes,ormaybeonlyfourtimesaday.
Note:
Ifthedeviceisasleepwhenitistimeforanupdate(asdefinedbyupdatePeriodMillis),thenthedevicewillwakeupinordertoperformtheupdate.Ifyoudon'tupdatemorethanonceperhour,thisprobablywon'tcausesignificantproblemsforthebatterylife.If,however,youneedtoupdatemorefrequentlyand/oryoudonotneedtoupdatewhilethedeviceisasleep,thenyoucaninsteadperformupdatesbasedonanalarmthatwillnotwakethedevice.Todoso,setanalarmwithanIntentthatyourAppWidgetProviderreceives,usingtheAlarmManager.SetthealarmtypetoeitherELAPSED_REALTIMEorRTC,whichwillonlydeliverthealarmwhenthedeviceisawake.ThensetupdatePeriodMillistozero("0").
•TheinitialLayoutattributepointstothelayoutresourcethatdefinestheAppWidgetlayout.
•TheconfigureattributedefinestheActivitytolaunchwhentheuseraddstheAppWidget,inorderforhimorhertoconfigureAppWidgetproperties.Thisisoptional(readCreatinganAppWidgetConfigurationActivitybelow).
SeetheAppWidgetProviderInfoclassformoreinformationontheattributesacceptedbytheelement.
CreatingtheAppWidgetLayout
YoumustdefineaninitiallayoutforyourAppWidgetinXMLandsaveitintheproject'sres/layout/directory.YoucandesignyourAppWidgetusingtheViewobjectslistedbelow,butbeforeyoubegindesigningyourAppWidget,pleasereadandunderstandtheAppWidgetDesignGuidelines.
CreatingtheAppWidgetlayoutissimpleifyou'refamiliarwithDeclaringLayoutinXML.However,youmustbeawarethatAppWidgetlayoutsarebasedonRemoteViews,whichdonotsupporteverykindoflayoutorviewwidget.
ARemoteViewsobject(and,consequently,anAppWidget)cansupportthefollowinglayoutclasses:
•FrameLayout
•LinearLayout
•RelativeLayout
Andthefollowingwidgetclasses:
•AnalogClock
•Button
•Chronometer
•ImageButton
•ImageView
•ProgressBar
•TextView
Descendantsoftheseclassesarenotsupported.
UsingtheAppWidgetProviderClass
YoumustdeclareyourAppWidgetProviderclassimplementationasabroadcastreceiverusingtheelementintheAndroidManifest(seeDeclaringanAppWidgetintheManifestabove).
TheAppWidgetProviderclassextendsBroadcastReceiverasaconvenienceclasstohandletheAppWidgetbroadcasts.TheAppWidgetProviderreceivesonlytheeventbroadcaststhatarerelevanttotheAppWidget,suchaswhentheAppWidgetisupdated,deleted,enabled,anddisabled.Whenthesebroadcasteventsoccur,theAppWidgetProviderreceivesthefollowingmethodcalls:
onUpdate(Context,AppWidgetManager,int[])
ThisiscalledtoupdatetheAppWidgetatintervalsdefinedbytheupdatePeriodMillisattributeintheAppWidgetProviderInfo(seeAddingtheAppWidgetProviderInfoMetadataabove).ThismethodisalsocalledwhentheuseraddstheAppWidget,soitshouldperformtheessentialsetup,suchasdefineeventhandlersforViewsandstartatemporaryService,ifnecessary.However,ifyouhavedeclaredaconfigurationActivity,thismethodisnotcalledwhentheuseraddstheAppWidget,butiscalledforthesubsequentupdates.ItistheresponsibilityoftheconfigurationActivitytoperformthefirstupdatewhenconfigurationisdone.(SeeCreatinganAppWidgetConfigurationActivitybelow.)
onDeleted(Context,int[])
ThisiscalledeverytimeanAppWidgetisdeletedfromtheAppWidgethost.
onEnabled(Context)
ThisiscalledwhenaninstancetheAppWidgetiscreatedforthefirsttime.Forexample,iftheuseraddstwoinstancesofyourAppWidget,thisisonlycalledthefirsttime.IfyouneedtoopenanewdatabaseorperformothersetupthatonlyneedstooccuronceforallAppWidgetinstances,thenthisisagoodplacetodoit.
onDisabled(Context)
ThisiscalledwhenthelastinstanceofyourAppWidgetisdeletedfromtheAppWidgethost.ThisiswhereyoushouldcleanupanyworkdoneinonEnabled(Context),suchasdeleteatemporarydatabase.
onReceive(Context,Intent)
Thisiscalledforeverybroadcastandbeforeeachoftheabovecallbackmethods.Younormallydon'tneedtoimplementthismethodbecausethedefaultAppWidgetProviderimplementationfiltersallAppWidgetbroadcastsandcallstheabovemethodsasappropriate.
Note:
InAndroid1.5,thereisaknownissueinwhichtheonDeleted()methodwillnotbecalledwhenitshouldbe.Toworkaroundthisissue,youcanimplementonReceive()asdescribedinthisGroupposttoreceivetheonDeleted()callback.
ThemostimportantAppWidgetProvidercallbackisonUpdated()becauseitiscalledwheneachAppWidgetisaddedtoahost(unlessyouuseaconfigurationActivity).IfyourAppWidgetacceptsanyuserinteraction