获取Android App的经纬度(getLastKnownLocation为null)

时间:2014-11-19 11:51:32

标签: android google-maps gps

我想在我的应用中获取当前位置的经纬度。我正在测试Galaxy Wi-Fi 5.0。我只需要双格式的数字,因为我将在google-maps-url中使用它。问题是lm.getLastKnownLocation(LocationManager.GPS_PROVIDER)返回null,我得到一个nullpointerexception。

private void getLatitudeLongitude()
{
        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if(location != null) {
            showMyAddress(location);
        }

        final LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                showMyAddress(location);
            }

            public void onProviderDisabled(String arg0) {
                // TODO Auto-generated method stub

            }

            public void onProviderEnabled(String arg0) {
                // TODO Auto-generated method stub

            }

            public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                // TODO Auto-generated method stub

            }
        };

        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);


        Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());   
        try {
            System.out.println(myLocation.getFromLocation(latitude, longitude, 1).toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

private void showMyAddress(Location location) {
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());   
    try {
        System.out.println( myLocation.getFromLocation(latitude, longitude, 1).toString());

    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

0 个答案:

没有答案