Java Examples for com.google.android.gms.location.LocationRequest

The following java examples will help you to understand the usage of com.google.android.gms.location.LocationRequest. These source code samples are taken from different open source projects.

Example 1
Project: android-rxlocationsettings-master  File: MainActivity.java View source code
private void ensureLocationSettings() {
    LocationSettingsRequest locationSettingsRequest = new LocationSettingsRequest.Builder().addLocationRequest(LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)).build();
    RxLocationSettings.with(this).ensure(locationSettingsRequest).subscribe(new Action1<Boolean>() {

        @Override
        public void call(Boolean enabled) {
            Toast.makeText(MainActivity.this, enabled ? "Enabled" : "Failed", Toast.LENGTH_LONG).show();
        }
    });
}
Example 2
Project: Linked-master  File: UserMenu.java View source code
@Override
public void onConnected(@Nullable Bundle bundle) {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(100000);
    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) {
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
Example 3
Project: Reactive-PlayServices-master  File: ObservableLocationTest.java View source code
@SmallTest
public void test_callSubscribe_startsReceivingLocationUpdates() {
    sut.call(testSubscriber);
    verify(mockLocationProvider, times(1)).requestLocationUpdates(any(GoogleApiClient.class), any(LocationRequest.class), locationListenerCaptor.capture());
    locationListenerCaptor.getValue().onLocationChanged(createLocation(LAT, LNG, ACCURACY));
    assertEquals(1, testSubscriber.getOnNextEvents().size());
}
Example 4
Project: Tahoe-master  File: GoogleLocationServiceActivity.java View source code
@Override
public void onConnected(Bundle bundle) {
    if (locationRequest == null) {
        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(DEFAULT_INTERVAL_MS);
        locationRequest.setFastestInterval(DEFAULT_FASTEST_INTERVAL_MS);
    }
    locationClient.requestLocationUpdates(locationRequest, this);
}
Example 5
Project: android-master  File: MainActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 1. setContnetView
    setContentView(R.layout.activity_main);
    // 2. get reference to TextView
    txtLong = (TextView) findViewById(R.id.txtLong);
    txtLat = (TextView) findViewById(R.id.txtLat);
    // 3. create LocationClient
    mLocationClient = new LocationClient(this, this, this);
    // 4. create & set LocationRequest for Location update
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the update interval to 5 seconds
    mLocationRequest.setInterval(1000 * 5);
    // Set the fastest update interval to 1 second
    mLocationRequest.setFastestInterval(1000 * 1);
}
Example 6
Project: moelaywatha-master  File: BaseActivity.java View source code
@Override
public void onConnected(Bundle bundle) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    Timber.d(mLastLocation == null ? "null" : "not null");
    if (mLastLocation != null) {
        mLatitude = (float) mLastLocation.getLatitude();
        mLongitude = (float) mLastLocation.getLongitude();
        Timber.d(mLatitude + "");
        Timber.d(mLongitude + "");
        mSharedPreferences.edit().putFloat(Config.LAST_LATITUDE, mLatitude).apply();
        mSharedPreferences.edit().putFloat(Config.LAST_LONGITUDE, mLongitude).apply();
    } else {
        LocationRequest mLocationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY).setInterval(// 10 seconds, in milliseconds
        10 * 1000).setFastestInterval(1 * 1000);
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}
Example 7
Project: AndroidLocationHub-master  File: GMSLocationHubAdapter.java View source code
/**
     * Builds a {@link com.google.android.gms.location.LocationRequest} from the custom implementation
     * of {@link net.frakbot.android.location.common.LocationHubRequest}.
     *
     * This method basically maps the handled property to the GMS ones.
     *
     * @param request The original {@link net.frakbot.android.location.common.LocationHubRequest} to convert.
     * @return A converted and ready to use {@link com.google.android.gms.location.LocationRequest}.
     */
private LocationRequest requestFromHub(LocationHubRequest request) {
    LocationRequest locationRequest = LocationRequest.create();
    // Power
    if (request.getPriority() == LocationHubRequest.PRIORITY_NO_POWER) {
        locationRequest.setPriority(LocationRequest.PRIORITY_NO_POWER);
    } else if (request.getPriority() == LocationHubRequest.PRIORITY_LOW_POWER) {
        locationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
    } else if (request.getPriority() == LocationHubRequest.PRIORITY_BALANCED_POWER_ACCURACY) {
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    } else if (request.getPriority() == LocationHubRequest.PRIORITY_HIGH_ACCURACY) {
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }
    // Interval
    locationRequest.setInterval(request.getInterval());
    // Fastest interval
    locationRequest.setFastestInterval(request.getFastestInterval());
    // Smallest displacement
    locationRequest.setSmallestDisplacement(request.getSmallestDisplacement());
    return locationRequest;
}
Example 8
Project: androidmooc-clase4-master  File: MainActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnDelete = (Button) findViewById(R.id.btnDelete);
    btnDelete.setOnClickListener(this);
    locationClient = new LocationClient(this, this, this);
    locationRequest = LocationRequest.create();
    locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);
}
Example 9
Project: AndroidOpenTextbook-master  File: MainActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mLocation[0] = (TextView) findViewById(R.id.lat_text);
    mLocation[1] = (TextView) findViewById(R.id.lon_text);
    mLocation[2] = (TextView) findViewById(R.id.altitude_text);
    mLocation[3] = (TextView) findViewById(R.id.speed_text);
    mLocation[4] = (TextView) findViewById(R.id.time_text);
    mLocation[5] = (TextView) findViewById(R.id.accuracy_text);
    mLocation[6] = (TextView) findViewById(R.id.bearing_text);
    // Google Play Service �有効�����ェックを行�
    if (!checkPlayServices()) {
        return;
    }
    // Create the Google API Client
    mApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addApi(LocationServices.API).addOnConnectionFailedListener(this).build();
    mLocationRequest = new LocationRequest();
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setInterval(5000);
    mLocationRequest.setSmallestDisplacement(1);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
