本文介绍了Android Location侦听器无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取当前设备的位置并使用以下命令打开Google Maps:

I would like to get current device location and open Google Maps with this:

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

但是此代码无法正常工作:由于某些原因,监听器将被忽略.

But this code is not working: for some reasons listener is ignored.

为什么以及如何解决?

推荐答案

因为requestLocationUpdates()是异步操作,并且结果(位置)在onLocationChanged()回调中返回.该位置无法立即显示.

Because requestLocationUpdates() is an asynchorous operation and the result (the location) is returned in the onLocationChanged() callback. The location isn't available immediately.

将您的Google地图意图代码移到此处:

Move your Google map intent code there:

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

}

这篇关于Android Location侦听器无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 21:27