Java Code Examples for com.google.android.gms.location.LocationServices

The following are top voted examples for showing how to use com.google.android.gms.location.LocationServices. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: VennTracker   File: MapsActivity.java   Source Code and License 6 votes vote down vote up
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));
    }
}
 
Example 2
Project: Runnest   File: LocationSettingsHandler.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Project: TFG-SmartU-La-red-social   File: FragmentMapa.java   Source Code and License 6 votes vote down vote up
@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));
    }
}
 
Example 4
Project: TFG-SmartU-La-red-social   File: FragmentMapaProyecto.java   Source Code and License 6 votes vote down vote up
@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();
    }
}
 
Example 5
Project: TFG-SmartU-La-red-social   File: FragmentMapaProyecto.java   Source Code and License 6 votes vote down vote up
@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));
    }
}
 
Example 6
Project: Shush   File: Geofencing.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 7
Project: proto-collecte   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@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
    }
}
 
Example 8
Project: Remindy   File: GeofenceUtil.java   Source Code and License 6 votes vote down vote up
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();
                }
            });
        }
    }

}
 
Example 9
Project: MyGeofencer   File: GeofencingController.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 10
Project: Dispatch   File: LocationUpdaterService.java   Source Code and License 6 votes vote down vote up
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();
        }
    }
}
 
Example 11
Project: civify-app   File: LocationAdapter.java   Source Code and License 6 votes vote down vote up
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();
        }
    }
}
 
Example 12
Project: CustomAndroidOneSheeld   File: GpsShield.java   Source Code and License 6 votes vote down vote up
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();

}
 
Example 13
Project: Moodr   File: MapsActivity.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 14
Project: Dispatch   File: LocationUpdaterService.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 15
Project: 2017.2-codigo   File: FusedLocationActivity.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 16
Project: bikedeboa-android   File: MapActivity.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 17
Project: 2017.2-codigo   File: FusedLocationMapActivity.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 18
Project: background-location-updates-android-o   File: MainActivity.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
}
 
Example 19
Project: do-road   File: MapFrag.java   Source Code and License 5 votes vote down vote up
@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));
            }

        }
}
 
Example 20
Project: Camera-warner   File: LocationService.java   Source Code and License 5 votes vote down vote up
@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());
}
 
Example 21
Project: GitHub   File: AddGeofenceObservable.java   Source Code and License 5 votes vote down vote up
@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));
                    }
                }
            });
}
 
Example 22
Project: GitHub   File: RemoveGeofenceByPendingIntentObservable.java   Source Code and License 5 votes vote down vote up
@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));
                    }
                }
            });
}
 
Example 23
Project: background-location-updates-android-o   File: MainActivity.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 24
Project: BonAppetit_Android-Project   File: MapsActivity.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
    }

}
 
Example 25
Project: GoMeet   File: LocationMonitoringService.java   Source Code and License 5 votes vote down vote up
@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");
}
 
Example 26
Project: proto-collecte   File: CollecteService.java   Source Code and License 5 votes vote down vote up
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);
        }
    }
 
Example 27
Project: Crimson   File: SearchClinics.java   Source Code and License 5 votes vote down vote up
@Override
public void onPause() {
    super.onPause();

    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}
 
Example 28
Project: GitHub   File: LocationUpdatesObservable.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 29
Project: Remindy   File: PlaceActivity.java   Source Code and License 5 votes vote down vote up
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);
        }
    }
 
Example 30
Project: ITagAntiLost   File: LocationActivity.java   Source Code and License 5 votes vote down vote up
@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);
  }
}
 
Example 31
Project: Android-Client   File: LocationService.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 32
Project: react-native-connectivity-status   File: RNConnectivityStatusModule.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 33
Project: flutter_geolocation   File: GpsCoordinatesPlugin.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 34
Project: Runnest   File: ChallengeActivity.java   Source Code and License 5 votes vote down vote up
private void setupGoogleApi() {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}
 
Example 35
Project: IelloAndroidAdminApp   File: MappaGoogle.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 36
Project: iSPY   File: MapsActivity3.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 37
Project: Expert-Android-Programming   File: SelectDeliveryAreaActivity.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 38
Project: Movie-Notifier-Android   File: LocationUtil.java   Source Code and License 5 votes vote down vote up
public void setupLocationClient(Context context) {
    if(locationClient == null) {
        if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationClient = LocationServices.getFusedLocationProviderClient(context);
        }
    }
}
 
Example 39
Project: PrivacyStreams   File: GoogleLocationUpdatesProvider.java   Source Code and License 5 votes vote down vote up
@Override
protected void provide() {
    mGoogleApiClient = new GoogleApiClient.Builder(getContext())
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    if (!mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }
}
 
Example 40
Project: proto-collecte   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@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);
    }
}