Example 10
Project: copcast-android-master  File: LocationService.java View source code
@Override
public void onCreate() {
    super.onCreate();
    final Intent resultIntent = new Intent(this, MainActivity.class);
    final Context context = getApplicationContext();
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setContentTitle(getString(R.string.notification_location_title)).setContentText(getString(R.string.notification_location_description)).setSmallIcon(R.drawable.ic_launcher);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_NO_CREATE);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify(mId, mBuilder.build());
    // Create a new global location parameters object
    mLocationRequest = LocationRequest.create();
    /*
         * Set the update interval
         */
    mLocationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the interval ceiling to one minute
    mLocationRequest.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
    /*
         * Create a new location client, using the enclosing class to
         * handle callbacks.
         */
    mLocationClient = new LocationClient(this, this, this);
    mLocationClient.connect();
}
Example 11
Project: google-play-services-master  File: MainActivity.java View source code
@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Update location every second
    mLocationRequest.setInterval(10);
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
Example 12
Project: iBurn-Android-master  File: GoogleMapFragment.java View source code
private void setupReverseGeocoder() {
    // Setting up JSEvaluator seems to be flaky if done immediately after app start :/
    locationSubscription = Observable.timer(2, TimeUnit.SECONDS).first().observeOn(AndroidSchedulers.mainThread()).flatMap( time -> JSEvaluator.getInstance("file:///android_asset/js/geocoder.html", getActivity().getApplicationContext())).doOnNext( evaluator -> Timber.d("Got evaluator")).flatMap( jsEvaluator -> LocationProvider.observeCurrentLocation(getActivity().getApplicationContext(), LocationRequest.create().setPriority(LocationRequest.PRIORITY_NO_POWER).setInterval(5 * 1000).setSmallestDisplacement(10)).doOnNext( location -> {
        if (prefs != null && Embargo.isEmbargoActive(prefs)) {
            float[] distance = new float[1];
            Location.distanceBetween(location.getLatitude(), location.getLongitude(), Geo.MAN_LAT, Geo.MAN_LON, distance);
            if (distance[0] < 5000) {
                Timber.d("Unlocking location data by geo trigger!");
                prefs.setEnteredValidUnlockCode(true);
                DataProvider.getInstance(getActivity().getApplicationContext()).subscribe(DataProvider::endUpgrade);
                if (getActivity() instanceof MainActivity) {
                    ((MainActivity) getActivity()).clearEmbargoSnackbar();
                }
            }
        }
    }).map( location -> new Pair<>(jsEvaluator, location))).observeOn(AndroidSchedulers.mainThread()).subscribe( evaluatorLocationPair -> {
        evaluatorLocationPair.first.reverseGeocode(evaluatorLocationPair.second.getLatitude(), evaluatorLocationPair.second.getLongitude(),  playaAddress -> {
            addressLabel.post(() -> {
                addressLabel.setVisibility(View.VISIBLE);
                addressLabel.setText(playaAddress);
            });
        });
    });
}
Example 13
Project: location-tracker-background-master  File: LocationService.java View source code
protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(this.interval);
    mLocationRequest.setFastestInterval(this.interval / 2);
    if (this.gps) {
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    } else if (this.netWork) {
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    }
}
Example 14
Project: mqttitude-master  File: FusedLocationLocator.java View source code
private void setupBackgroundLocationRequest() {
    Log.v(TAG, "setupBackgroundLocationRequest. Interval: " + getUpdateIntervall());
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    mLocationRequest.setInterval(getUpdateIntervallInMiliseconds());
    mLocationRequest.setFastestInterval(500);
    mLocationRequest.setSmallestDisplacement(500);
}
Example 15
Project: mtransit-for-android-master  File: MTActivityWithLocation.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (this.useLocation) {
        this.locationRequest = LocationRequest.create();
        // foreground app == high accuracy
        this.locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        this.locationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MS);
        this.locationRequest.setFastestInterval(LocationUtils.FASTEST_INTERVAL_IN_MS);
    }
}
Example 16
Project: playground-master  File: MainActivity.java View source code
protected void createLocationRequest() {
    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(500);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    Location lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher);
    mMarkerAtual = mMap.addMarker(new MarkerOptions().title("Local atual").icon(icon).position(new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude())));
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
Example 17
Project: project-ceeq-master  File: TrackerService.java View source code
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(INTERVAL);
    locationRequest.setFastestInterval(FASTEST_INTERVAL);
    locationClient = new LocationClient(this, this, this);
    requestType = (RequestType) intent.getExtras().get(ACTION);
    // senderAddress = intent.getExtras().getString(SENDER_ADDRESS);
    Utils.d("Type : " + requestType + " has sender address : " + senderAddress);
    locationClient.connect();
    return START_REDELIVER_INTENT;
}
Example 18
Project: RxLocation-master  File: MainPresenterTest.java View source code
@Test
public void settingsSatisfied_1Location() {
    Location loc = Mockito.mock(Location.class);
    Address address = Mockito.mock(Address.class);
    doReturn(Single.just(true)).when(locationSettings).checkAndHandleResolution(Matchers.any(LocationRequest.class));
    doReturn(Observable.just(loc)).when(fusedLocation).updates(Matchers.any(LocationRequest.class));
    doReturn(Maybe.just(address)).when(geocoding).fromLocation(Matchers.any(android.location.Location.class));
    mainPresenter.attachView(mainView);
    verify(mainView).onLocationUpdate(loc);
    verify(mainView).onAddressUpdate(address);
    verifyNoMoreInteractions(mainView);
}
Example 19
Project: SensingKit-Android-master  File: SKLocation.java View source code
private void registerForLocationUpdates() {
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Update location every second
    locationRequest.setInterval(1000);
    LocationServices.FusedLocationApi.requestLocationUpdates(mClient, locationRequest, this);
}
Example 20
Project: Tower-master  File: BaseFlightControlFragment.java View source code
private void enableFollowMe(final Drone drone) {
    if (drone == null)
        return;
    final LocationRequest locationReq = LocationRequest.create().setPriority(FOLLOW_LOCATION_PRIORITY).setFastestInterval(FOLLOW_LOCATION_UPDATE_FASTEST_INTERVAL).setInterval(FOLLOW_LOCATION_UPDATE_INTERVAL).setSmallestDisplacement(FOLLOW_LOCATION_UPDATE_MIN_DISPLACEMENT);
    final CheckLocationSettings locationSettingsChecker = new CheckLocationSettings(getActivity(), locationReq, new Runnable() {

        @Override
        public void run() {
            FollowApi.getApi(drone).enableFollowMe(getAppPrefs().getLastKnownFollowType());
        }
    });
    locationSettingsChecker.check();
}
Example 21
Project: Android-ReactiveLocation-master  File: MainActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lastKnownLocationView = (TextView) findViewById(R.id.last_known_location_view);
    updatableLocationView = (TextView) findViewById(R.id.updated_location_view);
    addressLocationView = (TextView) findViewById(R.id.address_for_location_view);
    currentActivityView = (TextView) findViewById(R.id.activity_recent_view);
    locationProvider = new ReactiveLocationProvider(getApplicationContext());
    lastKnownLocationObservable = locationProvider.getLastKnownLocation();
    final LocationRequest locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setNumUpdates(5).setInterval(100);
    locationUpdatesObservable = locationProvider.checkLocationSettings(new LocationSettingsRequest.Builder().addLocationRequest(locationRequest).setAlwaysShow(//Refrence: http://stackoverflow.com/questions/29824408/google-play-services-locationservices-api-new-option-never
    true).build()).doOnNext(new Action1<LocationSettingsResult>() {

        @Override
        public void call(LocationSettingsResult locationSettingsResult) {
            Status status = locationSettingsResult.getStatus();
            if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
                try {
                    status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                } catch (IntentSender.SendIntentException th) {
                    Log.e("MainActivity", "Error opening settings activity.", th);
                }
            }
        }
    }).flatMap(new Func1<LocationSettingsResult, Observable<Location>>() {

        @Override
        public Observable<Location> call(LocationSettingsResult locationSettingsResult) {
            return locationProvider.getUpdatedLocation(locationRequest);
        }
    });
    addressObservable = locationProvider.getUpdatedLocation(locationRequest).flatMap(new Func1<Location, Observable<List<Address>>>() {

        @Override
        public Observable<List<Address>> call(Location location) {
            return locationProvider.getReverseGeocodeObservable(location.getLatitude(), location.getLongitude(), 1);
        }
    }).map(new Func1<List<Address>, Address>() {

        @Override
        public Address call(List<Address> addresses) {
            return addresses != null && !addresses.isEmpty() ? addresses.get(0) : null;
        }
    }).map(new AddressToStringFunc()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    activityObservable = locationProvider.getDetectedActivity(50);
}
Example 22
Project: android_external_GmsLib-master  File: NativeLocationClientImpl.java View source code
private static Criteria makeNativeCriteria(LocationRequest request) {
    Criteria criteria = new Criteria();
    switch(request.getPriority()) {
        case LocationRequest.PRIORITY_HIGH_ACCURACY:
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setPowerRequirement(Criteria.POWER_HIGH);
            break;
        case LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY:
        default:
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
            break;
        case LocationRequest.PRIORITY_NO_POWER:
        case LocationRequest.PRIORITY_LOW_POWER:
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            criteria.setPowerRequirement(Criteria.POWER_LOW);
    }
    return criteria;
}
Example 23
Project: android_OpenLocationCodes-master  File: MainActivity.java View source code
@Override
public void onMapReady(final GoogleMap googleMap) {
    mGoogleMap = googleMap;
    mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    mGoogleMap.getUiSettings().setZoomGesturesEnabled(false);
    mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
    mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

        @Override
        public void onMapClick(final LatLng latLng) {
            openLocationCode(latLng.latitude, latLng.longitude, mCodeLength, false);
        }
    });
    mGoogleMap.setMyLocationEnabled(true);
    mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
    final Locator locator = new Locator(MainActivity.this);
    locator.start(LocationRequest.create().setNumUpdates(1).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY), new LocationListener() {

        @Override
        public void onLocationChanged(final Location location) {
            update(location, true);
        }
    });
    mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {

        @Override
        public boolean onMyLocationButtonClick() {
            final Location location = locator.location();
            if (location == null) {
                return false;
            }
            update(location, false);
            return true;
        }
    });
    mGoogleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {

        @Override
        public void onCameraIdle() {
            final Location location = locator.location();
            if (location == null) {
                return;
            }
            update(location, false);
        }
    });
}
Example 24
Project: android_packages_apps_GmsCore-master  File: WearableLocationService.java View source code
private static LocationRequestInternal readLocationRequest(DataMap dataMap, Context context) {
    LocationRequestInternal request = new LocationRequestInternal();
    request.triggerUpdate = true;
    request.request = new LocationRequest();
    request.clients = Collections.emptyList();
    if (dataMap.containsKey("PRIORITY"))
        request.request.setPriority(dataMap.getInt("PRIORITY", 0));
    if (dataMap.containsKey("INTERVAL_MS"))
        request.request.setInterval(dataMap.getLong("INTERVAL_MS", 0));
    if (dataMap.containsKey("FASTEST_INTERVAL_MS"))
        request.request.setFastestInterval(dataMap.getLong("FASTEST_INTERVAL_MS", 0));
    //if (dataMap.containsKey("MAX_WAIT_TIME_MS"))
    if (dataMap.containsKey("SMALLEST_DISPLACEMENT_METERS"))
        request.request.setSmallestDisplacement(dataMap.getFloat("SMALLEST_DISPLACEMENT_METERS", 0));
    if (dataMap.containsKey("NUM_UPDATES"))
        request.request.setNumUpdates(dataMap.getInt("NUM_UPDATES", 0));
    if (dataMap.containsKey("EXPIRATION_DURATION_MS"))
        request.request.setExpirationDuration(dataMap.getLong("EXPIRATION_DURATION_MS", 0));
    if (dataMap.containsKey("TAG"))
        request.tag = dataMap.getString("TAG");
    if (dataMap.containsKey("CLIENTS_PACKAGE_ARRAY")) {
        String[] packages = dataMap.getStringArray("CLIENTS_PACKAGE_ARRAY");
        if (packages != null) {
            request.clients = new ArrayList<ClientIdentity>();
            for (String packageName : packages) {
                request.clients.add(generateClientIdentity(packageName, context));
            }
        }
    }
    return request;
}
Example 25
Project: ASA-master  File: AdvancedLocationSettingsController.java View source code
@Override
public void onConnected(Bundle arg0) {
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Setting the update interval to  5mins
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    // Set the fastest update interval to 1 min
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
    LocationListener locationListener = new ASALocationListener();
    activity.getLocationClient().requestLocationUpdates(mLocationRequest, locationListener);
}
Example 26
Project: dronekit-android-master  File: MavLinkDroneManager.java View source code
public void onVehicleTypeReceived(FirmwareType type) {
    if (drone != null) {
        return;
    }
    final String droneId = connectionParameter.getUniqueId() + ":" + type.getType();
    switch(type) {
        case ARDU_COPTER:
            if (isCompanionComputerEnabled()) {
                onVehicleTypeReceived(FirmwareType.ARDU_SOLO);
                return;
            }
            Timber.i("Instantiating ArduCopter autopilot.");
            this.drone = new ArduCopter(droneId, context, mavClient, handler, new AndroidApWarningParser(), this);
            break;
        case ARDU_SOLO:
            Timber.i("Instantiating ArduSolo autopilot.");
            this.drone = new ArduSolo(droneId, context, mavClient, handler, new AndroidApWarningParser(), this);
            break;
        case ARDU_PLANE:
            Timber.i("Instantiating ArduPlane autopilot.");
            this.drone = new ArduPlane(droneId, context, mavClient, handler, new AndroidApWarningParser(), this);
            break;
        case ARDU_ROVER:
            Timber.i("Instantiating ArduPlane autopilot.");
            this.drone = new ArduRover(droneId, context, mavClient, handler, new AndroidApWarningParser(), this);
            break;
        case PX4_NATIVE:
            Timber.i("Instantiating PX4 Native autopilot.");
            this.drone = new Px4Native(droneId, context, handler, mavClient, new AndroidApWarningParser(), this);
            break;
        case GENERIC:
            Timber.i("Instantiating Generic mavlink autopilot.");
            this.drone = new GenericMavLinkDrone(droneId, context, handler, mavClient, new AndroidApWarningParser(), this);
            break;
    }
    this.followMe = new Follow(this, handler, new FusedLocation(context, handler));
    this.returnToMe = new ReturnToMe(this, new FusedLocation(context, handler, LocationRequest.PRIORITY_HIGH_ACCURACY, 1000L, 1000L, ReturnToMe.UPDATE_MINIMAL_DISPLACEMENT), this);
    StreamRates streamRates = drone.getStreamRates();
    if (streamRates != null) {
        streamRates.setRates(new StreamRates.Rates(droneStreamRate.get()));
    }
    drone.addDroneListener(this);
    drone.setAttributeListener(this);
    ParameterManager parameterManager = drone.getParameterManager();
    if (parameterManager != null) {
        parameterManager.setParameterListener(this);
    }
    MagnetometerCalibrationImpl magnetometer = drone.getMagnetometerCalibration();
    if (magnetometer != null) {
        magnetometer.setListener(this);
    }
}
Example 27
Project: home-assistant-Android-master  File: LocationUpdateReceiver.java View source code
@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(apiClient.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        if (prefs.getBoolean(Common.PREF_ENABLE_LOCATION_TRACKING, false) && !TextUtils.isEmpty(prefs.getString(Common.PREF_LOCATION_DEVICE_NAME, null))) {
            LocationRequest locationRequest = new LocationRequest();
            locationRequest.setInterval(prefs.getInt(Common.PREF_LOCATION_UPDATE_INTERVAL, 10) * 60 * 1000);
            locationRequest.setFastestInterval(5 * 60 * 1000);
            locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, getPendingIntent(apiClient.getContext()));
            Log.d(TAG, "Started requesting location updates");
        } else {
            LocationServices.FusedLocationApi.removeLocationUpdates(apiClient, getPendingIntent(apiClient.getContext()));
            Log.d(TAG, "Stopped requesting location updates");
        }
    }
    apiClient.disconnect();
}
Example 28
Project: MyTracks-master  File: MyTracksLocationManager.java View source code
@Override
public void run() {
    if (requestLastLocation != null && locationClient.isConnected()) {
        requestLastLocation.onLocationChanged(locationClient.getLastLocation());
        requestLastLocation = null;
    }
    if (requestLocationUpdates != null && locationClient.isConnected()) {
        LocationRequest locationRequest = new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(requestLocationUpdatesTime).setFastestInterval(requestLocationUpdatesTime).setSmallestDisplacement(requestLocationUpdatesDistance);
        locationClient.requestLocationUpdates(locationRequest, requestLocationUpdates, handler.getLooper());
    }
}
Example 29
Project: network-monitor-master  File: GmsDeviceLocationDataSource.java View source code
/**
     * Depending on the location fetching strategy, and the application's test interval register a listener to
     * receive location updates.
     */
@SuppressWarnings("MissingPermission")
private void registerLocationListener() {
    LocationFetchingStrategy locationFetchingStrategy = NetMonPreferences.getInstance(mContext).getLocationFetchingStrategy();
    Log.v(TAG, "registerLocationListener: strategy = " + locationFetchingStrategy);
    if (!mLocationClient.isConnected()) {
        Log.v(TAG, "LocationClient not connected, doing nothing");
        return;
    }
    if (!PermissionUtil.hasLocationPermission(mContext)) {
        Log.v(TAG, "LocationClient not connected, doing nothing");
        return;
    }
    LocationServices.FusedLocationApi.removeLocationUpdates(mLocationClient, mGmsLocationListener);
    LocationRequest request = new LocationRequest();
    if (locationFetchingStrategy == LocationFetchingStrategy.HIGH_ACCURACY_GMS) {
        request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        int pollingInterval = NetMonPreferences.getInstance(mContext).getUpdateInterval();
        if (pollingInterval < NetMonPreferences.PREF_MIN_POLLING_INTERVAL)
            pollingInterval = NetMonPreferences.PREF_MIN_POLLING_INTERVAL;
        request.setFastestInterval(pollingInterval);
    } else {
        request.setPriority(LocationRequest.PRIORITY_LOW_POWER);
        request.setNumUpdates(1);
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, request, mGmsLocationListener);
}
Example 30
Project: prey-android-client-master  File: UtilityService.java View source code
/**
     * Called when a location update is requested
     */
private void requestLocationInternal() {
    PreyLogger.d(ACTION_REQUEST_LOCATION);
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).build();
    // It's OK to use blockingConnect() here as we are running in an
    // IntentService that executes work on a separate (background) thread.
    ConnectionResult connectionResult = googleApiClient.blockingConnect(GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);
    if (connectionResult.isSuccess() && googleApiClient.isConnected()) {
        Intent locationUpdatedIntent = new Intent(this, UtilityService.class);
        locationUpdatedIntent.setAction(ACTION_LOCATION_UPDATED);
        // Send last known location out first if available
        Location location = FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            Intent lastLocationIntent = new Intent(locationUpdatedIntent);
            lastLocationIntent.putExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED, location);
            startService(lastLocationIntent);
        }
        // Request new location
        LocationRequest mLocationRequest = new LocationRequest().setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, PendingIntent.getService(this, 0, locationUpdatedIntent, 0));
        googleApiClient.disconnect();
    } else {
        PreyLogger.i(String.format(GOOGLE_API_CLIENT_ERROR_MSG, connectionResult.getErrorCode()));
    }
}
Example 31
Project: Shorcial-master  File: LocationActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mLocationClient = new LocationClient(this, this, this);
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    mLocationRequest.setInterval(30000);
    mLocationRequest.setFastestInterval(1000);
    if (savedInstanceState != null) {
        if (Utilities.imageLoader == null) {
            Utilities.setImageLoader(getApplicationContext());
        }
        if ((savedInstanceState.getSerializable("playa") != null) && (ValidacionPlaya.playa == null)) {
            ValidacionPlaya.playa = (Playa) savedInstanceState.getSerializable("playa");
        }
        if ((savedInstanceState.getSerializable("cargadaImagenes") != null)) {
            ValidacionPlaya.cargadaImagenes = (Boolean) savedInstanceState.getSerializable("cargadaImagenes");
        }
        if ((savedInstanceState.getSerializable("cargadaPlayas") != null)) {
            ValidacionPlaya.cargadaPlayas = (Boolean) savedInstanceState.getSerializable("cargadaPlayas");
        }
        if ((savedInstanceState.getSerializable("cargadaTemperatura") != null)) {
            ValidacionPlaya.cargadaTemperatura = (Boolean) savedInstanceState.getSerializable("cargadaTemperatura");
        }
        if ((savedInstanceState.getSerializable("cargadosComentarios") != null)) {
            ValidacionPlaya.cargadosComentarios = (Boolean) savedInstanceState.getSerializable("cargadosComentarios");
        }
        if ((savedInstanceState.getSerializable("cargadosMensajesPlaya") != null)) {
            ValidacionPlaya.cargadosMensajesPlaya = (Boolean) savedInstanceState.getSerializable("cargadosMensajesPlaya");
        }
        if ((savedInstanceState.getSerializable("cargadosUltimosCheckins") != null)) {
            ValidacionPlaya.cargadosUltimosCheckins = (Boolean) savedInstanceState.getSerializable("cargadosUltimosCheckins");
        }
        if ((savedInstanceState.getSerializable("comentariosPlaya") != null)) {
            ValidacionPlaya.comentariosPlaya = (ArrayList) savedInstanceState.getSerializable("comentariosPlaya");
        }
        if ((savedInstanceState.getSerializable("iconWeather") != null)) {
            ValidacionPlaya.iconWeather = (String) savedInstanceState.getSerializable("iconWeather");
        }
        if ((savedInstanceState.getSerializable("imagenes") != null)) {
            ValidacionPlaya.imagenes = (ArrayList) savedInstanceState.getSerializable("imagenes");
        }
        if ((savedInstanceState.getSerializable("lanzadaVerPlaya") != null)) {
            ValidacionPlaya.lanzadaVerPlaya = (Boolean) savedInstanceState.getSerializable("lanzadaVerPlaya");
        }
        if ((savedInstanceState.getSerializable("mensajesBotella") != null)) {
            ValidacionPlaya.mensajesBotella = (ArrayList) savedInstanceState.getSerializable("mensajesBotella");
        }
        if ((savedInstanceState.getSerializable("playas") != null)) {
            ValidacionPlaya.playas = (ArrayList) savedInstanceState.getSerializable("playas");
        }
        if ((savedInstanceState.getSerializable("playasCheckins") != null)) {
            ValidacionPlaya.playasCheckins = (ArrayList) savedInstanceState.getSerializable("playasCheckins");
        }
        if ((savedInstanceState.getSerializable("temperatura") != null)) {
            ValidacionPlaya.temperatura = (Double) savedInstanceState.getSerializable("temperatura");
        }
    }
}
Example 32
Project: sthlmtraveling-master  File: LocationManager.java View source code
public LocationRequest createLocationRequest() {
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(mHighAccuracy ? LocationRequest.PRIORITY_HIGH_ACCURACY : LocationRequest.PRIORITY_LOW_POWER);
    locationRequest.setInterval(UPDATE_INTERVAL);
    locationRequest.setFastestInterval(FASTEST_INTERVAL);
    locationRequest.setExpirationDuration(ACCEPTED_LOCATION_AGE_MILLIS);
    locationRequest.setNumUpdates(5);
    return locationRequest;
}
Example 33
Project: TruckMuncher-Android-master  File: CustomerMapFragment.java View source code
@Override
public void onConnected(Bundle bundle) {
    Location myLocation = LocationServices.FusedLocationApi.getLastLocation(apiClient);
    if (myLocation != null) {
        LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
        MapsInitializer.initialize(getActivity());
        mapView.getMap().animateCamera(CameraUpdateFactory.newLatLng(latLng));
    }
    LocationRequest request = new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setFastestInterval(FASTEST_REFRESH_INTERVAL).setInterval(REFRESH_INTERVAL);
    LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, request, this);
    Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(apiClient);
    if (lastLocation != null) {
        onLocationChanged(lastLocation);
    }
}
Example 34
Project: WeatherDoge-master  File: LocationApi.java View source code
@Override
public void onConnected(Bundle bundle) {
    LocationRequest request = LocationRequest.create();
    request.setPriority(LocationRequest.PRIORITY_LOW_POWER);
    request.setInterval(5000);
    request.setFastestInterval(1000);
    try {
        LocationServices.FusedLocationApi.requestLocationUpdates(client, request, this);
    } catch (SecurityException ex) {
        Log.wtf(TAG, ex);
        return;
    }
    receiver.onConnected();
}
Example 35
Project: WiFi-Automatic-master  File: GeofenceUpdateService.java View source code
@Override
public void onConnected(final Bundle bundle) {
    // should not happen?
    if (mLocationClient == null)
        return;
    if (BuildConfig.DEBUG)
        Logger.log("removing all fences");
    PendingIntent pi = PendingIntent.getService(this, 0, new Intent(this, GeoFenceService.class), PendingIntent.FLAG_UPDATE_CURRENT);
    LocationServices.GeofencingApi.removeGeofences(mLocationClient, pi);
    LocationServices.FusedLocationApi.removeLocationUpdates(mLocationClient, pi);
    Database database = Database.getInstance(this);
    List<Location> locations = database.getLocations();
    database.close();
    SharedPreferences prefs = getSharedPreferences("locationPrefs", MODE_PRIVATE);
    if (BuildConfig.DEBUG)
        Logger.log("re-adding all " + locations.size() + " fences");
    if (!locations.isEmpty()) {
        GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
        builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
        for (Location l : locations) {
            try {
                builder.addGeofence(new Geofence.Builder().setCircularRegion(l.coords.latitude, l.coords.longitude, LOCATION_RANGE_METER).setRequestId(l.coords.latitude + "@" + l.coords.longitude).setExpirationDuration(Geofence.NEVER_EXPIRE).setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER).build());
            } catch (Exception e) {
                if (BuildConfig.DEBUG)
                    Logger.log(e);
            }
        }
        try {
            if (PermissionChecker.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PermissionChecker.PERMISSION_GRANTED && PermissionChecker.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PermissionChecker.PERMISSION_GRANTED) {
                LocationServices.GeofencingApi.addGeofences(mLocationClient, builder.build(), pi);
                if (prefs.getBoolean("active", false)) {
                    LocationRequest mLocationRequest = new LocationRequest();
                    mLocationRequest.setInterval(prefs.getInt("interval", 15) * 60000);
                    mLocationRequest.setFastestInterval(5000);
                    mLocationRequest.setSmallestDisplacement(50f);
                    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
                    LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, pi);
                }
            } else {
                if (BuildConfig.DEBUG)
                    Logger.log("no location permission");
            }
        } catch (Exception iae) {
            if (BuildConfig.DEBUG)
                Logger.log(iae);
        }
    }
    disconnect();
}
Example 36
Project: wsdot-android-app-master  File: VesselWatchMapActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.map);
    enableAds();
    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
    // Initialize AsyncTasks
    camerasOverlayTask = new CamerasOverlayTask();
    vesselsOverlayTask = new VesselsOverlayTask();
    // Check preferences
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    showCameras = settings.getBoolean("KEY_SHOW_CAMERAS", true);
    // Setup Service Intent.
    camerasIntent = new Intent(this, CamerasSyncService.class);
    mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    mLocationRequest = LocationRequest.create().setInterval(10000).setFastestInterval(5000).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapview);
    mapFragment.getMapAsync(this);
}
Example 37
Project: 1Sheeld-Android-App-master  File: GpsShield.java View source code
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 38
Project: android-playlistr-master  File: UpdateLocationService.java View source code
@Override
public void onCreate() {
    super.onCreate();
    registerReceiver(networdReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
    registerReceiver(synSongBroadcastReceiver, new IntentFilter("com.ved.musicmapapp.service.syncsong"));
    mTimer = new Timer();
    mTimerCheckLocation = new Timer();
    syncingTimer = new Timer();
    mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                if (SettingsManager.getInstance(getApplicationContext()).isAutoUpdateLocation()) {
                    if (!mLocationClient.isConnected()) {
                        startLocationUpdate();
                    }
                }
            }
            super.handleMessage(msg);
        }
    };
    mLocationClient = new LocationClient(this, this, this);
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the update interval to 5 seconds
    mLocationRequest.setInterval(UPDATE_DURATION);
    // Set the fastest update interval to 1 second
    mLocationRequest.setFastestInterval(UPDATE_DURATION / 5);
    prefs = getSharedPreferences("MUSIC_MAP", Context.MODE_PRIVATE);
    mSharedPreferences = getSharedPreferences("settings", Context.MODE_PRIVATE);
    edt = prefs.edit();
