如何使用FusedLocationProviderClient

时间:2017-07-09 00:55:21

标签: java android google-maps-android-api-2 android-fusedlocation

我想定期(比如说每2分钟)当前的位置更新为此我正在遵循官方文档,我编写了这段代码,但它没有每两分钟给出当前位置更新,即使在我正在通过的LocationRequest对象中指定在requestLocationUpdates()中,这里是代码:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

private FusedLocationProviderClient FusedLocationClient;
private GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

 SupportMapFragment map = 
  getSupportFragmentManager().findFragmentById(R.id.map));

  map.getMapAsync(this);

  FusedLocationClient LocationServices.getFusedLocationProviderClient(this);
}


@Override
public void onConnected(Bundle bundle) {
    FusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {

                    if (location != null) {
                        Log.i("MainActivity ", "" + location.getLongitude()) 
                    }
                }
            });
FusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
FusedLocationClient.requestLocationUpdates(requestLocation(), 
new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            for (Location location : locationResult.getLocations()) {
               Log.i("MainActivity ", "" + location.getLongitude());
               //not getting current location updates every 2 minutes
            }
        };

    },null);

}

@Override
public void onConnectionSuspended(int i) {}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}

4 个答案:

答案 0 :(得分:58)

这与我的other answer here类似,已更新为使用最近推出的FusedLocationProviderClient类。

为了将FusedLocationProviderClient与Google Map结合使用:

  1. 等到谷歌地图准备就绪

  2. 如果需要,请在运行时请求位置权限

  3. 授予权限后请求位置更新

  4. 获取用户的位置后更新Google地图

  5. 首先确保您至少使用版本11的Google Play服务,因为旧版本没有FusedLocationProviderClient类(较新版本也可以使用):

    dependencies {
        compile 'com.google.android.gms:play-services-maps:11.6.0'
        compile 'com.google.android.gms:play-services-location:11.6.0'
        //........
    }
    

    请注意,FusedLocationProviderClient存在于版本11.0.2中,但由于初始实现中存在错误,建议您仅在11.6.0及更高版本上使用此类。 来自文档:

      

    注意:建议使用Google Play服务版本11.6.0或   更高,包括此类的错误修复。

    这是完整的Activity类:

    public class MapsActivity extends AppCompatActivity
            implements OnMapReadyCallback {
    
        GoogleMap mGoogleMap;
        SupportMapFragment mapFrag;
        LocationRequest mLocationRequest;
        Location mLastLocation;
        Marker mCurrLocationMarker;
        FusedLocationProviderClient mFusedLocationClient;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            getSupportActionBar().setTitle("Map Location Activity");
    
            mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    
            mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
            mapFrag.getMapAsync(this);
        }
    
        @Override
        public void onPause() {
            super.onPause();
    
            //stop location updates when Activity is no longer active
            if (mFusedLocationClient != null) {
                mFusedLocationClient.removeLocationUpdates(mLocationCallback);
            }
        }
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mGoogleMap = googleMap;
            mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(120000); // two minute interval
            mLocationRequest.setFastestInterval(120000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    //Location Permission already granted
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                    mGoogleMap.setMyLocationEnabled(true);
                } else {
                    //Request Location Permission
                    checkLocationPermission();
                }
            }
            else {
                mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                mGoogleMap.setMyLocationEnabled(true);
            }
        }
    
        LocationCallback mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                List<Location> locationList = locationResult.getLocations();
                if (locationList.size() > 0) {
                    //The last location in the list is the newest
                    Location location = locationList.get(locationList.size() - 1);
                    Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
                    mLastLocation = location;
                    if (mCurrLocationMarker != null) {
                        mCurrLocationMarker.remove();
                    }
    
                    //Place current location marker
                    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(latLng);
                    markerOptions.title("Current Position");
                    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
                    mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
    
                    //move map camera
                    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
                }
            }
        };
    
        public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
        private void checkLocationPermission() {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
    
                // Should we show an explanation?
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
    
                    // Show an explanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.
                    new AlertDialog.Builder(this)
                            .setTitle("Location Permission Needed")
                            .setMessage("This app needs the Location permission, please accept to use location functionality")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    //Prompt the user once explanation has been shown
                                    ActivityCompat.requestPermissions(MapsActivity.this,
                                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                            MY_PERMISSIONS_REQUEST_LOCATION );
                                }
                            })
                            .create()
                            .show();
    
    
                } else {
                    // No explanation needed, we can request the permission.
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            MY_PERMISSIONS_REQUEST_LOCATION );
                }
            }
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode,
                                               String permissions[], int[] grantResults) {
            switch (requestCode) {
                case MY_PERMISSIONS_REQUEST_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
                        // location-related task you need to do.
                        if (ContextCompat.checkSelfPermission(this,
                                Manifest.permission.ACCESS_FINE_LOCATION)
                                == PackageManager.PERMISSION_GRANTED) {
    
                            mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                            mGoogleMap.setMyLocationEnabled(true);
                        }
    
                    } else {
    
                        // permission denied, boo! Disable the
                        // functionality that depends on this permission.
                        Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                    }
                    return;
                }
    
                // other 'case' lines to check for other
                // permissions this app might request
            }
        }
    }
    

    系统将提示用户接受位置权限:

    enter image description here

    该位置将在应用启动时更新,每两分钟更新一次:

    enter image description here

答案 1 :(得分:3)

 mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            currentLocation = locationResult.getLastLocation();

        }
    };

这项工作对我而言。

答案 2 :(得分:-1)

    private LocationRequest locationRequest;

    public class MapsActivity extends FragmentActivity implements LocationListener{

    locationRequest = new LocationRequest();
    locationRequest.setInterval(60 * 1000);
    locationRequest.setFastestInterval(15 * 1000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


@Override
public void onLocationChanged(Location location) {

    latitude = location.getLatitude();
    longitude = location.getLongitude();

}

实施位置更改侦听器,您将能够覆盖已更改的位置...

答案 3 :(得分:-1)

为简单起见,请尝试使用此库https://github.com/mrmans0n/smart-location-lib。这将使用融合位置提供程序。

您只需输入此代码

SmartLocation.with(context).location(new LocationBasedOnActivityProvider(callback))
    .start(new OnLocationUpdatedListener() { ... });