Finding user location

别说谁变了你拦得住时间么 提交于 2019-12-02 09:28:53

Try the following solution:

  • First, make sure you have implemented the correct LocationListener interface in your activity class:

     com.google.android.gms.location.LocationListener
    

Then request the appropriate permissions to support Android devices running v6.0

 private static final int MY_PERMISSION_REQUEST_READ_COARSE_LOCATION = 102;

Then request permission:

@Override
public void onConnected(@Nullable Bundle bundle) {

  // what version of android are you using?
  // Answer = 6.0

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
        ActivityCompat.requestPermissions(thisActivity,
              new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
              MY_PERMISSION_REQUEST_READ_COARSE_LOCATION);

    }

    Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mCurrentLocation != null) {
        Log.d(TAG, "current location: " + mCurrentLocation.toString());
        latitude = mCurrentLocation.getLatitude();
        longitude = mCurrentLocation.getLongitude();
    }

     startLocationUpdates();

}

To get the results from permission requests at runtime, override this method:

@Override
public void onRequestPermissionsResult(int requestCode,
    String permissions[], int[] grantResults) {
    switch (requestCode) {

      case MY_PERMISSION_REQUEST_READ_COARSE_LOCATION:~~~~~~~~~~~
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            // permission was granted, yay! Do the
            // contacts-related task you need to do.

        } else {

            // permission denied, boo! Disable the
            // functionality that depends on this permission.
        }
        break;
    }

    // other 'case' lines to check for other
    // permissions this app might request
  }
}

Then, your method to update location:

protected void startLocationUpdates() {
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(UPDATE_INTERVAL)
            .setFastestInterval(FASTEST_INTERVAL);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        //request permission here like you already do above
        return;
    }

    //there is a problem here because LocationListener is cast as an activity
       LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

This should do it;

Happy coding!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!