|
Page 1 of 5 One of the coolest things about Android is the use of Widgets - the small "mini-apps" you add to your homescreen to get immediate information and functionality, often without even having to launch an app. Think of the weather ones, the fancy clocks, the stock price reporters or the RSS news feeds for example - they all update their displays without the user doing anything. There's clearly some magic going on behind the scenes here which may appear mysterious to the typical "app only" Android coder.
Twitter recently dropped their REST API which meant developers had to adopt one of the new authentication methods to use their services. So, here's a combination of the two - a Widget which just sends tweets using the new OAuth Twitter API.
How do widgets work?
The best way to think of Widgets is as extensions to regular apps, almost as if they're special windows into their inner workings. I say this because they appear so different you could be forgiven for thinking there's some whole new kind of app which is managed separately from regular apps. Well, widgets do have special considerations but for the most part everything you know about normal app development still applies. They've got some restrictions which aren't immediately obvious too, but I'll cover those as we get to them. Here's how the TwitterWidget looks:

The biggest difference from a developers point of view is the fact that Widgets are in fact broadcast receivers. This seems a strange relationship at first since you're probably used to thinking of these as part of an internal Android feature which you can use to intercept silent events in the background, such as incoming SMS's and phone calls. That's all true, but to understand why it's been done this way you need to understand how Widgets are run.
Widget Host
The fact a Widget exists on the home screen tells you straight away it interacts with another app, since the home screen is in fact an app all by itself. The home screen can show your Widget because it's also what Android calls an App Widget Host, i.e. an app which supports the management and control of Widgets. As pointed out ealier, our Widget is just an extension to a regular app, so in effect what we're doing is controlling another app, the App Widget Host, from ours using messages - hence the use of broadcast receivers. There's a rough parallel to a regular apps lifecycle, such as the onCreate(), onPause() etc callbacks we're used to but these all arrive as broadcast messages targetted at your Widget and include onEnabled(), onUpdate() etc.
|