单击按钮时如何获取当前的地理位置?

时间:2017-11-06 12:42:55

标签: android geolocation

我希望能够检索用户当前的地理位置(纬度,经度)并在按下Android按钮时将其显示到TextView中。我尝试了一些不同的策略(Android developer location strategies)但它没有显示任何位置。

我认为这与用户移动时调用“onLocationChanged()”方法这一事实有关,但我找不到任何文档。

这是我的代码(minSdkVersion是24,这就是我设置the requesting permissions strategy的原因)

CreateCustomStepActivity

public class CreateCustomStepActivity extends AppCompatActivity {
private TextView showLocation;
private Button scanGeolocationButton;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1400;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_custom_step);
    showLocation = (TextView) findViewById(R.id.showLocationTextId);
    scanGeolocationButton = (Button) findViewById(R.id.scanPositionButtonId);
    scanGeolocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (ContextCompat.checkSelfPermission(CreateCustomStepActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(CreateCustomStepActivity.this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
            }
        }
    });
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                getCurrentGeolocation();
        }
    }
}

private void getCurrentGeolocation() {
    // Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager) CreateCustomStepActivity.this.getSystemService(Context.LOCATION_SERVICE);
    LocationListener locationListener = new UserLocationListener();
    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
        // 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;
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
// Define a listener that responds to location updates
private class UserLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {
        String longitude = "Longitude: " + loc.getLongitude();
        String latitude = "Latitude: " + loc.getLatitude();
        String s = longitude + "\n" + latitude;
        showLocation.setText(s);
    }

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

实施GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener

GoogleApiClient

中添加onCreate
mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

connectdisconnect来自mGoogleApiClientonStart的{​​{1}}

onStop

onConnected

mLocationRequest = LocationRequest.create(); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setInterval(10); // Update location every second LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 中,要获取onLocationChanged的输出,请在此处绑定视图:

textview