// isGetData = true;
}
Example 39
Project: appDomi-master  File: Principal.java View source code
@Override
public void onConnected(Bundle bundle) {
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    //update location every second
    locationRequest.setInterval(1000);
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
Example 40
Project: bearing-master  File: GMSLocationProvider.java View source code
/**
	 * Internal request for recurring updates
	 */
private void internalRequestRecurringUpdates(final String requestId, final LocationProviderRequest request, final LocationListener listener) {
    final LocationRequest gmsRequest = getRecurringLocationRequestForBearingRequest(request);
    runningRequests.put(requestId, new com.google.android.gms.location.LocationListener() {

        private long lastReportedTimestamp = -1;

        private Location lastReportedLocation;

        @Override
        public void onLocationChanged(Location location) {
            long currentTimestamp = System.currentTimeMillis() / 1000;
            long timeSinceLastReport = currentTimestamp - lastReportedTimestamp;
            if (LOG) {
                Log.d("Bearing Location Tracker", "onLocationChanged last reported: " + timeSinceLastReport + " seconds ago (Fallback at " + request.trackingFallback / 1000 + ")");
            }
            if (lastReportedTimestamp == -1 || timeSinceLastReport > (request.trackingFallback / 1000)) {
                if (LOG) {
                    Log.d("Bearing Location Tracker", "Tracking fallback, forcing update");
                }
                lastReportedLocation = location;
                lastReportedTimestamp = currentTimestamp;
                // Force report
                if (listener != null) {
                    listener.onUpdate(location);
                }
                return;
            }
            if (request.trackingDisplacement != -1 && location.distanceTo(lastReportedLocation) > request.trackingDisplacement) {
                lastReportedLocation = location;
                lastReportedTimestamp = currentTimestamp;
                if (listener != null) {
                    listener.onUpdate(location);
                }
            }
        }
    });
    if (apiClient.isConnected()) {
        LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, gmsRequest, runningRequests.get(requestId));
    } else {
        final String connectRequestId = UUID.randomUUID().toString();
        pendingRequests.put(connectRequestId, new Runnable() {

            @Override
            public void run() {
                LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, gmsRequest, runningRequests.get(requestId));
            }
        });
    }
}
Example 41
Project: blindr-master  File: ChooseRoomActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.choose_map);
    handler = new Handler(getMainLooper());
    Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Raleway_Thin.otf");
    ((TextView) findViewById(R.id.textViewTop)).setTypeface(tf);
    findViewById(R.id.lastUsedAddress).setOnClickListener(this);
    trendingList = (ListView) findViewById(R.id.trending_list);
    trendingList.setOnItemClickListener(this);
    ((ImageView) findViewById(R.id.avatar)).setImageBitmap(Controller.getInstance().getMyself().getAvatar());
    ((TextView) findViewById(R.id.fake_name)).setText(Controller.getInstance().getMyself().getName());
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(2000);
    mLocationRequest.setNumUpdates(1);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    new Handler(getMainLooper()).postDelayed(new Runnable() {

        @Override
        public void run() {
            buildGoogleApiClient();
            mGoogleApiClient.connect();
        }
    }, 300);
    // Get a handle to the Map Fragment
    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMyLocationEnabled(true);
    map.setOnMapLongClickListener(this);
}
Example 42
Project: cgeo-wear-master  File: LocationUtils.java View source code
public void startLocationTracking(GoogleApiClient apiClient) {
    //Specify how quickly we want to receive location updates
    LocationRequest locationRequest = LocationRequest.create().setInterval(LOCATION_UPDATE_INTERVAL).setFastestInterval(LOCATION_UPDATE_MAX_INTERVAL).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, locationListener);
}
Example 43
Project: coursera-android-master  File: LocationGetLocationActivity.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (!servicesAvailable())
        finish();
    setContentView(R.layout.main);
    mAccuracyView = (TextView) findViewById(R.id.accuracy_view);
    mTimeView = (TextView) findViewById(R.id.time_view);
    mLatView = (TextView) findViewById(R.id.lat_view);
    mLngView = (TextView) findViewById(R.id.lng_view);
    // Create new Location Client. This class will handle callbacks
    mLocationClient = new LocationClient(this, this, this);
    // Create and define the LocationRequest
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Update every 10 seconds
    mLocationRequest.setInterval(POLLING_FREQ);
    // Recieve updates no more often than every 2 seconds
    mLocationRequest.setFastestInterval(FASTES_UPDATE_FREQ);
}
Example 44
Project: DeviceControl-master  File: GpsView.java View source code
@Override
protected void init(@Nullable AttributeSet attrs) {
    super.init(attrs);
    final Context context = getContext();
    unknownLocation = context.getString(R.string.gps_unknown_location);
    statusView = new TextView(context);
    final FrameLayout content = getContentView();
    content.addView(statusView);
    statusView.setText(R.string.gps_requesting_location);
    final ReactiveLocationProvider provider = new ReactiveLocationProvider(context);
    final LocationRequest locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setFastestInterval(1000).setInterval(10000);
    // get last known location, to display something quite fast
    subscribe(provider, provider.getLastKnownLocation());
    // then subscribe to get location updates
    addressObservable = subscribe(provider, provider.getUpdatedLocation(locationRequest));
}
Example 45
Project: esnavi-master  File: ShelterDetailActivity.java View source code
@Override
public void onConnected(Bundle bundle) {
    super.onConnected(bundle);
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000);
    LocationServices.FusedLocationApi.requestLocationUpdates(getGoogleApiClient(), mLocationRequest, this);
}
Example 46
Project: geohashdroid-master  File: CentralMapExtraActivity.java View source code
private void startListening() {
    // the permissions checks.
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        mFrag.permissionsDenied(false);
        LocationRequest lRequest = LocationRequest.create();
        lRequest.setInterval(1000);
        lRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleClient, lRequest, this);
    } else {
        mFrag.permissionsDenied(true);
    }
}
Example 47
Project: Just-Weather-master  File: WeatherActivity.java View source code
private void getLocation() {
    compositeDisposable.add(rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION).flatMap( granted -> {
        LocationRequest locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (granted) {
            return rxLocation.location().updates(locationRequest).firstElement().toObservable();
        } else {
            return Observable.empty();
        }
    }).doFinally(() -> swipeRefreshEmptyLayout.setRefreshing(false)).subscribe( location -> {
        Timber.d("location - %s", location);
        presenter.addCityByCoordinates(location.getLatitude(), location.getLongitude());
    }, Timber::e));
}
Example 48
Project: kuliah_mobile-master  File: LocationGetLocationActivity.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (!servicesAvailable())
        finish();
    setContentView(R.layout.main);
    mAccuracyView = (TextView) findViewById(R.id.accuracy_view);
    mTimeView = (TextView) findViewById(R.id.time_view);
    mLatView = (TextView) findViewById(R.id.lat_view);
    mLngView = (TextView) findViewById(R.id.lng_view);
    // Create new Location Client. This class will handle callbacks
    mLocationClient = new LocationClient(this, this, this);
    // Create and define the LocationRequest
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Update every 10 seconds
    mLocationRequest.setInterval(POLLING_FREQ);
    // Recieve updates no more often than every 2 seconds
    mLocationRequest.setFastestInterval(FASTES_UPDATE_FREQ);
}
Example 49
Project: maps-android-codelabs-master  File: LocationActivity.java View source code
private void restartLocationClient() {
    if (!(mLocationClient.isConnected() || mLocationClient.isConnecting())) {
        // Somehow it becomes connected here
        mLocationClient.connect();
        return;
    }
    LocationRequest request = LocationRequest.create();
    request.setInterval(LOCATION_UPDATES_INTERVAL);
    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
Example 50
Project: message-samples-android-master  File: LocationUpdaterService.java View source code
private static void registerForLocationUpdates(final Context context) {
    GoogleApiClient googleApiClient = WRU.getInstance(context).waitForGoogleApi();
    Log.d(TAG, "registerForLocationUpdates(): requesting location updates from FusedLocationApi");
    LocationRequest request = new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setSmallestDisplacement(// to prevent unnecessary updates if we haven't moved 10m
    10).setInterval(// 5 minutes
    5 * 60 * 60 * 1000).setFastestInterval(// 5 seconds
    5000);
    PendingResult<Status> result = LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, request, getLocationUpdatedPendingIntent(context));
    Log.d(TAG, "registerForLocationUpdates(): result=" + result);
}
Example 51
Project: Monitordroid-master  File: LocationService.java View source code
/**
	 * Called by Location Services when the request to connect the client
	 * finishes successfully. At this point, you can request the current
	 * location or start periodic updates
	 */
@Override
public void onConnected(Bundle bundle) {
    locationRequest = LocationRequest.create();
    if (minutesTillRefresh != 0) {
        locationRequest.setInterval(1000 * 60 * minutesTillRefresh);
        locationRequest.setFastestInterval(1000 * 60 * minutesTillRefresh);
    } else {
        // Single update, set interval to
        locationRequest.setInterval(1);
        // 1ms
        locationRequest.setFastestInterval(1);
    }
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationClient.requestLocationUpdates(locationRequest, this);
}
Example 52
Project: MontrealJustInCase-master  File: LocationUpdatesManager.java View source code
private void checkLocationSettings() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(LOCATION_UPDATES_INTERVAL);
    mLocationRequest.setFastestInterval(LOCATION_UPDATES_FASTEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    final PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest).build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

        @Override
        public void onResult(@NonNull LocationSettingsResult result) {
            onLocationSettingsResult(result);
        }
    });
}
Example 53
Project: naonedbus-master  File: NaoLocationManager.java View source code
@Override
public void onConnected(Bundle connectionHint) {
    if (DBG)
        Log.d(LOG_TAG, "onConnected");
    final LocationRequest request = new LocationRequest();
    request.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    request.setSmallestDisplacement(20f);
    request.setFastestInterval(4000);
    request.setInterval(15000);
    mLocationClient.requestLocationUpdates(request, this);
    Location lastLocation = mLocationClient.getLastLocation();
    onLocationChanged(lastLocation);
    mHandler.postDelayed(mTimeOutRunnable, TIMEOUT);
}
Example 54
Project: onebusaway-android-master  File: LocationHelper.java View source code
private void setupGooglePlayServices() {
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the update interval to 5 seconds
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    // Set the fastest update interval to 1 second
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
    // Init Google Play Services as early as possible in the Fragment lifecycle to give it time
    GoogleApiAvailability api = GoogleApiAvailability.getInstance();
    if (api.isGooglePlayServicesAvailable(mContext) == ConnectionResult.SUCCESS) {
        mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
        mGoogleApiClient.connect();
    }
}
Example 55
Project: OpenLocate-master  File: LocationService.java View source code
@Override
public void onConnected(Bundle bundle) {
    Log.v(TAG, "connected");
    String lat, longitude;
    Location mLastLocation;
    // mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
    //mGoogleApiClient);
    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(300000);
    mLocationRequest.setFastestInterval(300000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
// lat = String.valueOf(mLastLocation.getLatitude());
// longitude = String.valueOf(mLastLocation.getLongitude());
//  Log.v(TAG,lat);
}
Example 56
Project: PrayTime-Android-master  File: LocationHelper.java View source code
private LocationRequest createLocationRequest() {
    if (mCoarseLocationRequest == null) {
        mCoarseLocationRequest = new LocationRequest();
        mCoarseLocationRequest.setInterval(5000);
        mCoarseLocationRequest.setFastestInterval(1000);
        mCoarseLocationRequest.setNumUpdates(1);
        mCoarseLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    }
    return mCoarseLocationRequest;
}
Example 57
Project: Rollout-master  File: LocationManager.java View source code
@Override
public void run() {
    LocationRequest locationRequest = new LocationRequest().setFastestInterval(fastestIntervalInMs).setInterval(intervalInMs).setPriority(accuracy);
    Context context = application.getApplicationContext();
    Intent updateIntent = new Intent(context, LocationUpdateIntentService.class);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, updateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    GoogleApiClient locationClient = locationClientProvider.get();
    locationClient.blockingConnect();
    fusedLocationProviderApi.requestLocationUpdates(locationClient, locationRequest, pendingIntent);
}
Example 58
Project: rover-android-master  File: MainActivity.java View source code
public void onUpdateLocationClicked(View view) {
    //Rover.updateLocation();
    GoogleApiConnection connection = new GoogleApiConnection(getApplicationContext());
    final LocationRequest locationRequest = new LocationRequest().setInterval(1).setFastestInterval(1).setSmallestDisplacement(0).setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    final Context context = getApplicationContext();
    connection.setCallbacks(new GoogleApiConnection.Callbacks() {

        @Override
        public int onConnected(final GoogleApiClient client) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, new LocationListener() {

                    @Override
                    public void onLocationChanged(Location location) {
                        client.disconnect();
                    //Rover.updateLocation(location);
                    }
                });
            }
            return GoogleApiConnection.KEEP_ALIVE;
        }
    });
    connection.connect();
}
Example 59
Project: sharemyposition-master  File: ShareMyPosition.java View source code
@Override
public void onConnected(Bundle bundle) {
    if (this.mLocationClient != null && this.mLocationClient.isConnected()) {
        final LocationRequest locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setNumUpdates(1);
        this.mLocationClient.requestLocationUpdates(locationRequest, this);
        Log.d(LOG, "onConnected");
    }
}
Example 60
Project: steptastic-master  File: WatchListenerService.java View source code
@Override
public void onConnected(Bundle bundle) {
    Log.d(TAG, "onConnected()");
    connectToWatch();
    boolean hasFineLocation = ActivityCompat.checkSelfPermission(WatchListenerService.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    boolean hasCoarseLocation = ActivityCompat.checkSelfPermission(WatchListenerService.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    if (!hasFineLocation && !hasCoarseLocation) {
        // no permission!
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, new LocationRequest().setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY).setFastestInterval(// at most once a minute
    60 * 1000).setInterval(// at least once every 10 minutes
    10 * 60 * 1000), locationListener);
}
Example 61
Project: Surviving-with-android-master  File: MainActivity.java View source code
private void getUVIndex() {
    System.out.println("Get UV Index");
    if (!googleClient.isConnected()) {
        // Try to connect again
        googleClient.connect();
    }
    if (!googleClient.isConnected()) {
        showErrorMessage();
        return;
    }
    try {
        Location loc = getLocation();
        LocationRequest req = new LocationRequest();
        req.setInterval(5 * 1000);
        req.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        LocationServices.FusedLocationApi.requestLocationUpdates(googleClient, req, this);
    } catch (SecurityException t) {
        t.printStackTrace();
    }
}
Example 62
Project: training-content-master  File: MainActivity.java View source code
protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    //provide update after every 20 seconds
    mLocationRequest.setInterval(20000);
    // provide update if there is an update after 5 seconds also
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
Example 63
Project: Transit-master  File: LocationHelper.java View source code
private void setupGooglePlayServices() {
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the update interval to 5 seconds
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    // Set the fastest update interval to 1 second
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
    // Init Google Play Services as early as possible in the Fragment lifecycle to give it time
    GoogleApiAvailability api = GoogleApiAvailability.getInstance();
    if (api.isGooglePlayServicesAvailable(mContext) == ConnectionResult.SUCCESS) {
        mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
        mGoogleApiClient.connect();
    }
}
Example 64
Project: trigger.io-background_geolocation-master  File: BackgroundLocationService.java View source code
@Override
public void onCreate() {
    super.onCreate();
    mInProgress = false;
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    // Set the update interval to 5 seconds
    mLocationRequest.setInterval(Constants.UPDATE_INTERVAL);
    // Set the fastest update interval to 1 second
    mLocationRequest.setFastestInterval(Constants.FASTEST_INTERVAL);
    servicesAvailable = servicesConnected();
    /*
         * Create a new location client, using the enclosing class to
         * handle callbacks.
         */
    mLocationClient = new LocationClient(this, this, this);
}
Example 65
Project: YourAppIdea-master  File: AroundMeFragment.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ((YourApplication) getActivity().getApplication()).inject(this);
    setRetainInstance(true);
    setHasOptionsMenu(true);
    mGoogleApiClient = new GoogleApiClient.Builder(this.getActivity()).addApi(LocationServices.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
    mRequest = LocationRequest.create().setInterval(15000).setFastestInterval(5000).setSmallestDisplacement(50).setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    mGeocoder = new Geocoder(this.getActivity(), Locale.getDefault());
    mPlaceListAdapter = new PlaceRecyclerAdapter(new ArrayList<Place>());
    if (savedInstanceState != null) {
        this.mUseLocationClient = savedInstanceState.getBoolean("useLocationClient", true);
        this.mCityName = savedInstanceState.getString("cityName");
        this.mCurrentLocation = savedInstanceState.getParcelable("currentLocation");
        this.mLocalProvider = savedInstanceState.getBoolean("localProvider", true);
    }
    if (this.mLocalProvider) {
        mPlaceProvider = new PlaceLocalProvider(this, this);
    } else {
        mPlaceProvider = new PlaceRemoteProvider(this, this);
    }
}
Example 66
Project: aerogear-android-cookbook-master  File: MainActivity.java View source code
// -- Android Life Cycle ----------------------------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    application = (AeroDocApplication) getApplication();
    contentPanel = findViewById(R.id.contentPanel);
    availableLeadsFragments = new AvailableLeadsFragments();
    acceptedLeadsFragments = new AcceptedLeadsFragments();
    // -- Dropdown (Status)
    Spinner spinner = (Spinner) findViewById(R.id.status);
    ArrayAdapter<String> spinnerAdapter = (ArrayAdapter) spinner.getAdapter();
    int actualStatus = spinnerAdapter.getPosition(application.getSaleAgent().getStatus());
    spinner.setSelection(actualStatus, true);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            String status = (String) adapterView.getItemAtPosition(position);
            if (!application.getSaleAgent().getStatus().equals(status)) {
                updateStatus(status);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    });
    // -- Tabs (Leads - Available & Archived)
    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
    pager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
    tabs.setupWithViewPager(pager);
    // -- Track Moviment
    mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
Example 67
Project: assassins-master  File: LocationService.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Log.d(TAG, "received intent [" + action + "]");
    if (action.equals(PushNotifications.MATCH_COUNTDOWN) || action.equals(User.LOGIN_COMPLETE) || action.equals(PushNotifications.MATCH_START)) {
        sendLocationToServer(locationClient.getLastLocation());
    } else if (action.equals(PlayerModel.TARGET_RANGE_CHANGED) || action.equals(PlayerModel.ENEMY_RANGE_CHANGED)) {
        //TODO if the user is not moving, do not request location updates
        //use activity recognition (in comments below)
        //throttle location updates based on the nearest of these two ranges
        String tRange = PlayerModel.getTargetProximity(LocationService.this);
        String eRange = PlayerModel.getEnemyProximity(LocationService.this);
        int interval = SEARCH_INTERVAL;
        float dist = SEARCH_MIN_DISPLACEMENT;
        int priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
        if (tRange != null && eRange != null) {
            if (tRange.equals(PlayerModel.ATTACK_RANGE) || eRange.equals(PlayerModel.ATTACK_RANGE)) {
                interval = ATTACK_INTERVAL;
                dist = ATTACK_MIN_DISPLACEMENT;
                priority = LocationRequest.PRIORITY_HIGH_ACCURACY;
            } else if (tRange.equals(PlayerModel.HUNT_RANGE) || eRange.equals(PlayerModel.HUNT_RANGE)) {
                interval = HUNT_INTERVAL;
                dist = HUNT_MIN_DISPLACEMENT;
                priority = LocationRequest.PRIORITY_HIGH_ACCURACY;
            }
        }
        requestLocationUpdates(interval, dist, priority);
    } else if (action.equals(PushNotifications.MATCH_END)) {
        requestLocationUpdates(10000, 5.0f, LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    }
}
Example 68
Project: effective_android_sample-master  File: MainActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // ス�ット用�アダプタを作�
    ArrayAdapter<Spot> adapter = new ArrayAdapter<Spot>(this, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    adapter.add(SPOT_SKYTREE);
    adapter.add(SPOT_GORYOKAKU);
    adapter.add(SPOT_SAKURAJIMA);
    // スピナーを�期化
    Spinner spSpot = (Spinner) findViewById(R.id.sp_spot);
    spSpot.setAdapter(adapter);
    spSpot.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Log.d("tag", "onItemSelected");
            selectedSpot = (Spot) parent.getItemAtPosition(position);
            if (mLocationClient != null && mLocationClient.isConnected()) {
                Location lastLocation = mLocationClient.getLastLocation();
                if (lastLocation != null) {
                    updateDistanceText(lastLocation);
                }
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
    // �離表示用TextViewを�期化
    tvDistance = (TextView) findViewById(R.id.tv_distance);
    updateDistanceText(999);
    // LocationRequestを�期化
    {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setInterval(5000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setFastestInterval(1000);
    }
    // LocationClientを�期化
    mLocationClient = new LocationClient(this, this, this);
    startLocationUpdates();
}
Example 69
Project: flat-flatmates-master  File: GoogleMapsActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (servicesOk()) {
        setContentView(R.layout.google_maps);
        if (initMap()) {
            Intent intent = getIntent();
            if (HostFlat.SPACE_INTENT.equals(intent.getAction())) {
                hashMapSpaceDetails = (HashMap<String, String>) intent.getSerializableExtra("spaceDetails");
                spaceType = 1;
            }
            if (HostFlatMate.SPACE_INTENT.equals(intent.getAction())) {
                hashMapSpaceDetails = (HashMap<String, String>) intent.getSerializableExtra("spaceDetails");
                spaceType = 2;
            }
            if (HostRoom.SPACE_INTENT.equals(intent.getAction())) {
                hashMapSpaceDetails = (HashMap<String, String>) intent.getSerializableExtra("spaceDetails");
                spaceType = 3;
            }
            if (HostPg.SPACE_INTENT.equals(intent.getAction())) {
                hashMapSpaceDetails = (HashMap<String, String>) intent.getSerializableExtra("spaceDetails");
                spaceType = 4;
            }
            mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
            mLocationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(// 60 seconds, in milliseconds
            60 * 1000).setFastestInterval(// 10 second, in milliseconds
            10 * 1000);
            atvPlaces = (AutoCompleteTextView) findViewById(R.id.atv_places);
            atvPlaces.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    getPlacesData(s.toString());
                //placesTask = new PlacesTask();
                //placesTask.execute(s.toString());
                }

                @Override
                public void afterTextChanged(Editable s) {
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub
                }
            });
        }
    }
}
Example 70
Project: getLastLocationUsingGPS-android-master  File: MapsActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    setUpMapIfNeeded();
    btn_send_location = (Button) findViewById(R.id.send_my_location_btn);
    btn_send_location.setOnClickListener(this);
    // 10 seconds, in milliseconds
    long interval = 10 * 1000;
    // 1 second, in milliseconds
    long fastestInterval = 1 * 1000;
    float minDisplacement = 0;
    //        // Check if has GPS
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();
    }
    mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY).setInterval(interval).setFastestInterval(fastestInterval).setSmallestDisplacement(minDisplacement);
// Check if has GPS by using Google play service
//        buildLocationSettingsRequest();
//        checkLocationSettings();
}
Example 71
Project: Hancel-master  File: LocationManagement.java View source code
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    tMgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
    mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    showNotification();
    /* CelId = Util.getIMEI(getApplicationContext());
		 if(CelId.length()>=5 )
			{
			 CelId = CelId.substring(0, 5);
			}*/
    minutos = intent.getIntExtra("minutos", 5);
    //inicia actualizacion 20 segundos antes de obtener nuestros datos
    long UpdateInterval = (minutos * 60) * 1000 - (4000);
    // actualiza el fast a la mitad de tiempo
    long fastUpdate = UpdateInterval - (60 * 1000);
    TrackId = intent.getIntExtra("track", 0);
    //new google PLay service api
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    mLocationRequest.setInterval(UpdateInterval);
    mLocationRequest.setFastestInterval(fastUpdate);
    mLocationClient = new LocationClient(this, this, this);
    mLocationClient.connect();
    handler.post(getData);
    //o algún otro metodo de inicio
    return (START_STICKY);
}
Example 72
Project: Rogo-master  File: NearYouMapActivity.java View source code
@Override
public void onConnected(Bundle arg0) {
    Toast.makeText(this, "Connected to location service", Toast.LENGTH_SHORT).show();
    request = LocationRequest.create();
    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // should be 60000
    request.setInterval(30000);
    // should be 10000
    request.setFastestInterval(10000);
    mLocationClient.requestLocationUpdates(request, this);
}
Example 73
Project: SEPTA-Android-master  File: TrainViewActionBarActivity.java View source code
/*
     * Called by LocationModel Services when the request to connect the
     * client finishes successfully. At this point, you can
     * request the current location or start periodic updates
     */
