开发者

How does the Facebook for Android app's home screen widget work?

Actually this question applies to any widget that requires data from a remote server.

The answer would be pure speculation, but how do you think the widget gets its data? For those that don't know, the widget shows a history of your friends' latest status updates.

Some answers that I can think of:

  1. The widget polls the API directly
  2. The widget grabs data from some service that's running in the background, which polls the server
  3. Somehow Facebook implemented push on Android which I don't think exists
  4. The widget somehow detects that the user is using the screen and grabs the 开发者_开发知识库data on demand


I would say #1 or #2. Most likely #2 for the reasons jleedev gives in his answer.

Note that to implement an app widget you extend AppWidgetProvider, which is a BroadcastReceiver. This is simply a class that runs in the background and pushes updates to the widget on screen via RemoteViews. So what you are seeing on your home screen isn't an actual running Activity, it's just a fairly static view that is updated periodically via a special BroadcastReceiver. I say all this to show that there isn't much difference between your #1 and #2, as all homescreen app widget code you write runs in the background.

Also you can't really do #4. You can't detect when an app widget is on screen, unfortunately. The best you can do currently is schedule alarms to update your app widget, and use the flag that keeps those alarms from firing when the phone is asleep.


The Android SDK documentation refers to the sample Simple Wiktionary AppWidget. This runs a service that periodically pulls data from the Internet and pushes it back to the widget. Full source code is available.

The documentation says

If your App Widget setup process can take several seconds (perhaps while performing web requests) and you require that your process continues, consider starting a Service in the onUpdated() method... If you don't update more than once per hour, this probably won't cause significant problems for the battery life.


The widget that I wrote runs a service that periodically pulls data from the internet and pushes it to the widget. That seems to work well.


I would assume #2. The activity and the widget need to display the same content, so it makes sense to have a single service to download and cache the data. Widgets are defined to update on a certain interval, but that doesn’t necessarily have to be the same as how often the service downloads the data. Most apps I have that refresh periodically have a setting to control the refresh frequency, and I imagine that would be a setting on the service.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