2016-11-13 151 views
0

我想获得当前设备位置和开放Google Maps本:Android的位置监听器不工作

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) { 
    } 
} 

但这种代码是不工作:出于某些原因听众被忽略。

为什么以及如何解决它?

+0

为什么你实例位置监听器为'LocationListener的LocationListener的=新MyLocationListener();'而不是'MyLocationListener LocationListener的=新MyLocationListener();' – Jordan

回答

2

“为什么......”

因为requestLocationUpdates()是asynchorous操作和结果(位置)在onLocationChanged()回调返回。该位置不可立即使用。

“...以及如何解决它?”

移动你的谷歌地图有意向代码:

@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); 

} 
+1

我的理解是,您还需要取消注册您的位置侦听器以避免泄露活动 - 请参阅['removeUpdates'](https://developer.android.com/reference/android/location/LocationManager.html#removeUpdates (android.location.LocationListener))方法。 – clownba0t

+0

@Markus我改变了,问题仍然在这里,我试图调试这个,似乎onLocationChanged()不叫.. – VLeonovs

+1

这可能需要一段时间的位置获得。您设置的刷新周期时间间隔为5000毫秒,是刷新之间的_minimum_时间段。由于几个原因可能会更长。您还指定了最小距离为10米,因此导致位置移动距离不超过10米的位置更改将不会返回给您。考虑将其设置为0,至少在最初时。 – clownba0t