@Override
public void onConnected(Bundle dataBundle) {
    // Display the connection status
    LocationRequest mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
    mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
Example 74
Project: smart-location-lib-master  File: LocationGooglePlayServicesProvider.java View source code
private LocationRequest createRequest(LocationParams params, boolean singleUpdate) {
    LocationRequest request = LocationRequest.create().setFastestInterval(params.getInterval()).setInterval(params.getInterval()).setSmallestDisplacement(params.getDistance());
    switch(params.getAccuracy()) {
        case HIGH:
            request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            break;
        case MEDIUM:
            request.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            break;
        case LOW:
            request.setPriority(LocationRequest.PRIORITY_LOW_POWER);
            break;
        case LOWEST:
            request.setPriority(LocationRequest.PRIORITY_NO_POWER);
            break;
    }
    if (singleUpdate) {
        request.setNumUpdates(1);
    }
    return request;
}
Example 75
Project: SmartNavi-master  File: Locationer.java View source code
@Override
public void onConnected(Bundle arg0) {
    if (BuildConfig.debug) {
        Log.i("Location-Status", "onConnected");
    }
    try {
        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (lastLocation != null) {
            double startLat = lastLocation.getLatitude();
            double startLon = lastLocation.getLongitude();
            lastErrorGPS = lastLocation.getAccuracy();
            double altitude = lastLocation.getAltitude();
            lastLocationTime = lastLocation.getTime();
            if (BuildConfig.debug) {
                Log.i("Location-Status", "Last-Location: Error=" + lastErrorGPS + " Time:" + lastLocationTime);
            }
            double middleLat = startLat * 0.01745329252;
            double distanceLongitude = 111.3D * Math.cos(middleLat);
            Core.initialize(startLat, startLon, distanceLongitude, altitude, lastErrorGPS);
        }
        highRequest = LocationRequest.create();
        highRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // Update location every second
        highRequest.setInterval(1000);
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, highRequest, this);
        locationListener.onLocationUpdate(0);
        // remove location updates after 40s automatically
        mHandler.postDelayed(deaktivateTask, 40000);
    } catch (SecurityException e) {
        LocationManager locManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        boolean locationEnabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (locationEnabled == false) {
            if (BuildConfig.debug) {
                Log.i("Location-Status", "Security Exception");
            }
            locationListener.onLocationUpdate(5);
        } else {
            double startLat = 0;
            double startLon = 0;
            lastErrorGPS = 1000000;
            double altitude = 0;
            lastLocationTime = System.currentTimeMillis() - 1000000;
            double middleLat = startLat * 0.01745329252;
            double distanceLongitude = 111.3 * Math.cos(middleLat);
            Core.initialize(startLat, startLon, distanceLongitude, altitude, lastErrorGPS);
            locationListener.onLocationUpdate(8);
            mHandler.postDelayed(deaktivateTask, 40000);
        }
    }
}
Example 76
Project: speedr-master  File: MainService.java View source code
@Override
//Location permission is granted before the MainService is started
@SuppressWarnings("MissingPermission")
public void onConnected(Bundle bundle) {
    Crashlytics.log(Log.INFO, MainService.class.getSimpleName(), "Location connecting");
    LocationRequest locationRequest = new LocationRequest();
    //Request GPS location every 1 second
    locationRequest.setInterval(1000);
    locationRequest.setFastestInterval(500);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    try {
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, locationListener);
    } catch (IllegalStateException e) {
        Crashlytics.log(Log.INFO, MainService.class.getSimpleName(), "Play Services illegal state, retrying connection");
        Crashlytics.logException(e);
        googleApiClient.connect();
    }
    Crashlytics.log(Log.INFO, MainService.class.getSimpleName(), "Location connected");
}
Example 77
Project: amos-ss15-proj2-master  File: MainActivity.java View source code
@Override
public void init(Bundle savedInstanceState) {
    // Configure Navigation Drawer
    this.disableLearningPattern();
    this.allowArrowAnimation();
    this.setBackPattern(MaterialNavigationDrawer.BACKPATTERN_BACK_TO_FIRST);
    this.setDrawerHeaderImage(R.drawable.background_drawer);
    // Get all the saved user data to display some info in the navigation drawer
    showUserInfoInNavigationDrawer();
    SharedPreferences prefs = getSharedPreferences(Constants.SHARED_PREF_FILE_PREFERENCES, Context.MODE_PRIVATE);
    // Start timer to update the user's offers all the time
    if (AccountManager.isUserLoggedIn(this)) {
        Intent alarmIntent = new Intent(this, LocationUploadTimerReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 120 * 1000, pendingIntent);
    }
    // Subscribe to location updates
    LocationRequest request = //standard GMS LocationRequest
    LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(10000);
    ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(this);
    Subscription locationUpdateSubscription = locationProvider.getUpdatedLocation(request).subscribe(new Action1<Location>() {

        @Override
        public void call(Location location) {
            locationUpdater.setLastLocation(location);
        }
    });
    subscriptions.add(locationUpdateSubscription);
    // GPS availability
    if (!GPSavailable()) {
        checkForGPS();
    }
    // Registration for GCM, if we are not registered yet
    if (!gcmManager.isRegistered()) {
        Subscription subscription = gcmManager.register().compose(new DefaultTransformer<Void>()).retry(3).subscribe(new Action1<Void>() {

            @Override
            public void call(Void aVoid) {
                Timber.d("Registered at GCM.");
            }
        }, new CrashCallback(this, "failed to register for GCM"));
        subscriptions.add(subscription);
    }
    fillNavigationDrawer();
}
Example 78
Project: android-play-location-master  File: MainActivity.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Locate the UI widgets.
    mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button);
    mStopUpdatesButton = (Button) findViewById(R.id.stop_updates_button);
    mLatitudeTextView = (TextView) findViewById(R.id.latitude_text);
    mLongitudeTextView = (TextView) findViewById(R.id.longitude_text);
    mLastUpdateTimeTextView = (TextView) findViewById(R.id.last_update_time_text);
    mLocationInadequateWarning = (TextView) findViewById(R.id.location_inadequate_warning);
    // Set labels.
    mLatitudeLabel = getResources().getString(R.string.latitude_label);
    mLongitudeLabel = getResources().getString(R.string.longitude_label);
    mLastUpdateTimeLabel = getResources().getString(R.string.last_update_time_label);
    mRequestingLocationUpdates = false;
    mLastUpdateTime = "";
    // Update values using data stored in the Bundle.
    updateValuesFromBundle(savedInstanceState);
    // Kick off the process of building the GoogleApiClient, LocationRequest, and
    // LocationSettingsRequest objects.
    buildGoogleApiClient();
    createLocationRequest();
    buildLocationSettingsRequest();
}
Example 79
Project: android-SpeedTracker-master  File: WearableMainActivity.java View source code
private void requestLocation() {
    Log.d(TAG, "requestLocation()");
    /*
         * mGpsPermissionApproved covers 23+ (M+) style permissions. If that is already approved or
         * the device is pre-23, the app uses mSaveGpsLocation to save the user's location
         * preference.
         */
    if (mGpsPermissionApproved) {
        LocationRequest locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(UPDATE_INTERVAL_MS).setFastestInterval(FASTEST_INTERVAL_MS);
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this).setResultCallback(new ResultCallback<Status>() {

            @Override
            public void onResult(Status status) {
                if (status.getStatus().isSuccess()) {
                    if (Log.isLoggable(TAG, Log.DEBUG)) {
                        Log.d(TAG, "Successfully requested location updates");
                    }
                } else {
                    Log.e(TAG, "Failed in requesting location updates, " + "status code: " + status.getStatusCode() + ", message: " + status.getStatusMessage());
                }
            }
        });
    }
}
Example 80
Project: CodenameOne-master  File: AndroidLocationPlayServiceManager.java View source code
public void run() {
    LocationRequest r = locationRequest;
    com.codename1.location.LocationRequest request = getRequest();
    if (request != null) {
        LocationRequest lr = LocationRequest.create();
        if (request.getPriority() == com.codename1.location.LocationRequest.PRIORITY_HIGH_ACCUARCY) {
            lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        } else if (request.getPriority() == com.codename1.location.LocationRequest.PRIORITY_MEDIUM_ACCUARCY) {
            lr.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        } else {
            lr.setPriority(LocationRequest.PRIORITY_LOW_POWER);
        }
        lr.setInterval(request.getInterval());
        r = lr;
    }
    if (AndroidImplementation.getActivity() == null) {
        // we are in the background
        // Sometimes using regular locations in the background causes a crash
        // so we need to use the pending intent version.
        Context context = AndroidNativeUtil.getContext();
        Intent intent = new Intent(context, BackgroundLocationHandler.class);
        //an ugly workaround to the putExtra bug 
        if (bgListenerClass != null) {
            intent.setData(Uri.parse("http://codenameone.com/a?" + bgListenerClass.getName()));
        }
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        inMemoryBackgroundLocationListener = AndroidLocationPlayServiceManager.this;
        LocationServices.FusedLocationApi.requestLocationUpdates(getmGoogleApiClient(), r, pendingIntent);
    } else {
        LocationServices.FusedLocationApi.requestLocationUpdates(getmGoogleApiClient(), r, AndroidLocationPlayServiceManager.this);
    }
}
Example 81
Project: dashclock-master  File: WeatherExtension.java View source code
private void tryGooglePlayServicesGetLocationAndPublishWeatherUpdate(final Runnable errorRunnable) {
    int playServicesResult = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (playServicesResult != ConnectionResult.SUCCESS) {
        LOGW(TAG, "Google Play Services was unavailable (code " + playServicesResult + ").");
        if (errorRunnable != null) {
            errorRunnable.run();
        }
        return;
    }
    if (mLocationClient != null) {
        // an error.
        return;
    }
    LOGD(TAG, "Getting location using Google Play Services.");
    mLocationClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).addConnectionCallbacks(new ConnectionCallbacks() {

        @Override
        public void onConnected(Bundle bundle) {
            if (mServiceThreadHandler == null) {
                LOGW(TAG, "Empty Service thread handler; Play Services unavailable.");
                mLocationClient.disconnect();
                mLocationClient = null;
                if (errorRunnable != null) {
                    errorRunnable.run();
                }
                return;
            }
            mServiceThreadHandler.post(new Runnable() {

                @Override
                public void run() {
                    onHasLocation();
                }
            });
        }

        @Override
        public void onConnectionSuspended(int i) {
        }

        private void onHasLocation() {
            Location lastLocation = FusedLocationApi.getLastLocation(mLocationClient);
            if (lastLocation == null || (SystemClock.elapsedRealtimeNanos() - lastLocation.getElapsedRealtimeNanos()) >= STALE_LOCATION_NANOS) {
                LOGW(TAG, "Stale or missing last-known location; requesting " + "single location update.");
                Intent intent = new Intent(WeatherExtension.this, WeatherExtension.class);
                intent.setAction(ACTION_RECEIVED_LOCATION);
                PendingIntent locationPendingIntent = PendingIntent.getService(WeatherExtension.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, locationPendingIntent);
                // Schedule a retry if timing out. When the location request expires,
                // updates will simply stop, and we won't get any notification of this,
                // so handle it separately.
                mTimeoutHandler.removeCallbacksAndMessages(null);
                mTimeoutHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        LOGE(TAG, "Play Services location request timed out.");
                        disableOneTimeLocationListener();
                        scheduleRetry();
                    }
                }, LOCATION_TIMEOUT_MILLIS);
            } else {
                tryPublishWeatherUpdateFromGeolocation(lastLocation);
            }
            mLocationClient.disconnect();
            mLocationClient = null;
        }
    }).addOnConnectionFailedListener(new OnConnectionFailedListener() {

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            mLocationClient = null;
            if (errorRunnable != null) {
                errorRunnable.run();
            }
        }
    }).build();
    // Create a location request
    mLocationRequest = LocationRequest.create().setExpirationDuration(LOCATION_TIMEOUT_MILLIS - 1000).setFastestInterval(0).setInterval(0).setNumUpdates(1).setSmallestDisplacement(0).setPriority(LocationRequest.PRIORITY_LOW_POWER);
    // Connect to the location api
    mLocationClient.connect();
}
Example 82
Project: FWeather-master  File: LocationHelper.java View source code
@Override
public void onConnected(Bundle bundle) {
    if (!mLocationClient.isConnected()) {
        // Strange shit happens here sometimes...
        FLog.w(mContext, TAG, "LocationClient's onConnected was called, but the LocationClient is not connected. WTF!");
        onDisconnected();
    }
    // The LocationClient has connected
    FLog.d(mContext, TAG, "LocationClient has connected.");
    LocationRequest request = LocationRequest.create();
    request.setPriority(LocationRequest.PRIORITY_LOW_POWER);
    request.setFastestInterval(getMinUpdateInterval());
    FLog.v(TAG, "Requesting updates to the Play Services' Location Client...");
    mLocationClient.requestLocationUpdates(request, this);
    mPlayServicesConnRetriesLeft = PLAY_SERVICES_CONNECTION_RETRIES;
    onGenericConnected();
    Location currentLocation = mLocationClient.getLastLocation();
    if (currentLocation != null) {
        updateLocation(currentLocation);
    } else {
        FLog.d(TAG, "The Play Services' Location Client doesn't have a location available yet");
        startUpdateTimeout();
    }
}
Example 83
Project: landmarker-master  File: MainActivity.java View source code
/**
     * method for refreshing content from Places API.
     * will check location if its latest and do as needed
     */
