com.google.android.gms.location.LocationClient Java Examples

The following examples show how to use com.google.android.gms.location.LocationClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MyTracksLocationManager.java    From mytracks with Apache License 2.0 6 votes vote down vote up
public MyTracksLocationManager(Context context, Looper looper, boolean enableLocaitonClient) {
  this.context = context;
  this.handler = new Handler(looper);

  if (enableLocaitonClient) {
    locationClient = new LocationClient(context, connectionCallbacks, onConnectionFailedListener);
    locationClient.connect();
  } else {
    locationClient = null;
  }

  locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
  contentResolver = context.getContentResolver();
  observer = new GoogleSettingsObserver(handler);

  isAllowed = GoogleLocationUtils.isAllowed(context);

  contentResolver.registerContentObserver(
      GoogleLocationUtils.USE_LOCATION_FOR_SERVICES_URI, false, observer);
}
 
Example #2
Source File: MainActivity.java    From AndroidWearable-Samples with Apache License 2.0 6 votes vote down vote up
/**
 * Start a request for geofence monitoring by calling LocationClient.connect().
 */
public void addGeofences() {
    // Start a request to add geofences.
    mRequestType = REQUEST_TYPE.ADD;
    // Test for Google Play services after setting the request type.
    if (!isGooglePlayServicesAvailable()) {
        Log.e(TAG, "Unable to add geofences - Google Play services unavailable.");
        return;
    }
    // Create a new location client object. Since this activity class implements
    // ConnectionCallbacks and OnConnectionFailedListener, it can be used as the listener for
    // both parameters.
    mLocationClient = new LocationClient(this, this, this);
    // If a request is not already underway.
    if (!mInProgress) {
        // Indicate that a request is underway.
        mInProgress = true;
        // Request a connection from the client to Location Services.
        mLocationClient.connect();
    // A request is already underway, so disconnect the client and retry the request.
    } else {
        mLocationClient.disconnect();
        mLocationClient.connect();
    }
}
 
Example #3
Source File: GeofencingService.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
@Override
protected void onHandleIntent( Intent intent ) {
	NotificationCompat.Builder builder = new NotificationCompat.Builder( this );
	builder.setSmallIcon( R.drawable.ic_launcher );
	builder.setDefaults( Notification.DEFAULT_ALL );
	builder.setOngoing( true );

	int transitionType = LocationClient.getGeofenceTransition( intent );
	if( transitionType == Geofence.GEOFENCE_TRANSITION_ENTER ) {
		builder.setContentTitle( "Geofence Transition" );
		builder.setContentText( "Entering Geofence" );
		mNotificationManager.notify( 1, builder.build() );
	}
	else if( transitionType == Geofence.GEOFENCE_TRANSITION_EXIT ) {
		builder.setContentTitle( "Geofence Transition" );
		builder.setContentText( "Exiting Geofence" );
		mNotificationManager.notify( 1, builder.build() );
	}
}
 
Example #4
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);

	verifyPlayServices();

	mLocationClient = new LocationClient( this, this, this );
	mIntent = new Intent( this, GeofencingService.class );
	mPendingIntent = PendingIntent.getService( this, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT );

	mToggleButton = (ToggleButton) findViewById( R.id.geofencing_button );
	mToggleButton.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged( CompoundButton compoundButton, boolean b ) {
			if( b ) {
				startGeofence();
			} else {
				stopGeofence();
			}
		}
	});
}
 
Example #5
Source File: LocationGetLocationActivity.java    From coursera-android with MIT License 5 votes vote down vote up
@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 #6
Source File: LocationController.java    From vocefiscal-android with Apache License 2.0 5 votes vote down vote up
/**
 * @param context
 */
public LocationController(LocationClient mLocationClient, GoogleMap map) 
{
	super();

	this.mLocationClient = mLocationClient;
	this.map = map;

	initLocationController();
}
 
Example #7
Source File: GooglePlayClientWrapper.java    From barterli_android with Apache License 2.0 5 votes vote down vote up
public GooglePlayClientWrapper(final AbstractBarterLiActivity activity, final LocationListener locationListener) {
    mActivity = activity;
    mLocationClient = new LocationClient(mActivity, this, this);
    mLocationListener = locationListener;
    mLocationRequest = LocationRequest
                    .create()
                    .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
                    .setInterval(UPDATE_INTERVAL)
                    .setFastestInterval(FASTEST_INTERVAL);
}
 
Example #8
Source File: GeofenceTransitionsIntentService.java    From AndroidWearable-Samples with Apache License 2.0 4 votes vote down vote up
/**
 * Handles incoming intents.
 * @param intent The Intent sent by Location Services. This Intent is provided to Location
 *               Services (inside a PendingIntent) when addGeofences() is called.
 */
@Override
protected void onHandleIntent(Intent intent) {
    // First check for errors.
    if (LocationClient.hasError(intent)) {
        int errorCode = LocationClient.getErrorCode(intent);
        Log.e(TAG, "Location Services error: " + errorCode);
    } else {
        // Get the type of geofence transition (i.e. enter or exit in this sample).
        int transitionType = LocationClient.getGeofenceTransition(intent);
        // Create a DataItem when a user enters one of the geofences. The wearable app will
        // receive this and create a notification to prompt him/her to check in.
        if (Geofence.GEOFENCE_TRANSITION_ENTER == transitionType) {
            // Connect to the Google Api service in preparation for sending a DataItem.
            mGoogleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
            // Get the geofence id triggered. Note that only one geofence can be triggered at a
            // time in this example, but in some cases you might want to consider the full list
            // of geofences triggered.
            String triggeredGeofenceId = LocationClient.getTriggeringGeofences(intent).get(0)
                    .getRequestId();
            // Create a DataItem with this geofence's id. The wearable can use this to create
            // a notification.
            final PutDataMapRequest putDataMapRequest =
                    PutDataMapRequest.create(GEOFENCE_DATA_ITEM_PATH);
            putDataMapRequest.getDataMap().putString(KEY_GEOFENCE_ID, triggeredGeofenceId);
            if (mGoogleApiClient.isConnected()) {
                Wearable.DataApi.putDataItem(
                    mGoogleApiClient, putDataMapRequest.asPutDataRequest()).await();
            } else {
                Log.e(TAG, "Failed to send data item: " + putDataMapRequest
                         + " - Client disconnected from Google Play Services");
            }
            mGoogleApiClient.disconnect();
        } else if (Geofence.GEOFENCE_TRANSITION_EXIT == transitionType) {
            // Delete the data item when leaving a geofence region.
            mGoogleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
            Wearable.DataApi.deleteDataItems(mGoogleApiClient, GEOFENCE_DATA_ITEM_URI).await();
            mGoogleApiClient.disconnect();
        }
    }
}
 
Example #9
Source File: PTRMapFragment.java    From AndroidDemoProjects with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	mLocationClient = new LocationClient( getActivity(), this, this );
}
 
Example #10
Source File: LocationController.java    From slidingdebugmenu with Apache License 2.0 4 votes vote down vote up
private LocationController(Context context) {
    if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS)
        mLocationClient = new LocationClient(context, this, this);
    else EventBus.getDefault().post(new LocationEvent(null));
}
 
Example #11
Source File: BackgroundService.java    From GeoLog with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
	Debug.log("Thread init");
				
	databaseHelper = Database.Helper.getInstance(context);
	
	alarm = (AlarmManager)context.getSystemService(ALARM_SERVICE);
	{
		Intent i = new Intent(context.getApplicationContext(), BackgroundService.class);
		i.putExtra(EXTRA_ALARM_CALLBACK, 1);
		alarmCallback =	PendingIntent.getService(BackgroundService.this, 0, i, 0);
	}

	Looper.prepare();
	handler = new Handler();
			
	Debug.log("Registering for updates");			
	prefs = PreferenceManager.getDefaultSharedPreferences(context);					
	long id = prefs.getLong(SettingsFragment.PREF_CURRENT_PROFILE, 0);
	if (id > 0) currentProfile = Database.Profile.getById(databaseHelper, id, null);
	if (currentProfile == null) currentProfile = Database.Profile.getOffProfile(databaseHelper);
	metric = !prefs.getString(SettingsFragment.PREF_UNITS, SettingsFragment.PREF_UNITS_DEFAULT).equals(SettingsFragment.VALUE_UNITS_IMPERIAL);
	prefs.registerOnSharedPreferenceChangeListener(preferencesUpdated);
	LocalBroadcastManager.getInstance(context).registerReceiver(databaseUpdated, new IntentFilter(Database.Helper.NOTIFY_BROADCAST));
	
	Debug.log("Registering for power levels");
	context.registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
	
	Debug.log("Connecting ActivityRecognitionClient");
	activityIntent = PendingIntent.getService(context, 1, new Intent(context, BackgroundService.class), 0);
	activityClient = new ActivityRecognitionClient(context, activityConnectionCallbacks, activityConnectionFailed);
	activityClient.connect();

	Debug.log("Connecting LocationClient");
	locationClient = new LocationClient(context, locationConnectionCallbacks, locationConnectionFailed);
	locationClient.connect();
	
	Debug.log("Entering loop");
	handler.post(new Runnable() {				
		@Override
		public void run() {
			updateListeners(FLAG_SETUP);
		}
	});						
	Looper.loop();			
	Debug.log("Exiting loop");
	
	context.unregisterReceiver(batteryReceiver);
	
	LocalBroadcastManager.getInstance(context).unregisterReceiver(databaseUpdated);
	prefs.unregisterOnSharedPreferenceChangeListener(preferencesUpdated);			
	
	if (activityConnected) {
		activityClient.removeActivityUpdates(activityIntent);
		activityClient.disconnect();
	}
	if (locationConnected) {
		locationClient.removeLocationUpdates(locationListener);
		locationClient.disconnect();
	}			
}