简体   繁体   English

无法在Android中获取位置

[英]Trouble getting the location in android

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() . 我将问题缩小为.getLatitude().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可以进行检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM