Java 类com.google.android.gms.location.LocationServices 实例源码

项目:VennTracker    文件:MapsActivity.java   
private void getLocation() {
    /*if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.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;
    }*/
    checkLocationPermission();
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mCircleSnap && mLastLocation != null) {
        LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
    }
}
项目:Runnest    文件:LocationSettingsHandler.java   
/**
 * Check whether gps is turned on or not.
 */
public boolean checkLocationSettings() {
    // In case of a test session don't check settings
    if (((AppRunnest) activity.getApplication()).isTestSession()) {
        return true;
    }

    if (!gpsIsTurnedOn) {
        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(
                googleApiClient,
                locationSettingsRequest);
        result.setResultCallback(this);
    }

    return gpsIsTurnedOn;
}
项目:TFG-SmartU-La-red-social    文件:FragmentMapa.java   
@Override
public void onConnected(@Nullable Bundle bundle) {
    //Compruebo los permisos de la localización
    //si no los tengo me salgo del método
    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        //Pongo mi localización en el mapa
        mMap.setMyLocationEnabled(true);
    }else
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

    //Obtengo la última localización conocida
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        miPosicion = new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude());
        if(mMap!=null)
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(miPosicion,12));
    }
}
项目:TFG-SmartU-La-red-social    文件:FragmentMapaProyecto.java   
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mBundle = savedInstanceState;
    if (getArguments() != null) {
        proyecto = getArguments().getParcelable(ARG_PROYECTO);
    }
    //Para localizar al usuario inicializo la variable de la API de Google Maps
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(getContext())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
}
项目:TFG-SmartU-La-red-social    文件:FragmentMapaProyecto.java   
@Override
public void onConnected(@Nullable Bundle bundle) {
    //Compruebo los permisos de la localización
    //si no los tengo me salgo del método
    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        //Pongo mi localización en el mapa
        mMap.setMyLocationEnabled(true);
    }else
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    //Obtengo la última localización conocida
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        miPosicion = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
        if (mMap != null)
            if (posicionProyecto != null)
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(posicionProyecto, 12));
            else
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(miPosicion, 12));
    }
}
项目:Shush    文件:Geofencing.java   
/**
 * Registers the list of geofences specified in mGeofenceList with Google Play Services
 * Uses {@code #mClient } to connect to google play services
 * Uses {@link #getGeofenceRequest()} to get the list of Geofences to be registered
 * Uses {@link #getGeofencePendingIntent()} to get the pending intent to launch the intent service
 * when the geofence is triggered
 * Triggers {@link #onResult(Result)} when the geofences have been registered successfully
 */
public void registerAllGeofences() {
    if (mClient == null || !mClient.isConnected()
            || mGeofenceList == null || mGeofenceList.size() == 0) {
        return;
    }

    try {
        LocationServices.GeofencingApi.addGeofences(mClient,
                getGeofenceRequest(),
                getGeofencePendingIntent()).setResultCallback(this);
    }
    catch (SecurityException securityException){
        securityException.printStackTrace();
    }
}
项目:proto-collecte    文件:MainActivity.java   
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_ALL_PERMISSIONS: {
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, R.string.persmissions_non_accordees, Toast.LENGTH_LONG);
                    return;
                }
            }

            finishIntialisation();
            initMap();
            // noinspection MissingPermission
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, createLocationRequest(), this);
            return;
        }
        // other 'case' lines to check for other
        // permissions this app might request
    }
}
项目:Remindy    文件:GeofenceUtil.java   
public static void addGeofences(final Context context, GoogleApiClient googleApiClient) {
    checkGoogleApiClient(googleApiClient);
    List<Place> places = new RemindyDAO(context).getActivePlaces();

    if(places.size() > 0) {
        if (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)) {
            LocationServices.GeofencingApi.addGeofences(
                    googleApiClient,
                    getGeofencingRequest(places),
                    getGeofencePendingIntent(context)
            ).setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    if(status.isSuccess())
                        Toast.makeText(context, "Geofences added/updated!", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

}
项目:MyGeofencer    文件:GeofencingController.java   
/**
 * Removes geofences, which stops further notifications when the device enters or exits
 * previously registered geofences.
 */
public void removeGeofences() {
    if (!mGoogleApiClient.isConnected()) {
        Toast.makeText(context, context.getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
        return;
    }
    try {
        // Remove geofences.
        LocationServices.GeofencingApi.removeGeofences(
                mGoogleApiClient,
                // This is the same pending intent that was used in addGeofences().
                getGeofencePendingIntent()
        ).setResultCallback(this); // Result processed in onResult().
    } catch (SecurityException securityException) {
        // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
        logSecurityException(securityException);
    }
}
项目:Dispatch    文件:LocationUpdaterService.java   
private void startLocationUpdates() {

     // set location interval updates
    initLocationRequest();

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Log.i(LOGSERVICE, "Permission not granted.");
        return;
    } else {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        buildGoogleApiClient();
        // enter current location in lat lng into firebase
        if (mUser.getUserID() != null) {
            mDatabase.child("users").child(mUser.getUserID()).child("latitude").setValue(userLocation.latitude);
            mDatabase.child("users").child(mUser.getUserID()).child("longitude").setValue(userLocation.longitude);
        } else {
            Toast.makeText(getApplicationContext(), "Current user not recognized. Try reauthenticating.",
                    Toast.LENGTH_LONG).show();
        }
    }
}
项目:civify-app    文件:LocationAdapter.java   
private void updateLocation() {
    Log.v(TAG, "Trying to update location...");
    if (isDelayedUpdate()) Log.v(TAG, "Detected delayed updates.");
    else {
        if (checkConnection()) {
            if (hasPermissions()) {
                setRequestingPermissions(true);
                LocationSettingsRequest.Builder builder =
                        new LocationSettingsRequest.Builder().addLocationRequest(
                                getLocationRequest()).setAlwaysShow(true);

                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
                        builder.build()).setResultCallback(getLocationSettingsResultCallback());
                Log.v(TAG, "Settings verification requested.");
            } else checkForPermissions();
        }
    }
}
项目:CustomAndroidOneSheeld    文件:GpsShield.java   
public void startGps() {
    mUpdatesRequested = true;
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setInterval(PERIOD);
    mLocationRequest.setFastestInterval(PERIOD);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // check Internet connection

    mLocationClient = new GoogleApiClient.Builder(getApplication())
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    if (mLocationClient != null)
        mLocationClient.connect();

}
项目:Moodr    文件:MapsActivity.java   
@Override
public void onConnected(Bundle bundle) {
    Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

    //mLocationRequest.setSmallestDisplacement(0.1F);

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
项目:Dispatch    文件:LocationUpdaterService.java   
@Override
public void onCreate() {
    Log.i(LOGSERVICE, "In onCreate");
    super.onCreate();

    // Build GoogleApiClient
    buildGoogleApiClient();

    // Firebase Authorization
    mAuth = FirebaseAuth.getInstance();
    mUserManager = new UserManager();

    // Set User event listener
    setUserEventListener();
    mUserManager.getUser(mAuth.getCurrentUser().getUid(), new IGetUserListener() {
        @Override
        public void onGetSingleUser(User retrievedUser) {
            mUser = retrievedUser;
        }
        @Override
        public void onFailedSingleUser() {
        }
    });

    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
}
项目:2017.2-codigo    文件:FusedLocationActivity.java   
@Override
@SuppressWarnings({"MissingPermission"})
public void run() {
    Location loc=LocationServices.FusedLocationApi.getLastLocation(playServices);
    //se nao tem objeto valido, agenda pra tentar daqui a pouco
    /*
    if (loc == null) {
        getListView().postDelayed(this, 1000);
    }
    else {
        adapter.add(loc);
    }
    /**/

    //implementacao alternativa
    if (loc != null) {
        adapter.add(loc);
    }
    //getListView().postDelayed(this, 5000);
}
项目:bikedeboa-android    文件:MapActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = DataBindingUtil.setContentView(this, R.layout.activity_maps);

    // Set listeners
    binding.menuDrawer.menuNavigationView.setNavigationItemSelectedListener(this);
    binding.placeSearch.setOnClickListener(placeSearchListener);
    binding.drawerButton.setOnClickListener(menuDrawerToggleListener);
    binding.filterButton.setOnClickListener(filterDrawerToggleListener);
    binding.myLocation.setOnClickListener(myLocationListener);

    // Create the location client to start receiving updates
    googleApiClient = new GoogleApiClient.Builder(getBaseContext())
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(map);
    mapFragment.getMapAsync(this);
}
项目:2017.2-codigo    文件:FusedLocationMapActivity.java   
@Override
public void onConnected(Bundle bundle) {

    //inicializa list view
    adapter=new ArrayAdapter<Location>(this, android.R.layout.simple_list_item_1, data);
    setListAdapter(adapter);

    //define requisicao para obter localizacao
    //objeto define quantos updates serao necessarios
    //deadline para desistir se nao conseguir obter location
    //intervalo
    //otimizacao de energia, caso aplicavel
    locationRequest = new LocationRequest()
            .setNumUpdates(5)
            .setExpirationDuration(60000)
            .setInterval(1000)
            .setPriority(LocationRequest.PRIORITY_LOW_POWER);


    LocationSettingsRequest.Builder b = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(playServices, b.build());
    result.setResultCallback(this);
}
项目:background-location-updates-android-o    文件:MainActivity.java   
/**
 * Builds {@link GoogleApiClient}, enabling automatic lifecycle management using
 * {@link GoogleApiClient.Builder#enableAutoManage(android.support.v4.app.FragmentActivity,
 * int, GoogleApiClient.OnConnectionFailedListener)}. I.e., GoogleApiClient connects in
 * {@link AppCompatActivity#onStart}, or if onStart() has already happened, it connects
 * immediately, and disconnects automatically in {@link AppCompatActivity#onStop}.
 */
private void buildGoogleApiClient() {
    if (mGoogleApiClient != null) {
        return;
    }
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .enableAutoManage(this, this)
            .addApi(LocationServices.API)
            .build();
    createLocationRequest();
}
项目:do-road    文件:MapFrag.java   
@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(lastLocation!=null) {
            LatLng center = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());

                mMap.addMarker(new MarkerOptions().position(center).title("Place Pickup here"));
                //pickUpMarker.setDraggable(true);
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(center, 10));
            }

        }
}
项目:Camera-warner    文件:LocationService.java   
@Override
public void onCreate() {
    super.onCreate();

    Log.d("LocationService", "onCreate");

    manager = new DataProviderManager();
    manager.addObserver(this);

    mClient = LocationServices.getFusedLocationProviderClient(this);

    //implementation of the location update callback
    //what happens when the service receives the user location is defined here
    callback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            lastLocation = locationResult.getLastLocation();
            Log.d("LocationService", "new location received");
            notifyUIOfNewPosition();
            //update the location providers with the new location
            manager.onLocationChanged(lastLocation);

            if (PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean(getString(R.string.pref_active_key), getResources().getBoolean(R.bool.pref_active_default))
                    && manager.isCameraNearerThan(Float.parseFloat(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString(getString(R.string.pref_radius_key), getString(R.string.pref_radius_default))), lastLocation)) {
                enableCameraWarning();
            } else {
                disableCameraWarning();
            }

        }
    };

    //build the notification for @see {@link #startForeground()} to keep the service from being killed
    startForeground(CAMERA_FOREGROUND_SERVICE_NOTIFICATION_ID, buildForegroundNotification());
}
项目:GitHub    文件:AddGeofenceObservable.java   
@Override
protected void onGoogleApiClientReady(GoogleApiClient apiClient, final Observer<? super Status> observer) {
    LocationServices.GeofencingApi.addGeofences(apiClient, request, geofenceTransitionPendingIntent)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        observer.onNext(status);
                        observer.onCompleted();
                    } else {
                        observer.onError(new StatusException(status));
                    }
                }
            });
}
项目:GitHub    文件:RemoveGeofenceByPendingIntentObservable.java   
@Override
protected void removeGeofences(GoogleApiClient locationClient, final Observer<? super Status> observer) {
    LocationServices.GeofencingApi.removeGeofences(locationClient, pendingIntent)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        observer.onNext(status);
                        observer.onCompleted();
                    } else {
                        observer.onError(new StatusException(status));
                    }
                }
            });
}
项目:background-location-updates-android-o    文件:MainActivity.java   
/**
 * Handles the Request Updates button and requests start of location updates.
 */
public void requestLocationUpdates(View view) {
    try {
        Log.i(TAG, "Starting location updates");
        LocationRequestHelper.setRequesting(this, true);
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, getPendingIntent());
    } catch (SecurityException e) {
       LocationRequestHelper.setRequesting(this, false);
        e.printStackTrace();
    }
}
项目:BonAppetit_Android-Project    文件:MapsActivity.java   
/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    //Prepare button and add padding when placed in Map
    final Button button = (Button) findViewById(R.id.share_location);
    button.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            mMap.setPadding(0, button.getHeight(), 0, 0);
        }
    });
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mMap.setMyLocationEnabled(true);
    } else {
        ActivityCompat.requestPermissions(this,PERMISSIONS_STORAGE,REQUEST_ACCESS);
    }
    try {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            LatLng ll = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            addPointToView(ll);
            mLastLocation = null;
        }
    }catch (NullPointerException ne){
        ne.printStackTrace();
    }

}
项目:GoMeet    文件:LocationMonitoringService.java   
@Override
public void onConnected(Bundle dataBundle) {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Log.e(TAG, "Permission not granted");
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this);
    Log.i(TAG, "Connected to Google API");
}
项目:proto-collecte    文件:CollecteService.java   
private void configureLocationConnection() {
        LocationRequest locationRequest = createLocationRequest();
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
        if (collecteActiverPref) {
            com.google.android.gms.common.api.PendingResult<LocationSettingsResult> locationSettingsResultPendingResult = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
            locationSettingsResultPendingResult
                    .setResultCallback(new ResultCallback<LocationSettingsResult>() {
                        @Override
                        public void onResult(LocationSettingsResult result) {
                            if (LocationSettingsStatusCodes.SUCCESS != result.getStatus().getStatusCode()) {
                                Intent localIntent = new Intent(Constants.GOOGLE_API).putExtra(Constants.GOOGLE_API_LOCATION_RESULT, result.getStatus());
                                LocalBroadcastManager.getInstance(CollecteService.this).sendBroadcast(localIntent);
                            }
                        }
                    });
            // noinspection MissingPermission : permissions dans le manifest
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
            //noinspection MissingPermission
//            mLocationManager.addNmeaListener(new GpsStatus.NmeaListener() {
//                @Override
//                public void onNmeaReceived(long l, String s) {
//                    boolean a = false;
//                }
//            });
        } else {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }
项目:Crimson    文件:SearchClinics.java   
@Override
public void onPause() {
    super.onPause();

    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}
项目:GitHub    文件:LocationUpdatesObservable.java   
@Override
protected void onGoogleApiClientReady(GoogleApiClient apiClient, final Observer<? super Location> observer) {
    listener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            observer.onNext(location);
        }
    };
    LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, listener);
}
项目:Remindy    文件:PlaceActivity.java   
private void moveCameraToLastKnownLocation() {

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (lastLocation != null) {
                moveCameraToLocation(lastLocation);
            }
        } else {
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_ACCESS_FINE_LOCATION_GET_LAST_LOCATION);
        }
    }
项目:ITagAntiLost    文件:LocationActivity.java   
@Override
public void onConnected(Bundle connectionHint) {
  if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
      != PackageManager.PERMISSION_GRANTED
      && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
      != PackageManager.PERMISSION_GRANTED) {
    requestLocationPermission();
    return;
  }
  if (currentLocation == null) {
    currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
  }
}
项目:Android-Client    文件:LocationService.java   
@Override
public void onConnected(@Nullable Bundle bundle) {
    //TODO: ask for permission at appropriate time
    LocationRequest locationRequest = new LocationRequest();
    locationRequest.setInterval(30000);
    locationRequest.setFastestInterval(30000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    if (Nammu.checkPermission(Manifest.permission.ACCESS_FINE_LOCATION)) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, LocationService.this);
    }
}
项目:react-native-connectivity-status    文件:RNConnectivityStatusModule.java   
/**
 * Asks to enable location services.
 */
@ReactMethod
public void enableLocation(final Promise promise) {
  mGoogleApiClient = new GoogleApiClient.Builder(getReactApplicationContext())
          .addApi(LocationServices.API)
          .addConnectionCallbacks(this)
          .addOnConnectionFailedListener(this)
          .build();

  mGoogleApiClient.connect();

  promise.resolve(true);
}
项目:flutter_geolocation    文件:GpsCoordinatesPlugin.java   
private void connectToGoogleClient() {
  ConnectionManager _connManager = new ConnectionManager();
  _client = new GoogleApiClient.Builder(_activity)
          .addConnectionCallbacks(_connManager)
          .addOnConnectionFailedListener(_connManager)
          .addApi(LocationServices.API)
          .build();
  _locationRequest = new LocationRequest()
          .setInterval(5)
          .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
  _client.connect();
}
项目:Runnest    文件:ChallengeActivity.java   
private void setupGoogleApi() {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}
项目:IelloAndroidAdminApp    文件:MappaGoogle.java   
/**
 * Costruttore della classe. Inizializza i componenti della mappa.
 */