private void checkLastLocation() {
    mLocationReq = new LocationRequest();
    mLocationReq.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationReq.setInterval(1000);
    mLocationReq.setFastestInterval(5000);
    mLocationReq.setNumUpdates(MAX_UPDATE_TRIES);
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation == null) {
        checkSettings();
        return;
    }
    //it exists, see how old it is
    int hours = getLocationAgeHours(mLastLocation);
    Log.d(TAG, mLastLocation + "\nHours since update: " + hours);
    if (hours > MIN_AGE_IN_HOURS) {
        // || seconds > 15 ) //for testing
        setLocationListener();
        return;
    }
    //location is fine, update places
    getNewPlaces();
}
Example 84
Project: MapDrawingTools-master  File: MapsActivity.java View source code
private void requestActivatingGPS() {
    LocationRequest locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setNumUpdates(5).setInterval(100);
    locationUpdatesObservable = locationProvider.getUpdatedLocation(locationRequest);
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest).setAlwaysShow(true);
    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

        @Override
        public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
            final Status status = locationSettingsResult.getStatus();
            switch(status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    getLastKnowLocation();
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    try {
                        // Show the dialog by calling startResolutionForResult(),
                        // and check the result in onActivityResult().
                        status.startResolutionForResult(MapsActivity.this, REQUEST_CHECK_SETTINGS);
                    } catch (IntentSender.SendIntentException e) {
                        e.printStackTrace();
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    Log.e(TAG, "Error happen during show Dialog for Turn of GPS");
                    break;
            }
        }
    });
}
Example 85
Project: Purple-Robot-master  File: FusedLocationProbe.java View source code
@Override
public void onConnected(Bundle bundle) {
    final LocationRequest request = new LocationRequest();
    request.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    SharedPreferences prefs = Probe.getPreferences(this._context);
    long freq = Long.parseLong(prefs.getString(FusedLocationProbe.FREQUENCY, Probe.DEFAULT_FREQUENCY));
    request.setInterval(freq);
    long distance = Long.parseLong(prefs.getString(FusedLocationProbe.DISTANCE, FusedLocationProbe.DEFAULT_DISTANCE));
    if (distance != 0)
        request.setSmallestDisplacement(distance);
    try {
        if (this._apiClient != null && this._apiClient.isConnected())
            LocationServices.FusedLocationApi.requestLocationUpdates(this._apiClient, request, this, this._context.getMainLooper());
    } catch (IllegalStateException e) {
        LogManager.getInstance(this._context).logException(e);
    }
}
Example 86
Project: Bluefruit_LE_Connect_Android-master  File: ControllerActivity.java View source code
private void registerEnabledSensorListeners(boolean register) {
    // Accelerometer
    if (register && (mSensorData[kSensorType_Accelerometer].enabled || mSensorData[kSensorType_Quaternion].enabled)) {
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    } else {
        mSensorManager.unregisterListener(this, mAccelerometer);
    }
    // Gyroscope
    if (register && mSensorData[kSensorType_Gyroscope].enabled) {
        mSensorManager.registerListener(this, mGyroscope, SensorManager.SENSOR_DELAY_NORMAL);
    } else {
        mSensorManager.unregisterListener(this, mGyroscope);
    }
    // Magnetometer
    if (register && (mSensorData[kSensorType_Magnetometer].enabled || mSensorData[kSensorType_Quaternion].enabled)) {
        if (mMagnetometer == null) {
            new AlertDialog.Builder(this).setMessage(getString(R.string.controller_magnetometermissing)).setPositiveButton(android.R.string.ok, null).show();
        } else {
            mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_NORMAL);
        }
    } else {
        mSensorManager.unregisterListener(this, mMagnetometer);
    }
    // Location
    if (mGoogleApiClient.isConnected()) {
        if (register && mSensorData[kSensorType_Location].enabled) {
            LocationRequest locationRequest = new LocationRequest();
            locationRequest.setInterval(2000);
            locationRequest.setFastestInterval(500);
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            // Location updates should have already been granted to scan for bluetooth peripherals, so we dont ask for them again
            try {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
            } catch (SecurityException e) {
                Log.e(TAG, "Security exception requesting location updates: " + e);
            }
        } else {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }
}
Example 87
Project: CFADeviceManager-Android-master  File: MainActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //  intent = new Intent(this, CFAService.class);
    gs = (GlobalState) getApplication();
    // Initialize Device Policy Manager service and our receiver class
    devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    demoDeviceAdmin = new ComponentName(this, MyDeviceAdminReceiver.class);
    gps = new GPSTracker(getApplicationContext());
    if (devicePolicyManager.isAdminActive(demoDeviceAdmin)) {
    // do nothing
    } else {
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, demoDeviceAdmin);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, getString(R.string.device_admin_explanation));
        startActivity(intent);
    }
    getBaseContext().getApplicationContext().sendBroadcast(new Intent("StartupReceiver_Manual_Start"));
    Battery_Status = gs.getBatteryStatus();
    //   locationDetector = new LocationDetector(this);
    myDbHelp = DatabaseHelper.getInstance(getApplicationContext());
    try {
        myDbHelp.createDataBase();
        imei = gs.getDeviceImei();
        myDbHelp.insertImei(imei);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Intent serviceIntent = new Intent(this, MyMqttService.class);
    serviceIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    startService(serviceIntent);
    logoview = (ImageView) findViewById(R.id.logoview);
    nameview = (TextView) findViewById(R.id.nameview);
    usernameet = (EditText) findViewById(R.id.usernameet);
    passwordet = (EditText) findViewById(R.id.pwet);
    submit = (Button) findViewById(R.id.submit);
    maintv = (TextView) findViewById(R.id.maintv);
    maintv.setTextSize(20);
    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    Log.e(TAG, "saved username: " + sharedpreferences.getString(usernamePref, "noValun"));
    Log.e(TAG, "saved pw: " + sharedpreferences.getString(passwordPref, "noValpw"));
    if (sharedpreferences.getString(usernamePref, "noValun").equals("admin") && sharedpreferences.getString(passwordPref, "noValpw").equals("cfap")) {
        Log.e(TAG, "username & pw already saved");
        logoview.setVisibility(View.GONE);
        nameview.setVisibility(View.GONE);
        usernameet.setVisibility(View.GONE);
        passwordet.setVisibility(View.GONE);
        submit.setVisibility(View.GONE);
        maintv.setVisibility(View.VISIBLE);
        maintv.setText("Your device is now registered with the Government of Andhra Pradesh, India");
        if (googleApiClient == null) {
            googleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
            googleApiClient.connect();
            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(30 * 1000);
            locationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
            //**************************
            //this is the key ingredient
            builder.setAlwaysShow(true);
            //**************************
            PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

                @Override
                public void onResult(LocationSettingsResult result) {
                    final Status status = result.getStatus();
                    final LocationSettingsStates state = result.getLocationSettingsStates();
                    switch(status.getStatusCode()) {
                        case LocationSettingsStatusCodes.SUCCESS:
                            // requests here.
                            break;
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            // a dialog.
                            try {
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                status.startResolutionForResult(MainActivity.this, 1000);
                            } catch (IntentSender.SendIntentException e) {
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            // settings so we won't show the dialog.
                            break;
                    }
                }
            });
        }
    /*  Intent serviceIntent = new Intent(this, MyMqttService.class);
            serviceIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startService(serviceIntent); */
    }
    submit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if ((usernameet.getText().toString().equals("admin") && passwordet.getText().toString().equals("cfap"))) {
                logoview.setVisibility(View.GONE);
                nameview.setVisibility(View.GONE);
                usernameet.setVisibility(View.GONE);
                passwordet.setVisibility(View.GONE);
                submit.setVisibility(View.GONE);
                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(usernamePref, "admin");
                editor.putString(passwordPref, "cfap");
                editor.commit();
                maintv.setVisibility(View.VISIBLE);
                maintv.setText("Registering Device...");
                Thread t = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        register();
                    }
                });
                t.start();
            } else {
                usernameet.setText("");
                passwordet.setText("");
                Toast.makeText(MainActivity.this, "The login details you entered are incorrect. Please try again!", 3).show();
            }
        }
    });
}
Example 88
Project: GeoLog-master  File: BackgroundService.java View source code
@SuppressLint("NewApi")
private void updateListeners(int flags) {
    if (!(activityConnected && locationConnected && (currentProfile != null)))
        return;
    if (currentProfile.getType() == Type.OFF) {
        stopSelf();
    }
    if ((flags & FLAG_PROFILE) == FLAG_PROFILE) {
        Debug.log("Profile update");
        lastActivity = Activity.UNKNOWN;
        lastConfidence = 0;
        scheduledReduceAccuracyTime = 0L;
        lastProfileUpdate = SystemClock.elapsedRealtime();
    }
    Accuracy originalAccuracy = lastLocationAccuracy;
    Database.Profile.ActivitySettings wanted = currentProfile.getActivitySettings(lastActivity);
    Database.Accuracy wantedAccuracy = wanted.getAccuracy();
    int wantedLocationInterval = wanted.getLocationInterval();
    int wantedActivityInterval = wanted.getActivityInterval();
    boolean allowUpdateActivityInterval = true;
    boolean allowUpdateLocationInterval = true;
    boolean allowUpdateLocationAccuracy = true;
    if (((SystemClock.elapsedRealtime() > lastProfileUpdate + (90 * 1000)) || (SystemClock.elapsedRealtime() < lastProfileUpdate)) && (currentProfile.getReduceAccuracyDelay() > 0) && ((wantedActivityInterval > lastActivityInterval) || (wantedLocationInterval > lastLocationInterval) || (Database.accuracyToInt(wantedAccuracy) < Database.accuracyToInt(lastLocationAccuracy)))) {
        long left = 0;
        if (scheduledReduceAccuracyTime == 0) {
            left = currentProfile.getReduceAccuracyDelay() * 1000;
            scheduledReduceAccuracyTime = SystemClock.elapsedRealtime() + left;
            alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, scheduledReduceAccuracyTime + 1000, alarmCallback);
        } else {
            left = scheduledReduceAccuracyTime - SystemClock.elapsedRealtime();
        }
        if (left <= 0)
            scheduledReduceAccuracyTime = 0L;
        allowUpdateActivityInterval = ((left <= 0) || (wantedActivityInterval < lastActivityInterval) || (lastActivityInterval == -1));
        allowUpdateLocationInterval = ((left <= 0) || (wantedLocationInterval < lastLocationInterval) || (lastLocationInterval == -1));
        allowUpdateLocationAccuracy = ((left <= 0) || (Database.accuracyToInt(wantedAccuracy) > Database.accuracyToInt(lastLocationAccuracy)));
        if (!allowUpdateActivityInterval)
            wantedActivityInterval = lastActivityInterval;
        if (!allowUpdateLocationInterval)
            wantedLocationInterval = lastLocationInterval;
        if (!allowUpdateLocationAccuracy)
            wantedAccuracy = lastLocationAccuracy;
        if (!allowUpdateActivityInterval)
            Debug.log(String.format(Locale.ENGLISH, "ActivityInterval --> Delay (%ds remaining)", (left / 1000)));
        if (!allowUpdateLocationInterval)
            Debug.log(String.format(Locale.ENGLISH, "LocationInterval --> Delay (%ds remaining)", (left / 1000)));
        if (!allowUpdateLocationAccuracy)
            Debug.log(String.format(Locale.ENGLISH, "LocationAccuracy --> Delay (%ds remaining)", (left / 1000)));
    } else {
        scheduledReduceAccuracyTime = 0;
        alarm.cancel(alarmCallback);
    }
    if ((wantedAccuracy != lastLocationAccuracy) || (wantedLocationInterval != lastLocationInterval)) {
        String s = "NONE";
        if (wantedAccuracy == Accuracy.LOW)
            s = "LOW";
        if (wantedAccuracy == Accuracy.HIGH)
            s = "HIGH";
        Debug.log(String.format(Locale.ENGLISH, "Location --> %s %ds", s, wantedLocationInterval));
        locationClient.removeLocationUpdates(locationListener);
        if ((wantedAccuracy != Accuracy.NONE) && (wantedLocationInterval > 0)) {
            if ((lastLocationAccuracy == Accuracy.NONE) || (lastLocationInterval == 0))
                isSegmentStart = true;
            LocationRequest req = new LocationRequest();
            req.setFastestInterval(wantedLocationInterval * 250);
            req.setInterval(wantedLocationInterval * 1000);
            if (lastLocationAccuracy == Accuracy.NONE)
                req.setPriority(LocationRequest.PRIORITY_NO_POWER);
            if (lastLocationAccuracy == Accuracy.LOW)
                req.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            if (lastLocationAccuracy == Accuracy.HIGH)
                req.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationClient.requestLocationUpdates(req, locationListener);
        }
        lastLocationAccuracy = wantedAccuracy;
        lastLocationInterval = wantedLocationInterval;
    }
    if (wantedActivityInterval != lastActivityInterval) {
        Debug.log(String.format(Locale.ENGLISH, "Activity --> %ds", wantedActivityInterval));
        activityClient.removeActivityUpdates(activityIntent);
        if ((wantedActivityInterval == 0) && (lastActivityInterval != 0)) {
            lastActivity = Activity.UNKNOWN;
            lastConfidence = 0;
        }
        if (wantedActivityInterval != 0) {
            activityClient.requestActivityUpdates(wantedActivityInterval * 1000, activityIntent);
        }
        lastActivityInterval = wantedActivityInterval;
    }
    if ((flags & FLAG_ACTIVITY_UPDATE) == FLAG_ACTIVITY_UPDATE) {
        if ((lastLocation == null) || (lastLocation.getActivity() != lastActivity) || (lastLocation.getConfidence() != lastConfidence)) {
            Debug.log("Activity update");
            if (lastLocation == null) {
                lastLocationDuplicates = 0;
                lastLocation = new Database.Location();
                lastLocation.setTime(System.currentTimeMillis());
            }
            lastLocation.setActivity(lastActivity);
            lastLocation.setConfidence(lastConfidence);
        }
    } else if ((flags & FLAG_LOCATION_UPDATE) == FLAG_LOCATION_UPDATE) {
        if ((lastLocation == null) || (lastLocLoc == null) || (lastLocation.getLatitude() != lastLocLoc.getLatitude()) || (lastLocation.getLongitude() != lastLocLoc.getLongitude()) || (lastLocation.getAccuracyDistance() > lastLocLoc.getAccuracy()) || (lastLocation.getActivity() != lastActivity) || (lastLocation.getConfidence() != lastConfidence) || (lastLocation.getAccuracySetting() != originalAccuracy) || (isSegmentStart)) {
            Debug.log("Location update");
            if (lastLocationDuplicates > 0) {
                Debug.log("Saving last duplicate (out of " + String.valueOf(lastLocationDuplicates) + ")");
                Database.Location.copy(databaseHelper, lastLocation);
            }
            lastLocationDuplicates = 0;
            Database.Location loc = new Database.Location();
            loc.setActivity(lastActivity);
            loc.setConfidence(lastConfidence);
            loc.setBattery(lastBatteryLevel);
            loc.setAccuracySetting(originalAccuracy);
            loc.isSegmentStart(isSegmentStart);
            loc.loadFromLocation(lastLocLoc);
            Debug.log("Saved to database: " + String.valueOf(loc.saveToDatabase(databaseHelper)));
            lastLocation = loc;
            isSegmentStart = false;
        } else if ((lastLocation != null) && (lastLocLoc != null)) {
            lastLocationDuplicates++;
            lastLocation.setActivity(lastActivity);
            lastLocation.setConfidence(lastConfidence);
            lastLocation.setBattery(lastBatteryLevel);
            lastLocation.setAccuracySetting(originalAccuracy);
            lastLocation.isSegmentStart(isSegmentStart);
            lastLocation.loadFromLocation(lastLocLoc);
        }
    }
    if (lastLocation != null) {
        notificationBuilder.setWhen(lastLocation.getTime()).setContentText(String.format(Locale.ENGLISH, "%s ~ %d%% / %.5f, %.5f ~ %.0f%s", Database.activityToString(lastLocation.getActivity()), lastLocation.getConfidence(), lastLocation.getLatitude(), lastLocation.getLongitude(), metric ? lastLocation.getAccuracyDistance() : lastLocation.getAccuracyDistance() * SettingsFragment.METER_FEET_RATIO, metric ? "m" : "ft"));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            notificationBuilder.setShowWhen(true);
        }
        updateNotification();
    }
}
Example 89
Project: iNaturalistAndroid-master  File: INaturalistApp.java View source code
/** Checks if location services are enabled */
public boolean isLocationEnabled(final OnLocationStatus locationCallback) {
    // First, check if GPS is disabled
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    boolean gpsEnabled = (lm.isProviderEnabled(LocationManager.GPS_PROVIDER) || lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
    if (!gpsEnabled)
        return false;
    // Next, see if specifically the user has revoked location access to our app
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).build();
        mGoogleApiClient.connect();
    }
    if (locationCallback != null) {
        final LocationRequest locationRequest = new LocationRequest();
        locationRequest.setInterval(10000);
        locationRequest.setFastestInterval(5000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

            @Override
            public void onResult(LocationSettingsResult locationSettingsResult) {
                final Status status = locationSettingsResult.getStatus();
                switch(status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can initialize location
                        // requests here.
                        locationCallback.onLocationStatus(true);
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied
                        locationCallback.onLocationStatus(false);
                        break;
                }
            }
        });
    }
    return gpsEnabled;
}
Example 90
Project: io2015-codelabs-master  File: UtilityService.java View source code
/**
     * Called when a location update is requested
     */
