如何在Android上获取用户的当前位置?

时间:2017-08-27 22:49:57

标签: java android location

我一直在尝试使用融合位置API获取用户的位置大约一周,完全按照此处所述https://developer.android.com/training/location/retrieve-current.html 但我没有得到任何结果。有时它的工作原理,但主要是它没有,这只是在虚拟设备上,在真实设备上没有发生。 这是我的MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                10);
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                10);
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    Log.v("","the beg");
    mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        // ...
                        Log.v("", String.valueOf(location.getLatitude()));
                        Log.v("", String.valueOf(location.getLongitude()));
                    }
                }
            });
    Log.v("","the end");
}

} 这是我的Android.m

1 个答案:

答案 0 :(得分:0)

首先,定义LocationListener以处理位置更改。

private final LocationListener mLocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(final Location location) {
        //your code here
    }
};

然后获取LocationManager并要求进行位置更新

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
LOCATION_REFRESH_TIME,
            LOCATION_REFRESH_DISTANCE, mLocationListener);
}

最后确保您已在Manifest上添加了权限,

仅使用基于网络的位置使用此

对于基于GPS的位置,这一个