How to use updated gps location data in main android activity?
I have googled alot of questions and forums and could not find an answer so I hope this question does not repeat. If so, please direct me to the primary question.
Ok the thing is I do not know how to update gps location in android and then actually use this value in main activity. So I have a layout composed of two TextViews, one displaying longitude and another for displaying latitude. I have set one LocationManager, LocationListener (to update location) and then i call requestLocationUpdates() on my LocationManager as instructed in this tutorial http://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/
I use same onCreate and LocationListener methods as in tutorial above. As you can see onLocationChanged() makes a toast in this tutorial, but I would like to change text of my TextViews. Could you please show me how can I use values from getLongitude() (and similar methods) in my main activity.
public void onLocationChanged(Location loc)
{
loc.getLatit开发者_如何学Cude();
loc.getLongitude();
String Text = “My current location is: “ +
“Latitud = “ + loc.getLatitude() +
“Longitud = “ + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}
in your main activity, after onCreate
and setContentView
you need
EditText lat = new EditText findViewById(R.id.lat_view);
EditText lon = new EditText findViewById(R.id.lon_view);
(or whatever your lat & lon textviews are called in xml)
and then in your onLocationChanged
add
lat.setText(loc.getLatitude);
lon.setText(loc.getLongitude);
you might need to make the EditText
s static, im not in front of eclipse atm.
from your main activity pass the textview in constructor of MyLocationListener(referring to tutorial you used).So basically you have to define a constructor in MyLocationListener
public class MyLocationListener implements LocationListener {
Context context;
TextView tv;
public MyLocationListener(Context context,TextView tv){
this.context=context;
this.tv=tv;
}
public void onLocationChanged(Location loc) {
tv.setText("your text comes here");
}
}
and in main activity
TextView tv = (TextView) findViewById(R.id.yourTextViewId);
LocationListener mlocListener = new MyLocationListener(getApplicationContext(),tv);
精彩评论