I'm writing an Android App that uses my GPS Location. My code is very simple.
public class MyActivityThing extends Activity {
Location l;
MyLocationListener locationListener;
LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.car, menu);
return true;
}
public void setHotColdLocation(View view)
{
l = locationListener.getCurrentLocation();
}
}
Here is my MyLocationListener
public class MyLocationListener implements LocationListener {
private static Location thelocation;
@Override
public void onLocationChanged(Location location) {
thelocation = location;
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
public Location getCurrentLocation()
{
return thelocation;
}
}
My situation is this. I have a button that onClick
calls the setHotColdLocation
method in MyActivityThing
.
My question is, how should I ensure that the location is set when the user presses the button? The onLocationChanged
method is not called immediately, so when the app first starts I can press the button and cause an exception....
Should I make the button invisible until the location is called?
Should I just enclose the contents of setHotColdLocation
in a try catch and throw away the users clicks until the location is set?
I can think of tons of ways to make it work, but I don't know the best one...or the right one.
Any help?
Another way to put it is that your button can start a task that ultimately sets the location.