public MappaGoogle(MainActivity a) {
    mMainActivity = a;

    // inizializza la mappa
    final SupportMapFragment mapFragment =
            (SupportMapFragment) a.getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);


    // verifica se si dispone dell'autorizzazione alla posizione, ed eventualmente la chiede.
    // Per le versioni di android precedenti a M, il permesso è confermato automaticamente
    if (ActivityCompat.checkSelfPermission(mMainActivity,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
     && ActivityCompat.checkSelfPermission(mMainActivity,
            android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
     && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            mMainActivity.requestPermissions(new String[]
                            {android.Manifest.permission.ACCESS_FINE_LOCATION,
                             android.Manifest.permission.ACCESS_COARSE_LOCATION},
                    PERMISSION_CODE);

    } else {
        mGeoPermessoDisponibile = true;
    }

    // inizializza i servizi di localizzazione google
    mLocationProvider = LocationServices.getFusedLocationProviderClient(mMainActivity);
}
项目:iSPY    文件:MapsActivity3.java   
@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}
项目:Expert-Android-Programming    文件:SelectDeliveryAreaActivity.java   
private void checkPermissions() {
    if (!marshmallowPermission.checkPermissionForLocation()) {
        marshmallowPermission.requestPermissionForLocation();
    } else {

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        MyLg.e(TAG, "Start Listener");
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}
项目:Movie-Notifier-Android    文件:LocationUtil.java   
public void setupLocationClient(Context context) {
    if(locationClient == null) {
        if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationClient = LocationServices.getFusedLocationProviderClient(context);
        }
    }
}
项目:PrivacyStreams    文件:GoogleLocationUpdatesProvider.java   
@Override
protected void provide() {
    mGoogleApiClient = new GoogleApiClient.Builder(getContext())
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    if (!mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }
}
项目:proto-collecte    文件:MainActivity.java   
@Override
protected void onStop() {
    super.onStop();
    mTelephonyMgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
    //noinspection MissingPermission
    mLocationManager.removeGpsStatusListener(mGpsStatusListener);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mLocationReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mGoogleApiReceiver);
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
    if(marker != null) {
        marker.setTag(null);
    }
}