14.01.2013 Views

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8: Working in the Background<br />

256<br />

6. The EarthquakeService will now update the earthquake provider each time it is asked to<br />

refresh, as well as on an automated schedule (if one is specifi ed). This information is not yet<br />

passed back to the Earthquake Activity’s ListView or the EathquakeMap Activity.<br />

To alert those components, and any other applications interested in earthquake data, modify the<br />

EarthquakeService to broadcast a new Intent whenever a new earthquake is added.<br />

6.1. Modify the addNewQuake method to call a new announceNewQuake method.<br />

public static final String NEW_EARTHQUAKE_FOUND = “New_Earthquake_Found”;<br />

private void addNewQuake(Quake _quake) {<br />

ContentResolver cr = getContentResolver();<br />

// Construct a where clause to make sure we don’t already have this<br />

// earthquake in the provider.<br />

String w = EarthquakeProvider.KEY_DATE +<br />

“ = “ + _quake.getDate().getTime();<br />

}<br />

// If the earthquake is new, insert it into the provider.<br />

Cursor c = cr.query(EarthquakeProvider.CONTENT_URI, null, w, null, null);<br />

if (c.getCount()==0){<br />

ContentValues values = new ContentValues();<br />

values.put(EarthquakeProvider.KEY_DATE, _quake.getDate().getTime());<br />

values.put(EarthquakeProvider.KEY_DETAILS, _quake.getDetails());<br />

double lat = _quake.getLocation().getLatitude();<br />

double lng = _quake.getLocation().getLongitude();<br />

values.put(EarthquakeProvider.KEY_LOCATION_LAT, lat);<br />

values.put(EarthquakeProvider.KEY_LOCATION_LNG, lng);<br />

values.put(EarthquakeProvider.KEY_LINK, _quake.getLink());<br />

values.put(EarthquakeProvider.KEY_MAGNITUDE, _quake.getMagnitude());<br />

cr.insert(EarthquakeProvider.CONTENT_URI, values);<br />

announceNewQuake(_quake);<br />

}<br />

c.close();<br />

private void announceNewQuake(Quake quake) {<br />

}<br />

6.2. Within announceNewQuake, broadcast a new Intent whenever a new earthquake<br />

is found.<br />

private void announceNewQuake(Quake quake) {<br />

Intent intent = new Intent(NEW_EARTHQUAKE_FOUND);<br />

intent.putExtra(“date”, quake.getDate().getTime());<br />

intent.putExtra(“details”, quake.getDetails());<br />

intent.putExtra(“longitude”, quake.getLocation().getLongitude());<br />

intent.putExtra(“latitude”, quake.getLocation().getLatitude());<br />

intent.putExtra(“magnitude”, quake.getMagnitude());<br />

sendBroadcast(intent);<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!