Can't get location on application startup
I am trying to develop little application which at startup shows the name of current location in a toast or something. The code I wrote will show a Toast on the display with the loc开发者_Go百科ation only is I send the coordinates manually from the Emulator Control View from Eclipse.
My question: Is there a way to force somehow this sending of coordinates at the startup, because I want that Toast when the application is loaded? And how can I do it? Thanks.
Here is the code:
public class HomeActivity extends Activity implements LocationListener {
private LocationManager locationManager;
private String welcomeMsg;
private String crtLocationName;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initLocationManager();
}
private void initLocationManager(){
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 5000, this);
}
*/
@Override
public void onLocationChanged(Location location) {
if (location != null) {
try {
crtLocationName = getLocationName(location);
Toast.makeText( getApplicationContext(), crtLocationName, Toast.LENGTH_LONG).show();
} catch (IOException e) {
welcomeMsg = "Location cannot be determined";
crtLocationName = "";
}
// locationManager.removeUpdates(this);
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
As Emulator doesn't have a GPS receiver, the method onLocationChanged
will be only invoked when you give some new coordinates through DDMS.
On the real phone, it will not show a Toast instantly; it will wait before it locates the GPS satellite and receive a GPS fix, then it will show the Toast message.
精彩评论