Android Programming Tutorials

(Romina) #1
Posts On Location

Change onOptionsItemSelected() in Patchy to look like this:


@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.prefs) {
startActivity(new Intent(this, EditPreferences.class));

return(true);
}
else if (item.getItemId()==R.id.location) {
insertLocation();

return(true);
}

return(super.onOptionsItemSelected(item));
}

Then, add in the following implementation of insertLocation() in Patchy:


private void insertLocation() {
Location loc=locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (loc==null) {
Toast
.makeText(this, "No location available", Toast.LENGTH_SHORT)
.show();
}
else {
StringBuilder buf=new StringBuilder(status
.getText()
.toString());
buf.append(" L:");
buf.append(String.valueOf(loc.getLatitude()));
buf.append(",");
buf.append(String.valueOf(loc.getLongitude()));
status.setText(buf.toString());
}
}

You will need to add an import for android.widget.Toast, used to handle the


case where we do not have a GPS fix yet. Otherwise, if we have a fix, we


create a piece of text in Twittervision format, using the Location object, and


inject that into the EditText for the status.


Now, if you recompile and reinstall Patchy, and if you use DDMS to supply a


fake location (assuming you are running this on an emulator), the location


231
Free download pdf