Книга: Beginning Android
Lobbing One Over the Fence
Lobbing One Over the Fence
Classic IPC is one-way: the client calls functions on the service. It is possible, through the creative use of AIDL, to allow the service to call back into an activity. However, this is a bit fragile, as the service may not know if the activity is still around or if it has been killed off to free up some memory.
An alternative approach, first mentioned in Chapter 23 which discusses Intent
filters, is to have the service send a broadcast Intent that can be picked up by the activity… assuming the activity is still around and is not paused. We will examine the client side of this exchange in Chapter 31; for now, let us examine how the service can send a broadcast.
The theory behind the WeatherPlusService
implementation is that the service gets “tickled” when the device (or emulator) position changes. At that point, the service calls out to the Web service and generates a new forecast Web page for the activity to display. At the same time, though, the service also sends a broadcast, to alert the activity that there is a page update available if it wants it.
Here is the high-level implementation of the aforementioned flow:
private void updateForecast(Location loc) {
String url = String.format(format, loc.getLatitude(),
loc.getLongitude());
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandlerString responseHandler = new BasicResponseHandler();
String responseBody = client.execute(getMethod, responseHandler);
String page = generatePage(buildForecasts(responseBody));
synchronized(this) {
forecast = page;
}
sendBroadcast(broadcast);
} catch (Throwable t) {
android.util.Log.e("WeatherPlus",
"Exception in updateForecast()", t);
}
}
Much of this is similar to the equivalent piece of the original Weather demo — perform the HTTP request, convert that into a set of Forecast
objects, and turn those into a Web page. The first difference is that the Web page is simply cached in the service, since the service cannot directly put the page into the activity’s WebView
. The second difference is that we call sendBroadcast()
, which takes an Intent
and sends it out to all interested parties. That Intent is declared up front in the class prologue:
private Intent broadcast = new Intent(BROADCAST_ACTION);
Here, BROADCAST_ACTION
is simply a static String
with a value that will distinguish this Intent from all others:
public static final String BROADCAST_ACTION =
"com.commonsware.android.service.ForecastUpdateEvent";
- 4.4.4 The Dispatcher
- About the author
- Chapter 7. The state machine
- Appendix E. Other resources and links
- Example NAT machine in theory
- The final stage of our NAT machine
- Compiling the user-land applications
- The conntrack entries
- Untracked connections and the raw table
- Basics of the iptables command
- Other debugging tools
- Setting up user specified chains in the filter table