I am trying to get the zipcode for the users current location for later use in the program.
I've narrowed down the issue to the .getLatitude()
and .getLongitude()
. For some reason, the latitude and longitude is never set with the methods. Does anyone know why this is and how I can fix it? (I did set the permissions for the fine and coarse locations.) My code is below:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView t = (TextView)findViewById(R.id.TextView01);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3600, 1000, new LocationListener()
{
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onLocationChanged(Location loc)
{
if(loc != null)
{
lat = (int)(loc.getLatitude());
lon = (int)(loc.getLongitude());
}
}
});
t.setText("Lat: " + lat + " and long: " + lon);
Geocoder geo = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try
{
addresses = geo.getFromLocation(lat, lon, 1);
}
catch (IOException e)
{
t.setText("Could not find the Zip Code");
}
if(addresses.equals(null))
t.setText("Couldn't find the zip code");
else
{
zipcode = addresses.get(0).getPostalCode();
t.setText("Zip Code: " + zipcode);
}
}
这两个链接可能会为您提供帮助。. 该博客提供了带有示例代码的出色解释,您也可以参考第二个链接。 使用Gps可以进行检查
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.