private void requestLocationInternal() {
    Log.v(TAG, ACTION_REQUEST_LOCATION);
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).build();
    // It's OK to use blockingConnect() here as we are running in an
    // IntentService that executes work on a separate (background) thread.
    ConnectionResult connectionResult = googleApiClient.blockingConnect(Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);
    if (connectionResult.isSuccess() && googleApiClient.isConnected()) {
        Intent locationUpdatedIntent = new Intent(this, UtilityService.class);
        locationUpdatedIntent.setAction(ACTION_LOCATION_UPDATED);
        // Send last known location out first if available
        Location location = FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            Intent lastLocationIntent = new Intent(locationUpdatedIntent);
            lastLocationIntent.putExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED, location);
            startService(lastLocationIntent);
        }
        // Request new location
        LocationRequest mLocationRequest = new LocationRequest().setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, PendingIntent.getService(this, 0, locationUpdatedIntent, 0));
        googleApiClient.disconnect();
    } else {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG, connectionResult.getErrorCode()));
    }
}
Example 91
Project: PaintDrip-master  File: MapsActivity.java View source code
@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
    if (googleApiClient.isConnected()) {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        fusedLocationProviderApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }
}
Example 92
Project: recommendations-master  File: ExploreFragment.java View source code
private void onRequestLocationUpdates() {
    if (areAnyLocationProvidersEnabled()) {
        shouldRequestLocationUpdatesOnConnect = true;
        onPreLocationUpdate();
        LocationRequest locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(// 10 seconds
        10 * 1_000).setFastestInterval(// 1 second
        1_000);
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    } else {
        Toast.makeText(getActivity().getApplicationContext(), R.string.enable_location_updates, Toast.LENGTH_LONG).show();
        onCompleteLocationUpdate();
    }
}
Example 93
Project: rox-android-master  File: ExploreFragment.java View source code
private void onRequestLocationUpdates() {
    if (areAnyLocationProvidersEnabled()) {
        shouldRequestLocationUpdatesOnConnect = true;
        onPreLocationUpdate();
        LocationRequest locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(// 10 seconds
        10 * 1_000).setFastestInterval(// 1 second
        1_000);
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    } else {
        Toast.makeText(getActivity().getApplicationContext(), R.string.enable_location_updates, Toast.LENGTH_LONG).show();
        onCompleteLocationUpdate();
    }
}
Example 94
Project: samsung-chord-hackathon-master  File: NearbyActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nearby);
    // Show the Up button in the action bar.
    getActionBar().setDisplayHomeAsUpEnabled(true);
    mRestaurantsListV = (ListView) findViewById(R.id.restaurants_list);
    mRestaurantsListV.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
            // Launch Reservations activity
            GooglePlaces restaurantPlace = mGooglePlacesList.get(position);
            Intent intent = new Intent(NearbyActivity.this, ReservationFormActivity.class);
            intent.putExtra(AppConstants.RESTAURANT_NAME, restaurantPlace.getName());
            intent.putExtra(AppConstants.RESTAURANT_ADDRESS, restaurantPlace.getVicinity());
            startActivity(intent);
        }
    });
    mSearchField = (EditText) findViewById(R.id.search_field);
    mSearchButton = (Button) findViewById(R.id.search_button);
    mSearchButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            mSearchData = mSearchField.getText().toString();
            String[] params = new String[3];
            ;
            // Lat
            params[0] = // Lat
            "37.37677240";
            params[1] = "-121.92164020";
            params[2] = mSearchData;
            new FindNearbyRestaurantsTask().execute(params);
        }
    });
    // Get handles to the UI view objects
    mLatLng = (TextView) findViewById(R.id.lat_lng);
    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
    mConnectionState = (TextView) findViewById(R.id.text_connection_state);
    mConnectionStatus = (TextView) findViewById(R.id.text_connection_status);
    // Create a new global location parameters object
    mLocationRequest = LocationRequest.create();
    /*
		 * Set the update interval
		 */
    mLocationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the interval ceiling to one minute
    mLocationRequest.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
    // Note that location updates are off until the user turns them on
    mUpdatesRequested = false;
    // Open Shared Preferences
    mPrefs = getSharedPreferences(LocationUtils.SHARED_PREFERENCES, Context.MODE_PRIVATE);
    // Get an editor
    mEditor = mPrefs.edit();
    /*
		 * Create a new location client, using the enclosing class to handle
		 * callbacks.
		 */
    mLocationClient = new LocationClient(this, this, this);
}
Example 95
Project: wire-android-master  File: LocationFragment.java View source code
private void startPlayServicesListeningForCurrentLocation() {
    Timber.i("startPlayServicesListeningForCurrentLocation");
    if (locationRequest != null) {
        return;
    }
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(1000);
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
Example 96
Project: XPrivacyTester-master  File: MainActivity.java View source code
@Override
public void onConnected(Bundle arg0) {
    // FusedLocationApi
    try {
        Location loc = LocationServices.FusedLocationApi.getLastLocation(gClient);
        ((TextView) findViewById(R.id.GMS5_getLastLocation)).setText(loc == null ? "null" : loc.toString());
    } catch (Throwable ex) {
        ex.printStackTrace();
        ((TextView) findViewById(R.id.GMS5_getLastLocation)).setText(ex.getClass().getName());
    }
    LocationRequest locRec = new LocationRequest();
    locRec.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    LocationServices.FusedLocationApi.requestLocationUpdates(gClient, locRec, new LocationListener() {

        @Override
        public void onLocationChanged(Location loc) {
            try {
                ((TextView) findViewById(R.id.GMS5_requestLocationUpdates)).setText(loc == null ? "null" : loc.toString());
            } catch (Throwable ex) {
                ex.printStackTrace();
                ((TextView) findViewById(R.id.GMS5_requestLocationUpdates)).setText(ex.getClass().getName());
            }
        }
    });
    // ActivityRecognitionApi
    Intent activityIntent = new Intent(this, MainActivity.class);
    PendingIntent pi = PendingIntent.getService(MainActivity.this, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(gClient, 0, pi);
    ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(gClient, pi);
    // AppIndexApi
    PendingResult<Status> pr = AppIndex.AppIndexApi.view(gClient, this, new Intent(), "XPrivacy", null, null);
    pr.cancel();
    android.util.Log.w("XPrivacyTester", "cancelled=" + pr.isCanceled());
    pr.setResultCallback(new ResultCallback<Status>() {

        @Override
        public void onResult(Status status) {
            android.util.Log.w("XPrivacyTester", "callback status=" + status.getStatusCode());
        }
    });
    Status status = pr.await();
    android.util.Log.w("XPrivacyTester", "status=" + status.getStatusCode());
    AppIndex.AppIndexApi.viewEnd(gClient, this, new Intent());
}
Example 97
Project: DroidMapper-master  File: CameraActivity.java View source code
/**
     * After calling connect() on GoogleApiClient, this method will be invoked asynchronously when
     * the connect request has successfully completed.
     *
     * @param bundle Bundle of data provided to clients by Google Play services. May be null if no
     *               content is provided by the service.
     */
@Override
public void onConnected(Bundle bundle) {
    lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    if (lastLocation != null) {
        cameraView.setGeoTaggingLocation(lastLocation);
    }
    updateShownLocationDataHelper();
    // Request location updates from Google Play Services Fused Provider:
    if (intervalType == INTERVAL_TYPE_DISTANCE) {
        LocationRequest locationRequest = new LocationRequest();
        locationRequest.setInterval(1000L);
        locationRequest.setFastestInterval(1000L);
        locationRequest.setSmallestDisplacement(interval);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, locationListener);
    } else {
        LocationRequest locationRequest = new LocationRequest();
        locationRequest.setInterval(1000L);
        locationRequest.setFastestInterval(1000L);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, locationListener);
    }
}
Example 98
Project: DroidPlanner-Tower-master  File: GoogleMapFragment.java View source code
@Override
public void doRun() {
    final LocationRequest locationReq = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setFastestInterval(USER_LOCATION_UPDATE_FASTEST_INTERVAL).setInterval(USER_LOCATION_UPDATE_INTERVAL).setSmallestDisplacement(USER_LOCATION_UPDATE_MIN_DISPLACEMENT);
    final GoogleApiClient googleApiClient = getGoogleApiClient();
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationReq);
    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

        @Override
        public void onResult(LocationSettingsResult callback) {
            final Status status = callback.getStatus();
            switch(status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    // All location settings are satisfied. The client can initialize location
                    // requests here.
                    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationReq, GoogleMapFragment.this);
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    // a dialog.
                    try {
                        // Show the dialog by calling startResolutionForResult(),
                        // and check the result in onActivityResult().
                        status.startResolutionForResult(getActivity(), REQUEST_CHECK_SETTINGS);
                    } catch (IntentSender.SendIntentException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    // Location settings are not satisfied. However, we have no way to fix the
                    // settings so we won't show the dialog.
                    Log.w(TAG, "Unable to get accurate user location.");
                    Toast.makeText(getActivity(), "Unable to get accurate location. Please update your " + "location settings!", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    });
}
Example 99
Project: GeoPost-master  File: MainActivity.java View source code
/**
	 * Called when the location client is connected. It sets up the location
	 * request settings, zooms into the current location, and draws the
	 * unlocking radius around the user's current location.
	 * 
	 * @param Bundle of data provided to clients by Google Play services. 
	 * 		  May be null if no content is provided by the service.
	 */
@Override
public void onConnected(Bundle arg0) {
    Log.d("DEBUG", "onConnected begin");
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the update interval to 5 seconds
    locationRequest.setInterval(UPDATE_INTERVAL * SEC_TO_MILLIS);
    // Set the fastest update interval to 1 second
    locationRequest.setFastestInterval(FASTEST_UPDATE * SEC_TO_MILLIS);
    // Make the app open up to your current location
    Location currentLocation = locationClient.getLastLocation();
    if (currentLocation != null) {
        LatLng myLatLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLatLng, INIT_ZOOM));
        if (unlockedRadius != null) {
            unlockedRadius.remove();
        }
        drawCircle(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()));
    } else {
        DialogFragment newFragment = new EnableLocationFragment();
        newFragment.show(getSupportFragmentManager(), "enableLocation");
    }
    Log.d("DEBUG", "onConnected end");
    startPeriodicUpdates();
}
Example 100
Project: otm-android-master  File: MainMapFragment.java View source code
/**
     * ***************************************************************
     * Overrides for the GoogleApiClient.ConnectionCallbacks interface
     * ***************************************************************
     */
@Override
public void onConnected(Bundle bundle) {
    // 5 seconds
    int WAIT_DURATION = 5000;
    LocationRequest request = LocationRequest.create().setNumUpdates(1).setExpirationDuration(WAIT_DURATION).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, request,  loc -> {
        if (mLocationDeferred.isPending()) {
            mLocationDeferred.resolve(loc);
        }
    });
    new Handler().postDelayed(() -> {
        if (mLocationDeferred.isPending()) {
            mLocationDeferred.reject(new TimeoutException("Location request timed out"));
        }
    }, WAIT_DURATION);
}
Example 101
Project: Realtime-Port-Authority-master  File: BusMapFragment.java View source code
/**
     * Centers the map if the {@link android.Manifest.permission_group#LOCATION} permissions are granted.
     * If they are not and has never been asked, check to see if location settings should be granted.
     * If they are granted, center the location either on your last known location or on the first
     * location update. Otherwise, don't run it.
     */
private void centerMapWithPermissions() {
    if (mMap == null || getContext() == null)
        return;
    // first check if the permission is granted... if not, show why you should if user didn't say
    if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, CENTER_MAP_LOCATION_CODE);
        return;
    }
    Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    // use the last location if found and if less than 1 hour
    if (lastLocation != null && isInPittsburgh(lastLocation) && System.currentTimeMillis() - lastLocation.getTime() < 3600000) {
        Timber.i("Using last location to center map.");
        LatLng latLng = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomStopVisibility));
    } else {
        // request one location update
        Timber.i("Creating 1 location request to center map on you.");
        LocationRequest gLocationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(1000).setExpirationTime(// set expiration 10 seconds
        10000).setNumUpdates(// only do one update. needs above call for expiration
        1);
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, gLocationRequest, this);
    }
    enableGoogleMapLocation();
}