I decide to put the GPS location recording answer into a new post to make things cleaner.
Recording GPS Coordinates
The first thing we need to do is add a line into our AndroidManifest.xml saying we want to be allowed to record GPS coordinates:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" .... >
....
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>
(I put in those ....
to represent that I was omitting some content)
Next you have to add the android:onClick="functionToCall"
to the each of the button tags (see my other answer for more detail). The button tags should look something like this:
<Button android:text="Start"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startButton"></Button>
<Button android:text="Stop"
android:id="@+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="stopButton"></Button>
Now you have to ask the system for the LocationManager
, which we can give a LocationListener
to use when a location is recieved. We will give the LocationManager
the LocationListener
when the start button is hit and remove that listener when the stop button is hit. That LocationListener
will call a function to store the location.
Here is the code to do that:
package com.TrackLocation;
import java.util.ArrayList;
//Ommitted rest of the imports
public class TrackLocation extends Activity {
ArrayList<Location> recordedLocations = new ArrayList<Location>();
LocationManager locationManager;
LocationListener locationListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the manager from the system
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Create the locationListener that we will be adding and removing
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
recordLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
}
public void recordLocation(Location loc) {
recordedLocations.add(loc);
}
public void startButton(View view) {
//Add the listener asking for GPS
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
public void stopButton(View view) {
locationManager.removeUpdates(locationListener);
}
}
The above code doesn't do much with the values (in fact you can't even see the locations without using the debugger), but I wanted to keep this as small as possible. I have fuller version of the code that will display the locations in a ListView
. Here is the link to that fuller version.