Android位置侦听器无法正常工作

时间:2016-11-13 17:44:53

标签: android google-maps location

我想获取当前的设备位置,然后打开Google Maps

  if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener locationListener = new MyLocationListener();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);


    } else {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_LOCATION_REQUEST_CODE);
    }




private class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {

        longitude = loc.getLongitude();
        latitude = loc.getLatitude();

        Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=" + latitude + "," + longitude + "&daddr=55.877526, 26.533898"));
        startActivity(intent);
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}

但是这段代码不起作用:由于某些原因,侦听器被忽略了。

为什么以及如何解决它?

1 个答案:

答案 0 :(得分:2)

  

"为什么..."

因为requestLocationUpdates()是异步操作,并且onLocationChanged()回调中返回了结果(位置)。该位置无法立即使用。

  

" ...以及如何修复它?"

将Google地图意图代码移到那里:

@Override
public void onLocationChanged(Location loc) {

    longitude = loc.getLongitude();
    latitude = loc.getLatitude();

    Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=" + latitude + "," + longitude + "&daddr=55.877526, 26.533898"));
    startActivity(intent);

}