Skip to content

Instantly share code, notes, and snippets.

@groupsky
Last active April 20, 2016 09:28
Show Gist options
  • Save groupsky/8772ba063957e7ace78641909b8c6c35 to your computer and use it in GitHub Desktop.
Save groupsky/8772ba063957e7ace78641909b8c6c35 to your computer and use it in GitHub Desktop.
BearingLocationSource
/*
Copyright 2016 Geno Roupsky
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.hardware.GeomagneticField;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.LocationSource;
public class BearingLocationSource implements LocationSource, LocationListener, SensorEventListener, GoogleApiClient.ConnectionCallbacks, LifecycleFragment.OnStartListener, LifecycleFragment.OnStopListener {
private static final String TAG = "BearingLocationSource";
private static final String LIFECYCLE_FRAGMENT_TAG = "BearingLocationSource.LifecycleFragment";
private final GoogleApiClient mGoogleApiClient;
private final LocationRequest mLocationRequest;
private final SensorManager mSensorManager;
private final Sensor mAccelerometer;
private final Sensor mMagneticField;
private final float[] mValuesAccelerometer;
private final float[] mValuesMagneticField;
private final float[] mMatrixR;
private final float[] mMatrixI;
private final float[] mMatrixValues;
private final AverageAngle mAzimuthRadians;
private OnLocationChangedListener mListener;
private Location mLocation;
private boolean mConnected;
private boolean mActive;
private float mAzimuth = Float.NaN;
private float mBearing = Float.NaN;
private boolean mHasAccelerometerValues = false;
private boolean mHasMagneticValues = false;
public BearingLocationSource(Activity activity, int smoothing) {
Fragment fragment = activity.getFragmentManager().findFragmentByTag(LIFECYCLE_FRAGMENT_TAG);
fragment = fragment != null && !fragment.isRemoving() ? fragment : null;
if (fragment == null) {
fragment = new LifecycleFragment();
activity.getFragmentManager().beginTransaction().add(fragment, LIFECYCLE_FRAGMENT_TAG).commitAllowingStateLoss();
activity.getFragmentManager().executePendingTransactions();
}
((LifecycleFragment)fragment).setListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(activity)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.build();
mGoogleApiClient.connect();
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000);
mSensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mMagneticField = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mValuesAccelerometer = new float[3];
mValuesMagneticField = new float[3];
mMatrixR = new float[9];
mMatrixI = new float[9];
mMatrixValues = new float[3];
mAzimuthRadians = new AverageAngle(smoothing);
}
@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
Log.d(TAG, "activating location");
mListener = onLocationChangedListener;
mActive = true;
if (mConnected) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
if (mAccelerometer != null && mMagneticField != null) {
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, mMagneticField, SensorManager.SENSOR_DELAY_UI);
}
}
@Override
public void deactivate() {
Log.d(TAG, "deactivation location");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mSensorManager.unregisterListener(this);
mListener = null;
mActive = false;
}
private void notifyListener() {
if (mListener != null && mLocation != null) {
if (mBearing != Float.NaN) {
mLocation.setBearing(mBearing);
}
//The listener will be the maps:
mListener.onLocationChanged(mLocation);
}
}
@Override
public void onLocationChanged(Location location) {
mLocation = location;
updateBearing();
notifyListener();
}
@Override
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
System.arraycopy(event.values, 0, mValuesAccelerometer, 0, 3);
mHasAccelerometerValues = true;
break;
case Sensor.TYPE_MAGNETIC_FIELD:
System.arraycopy(event.values, 0, mValuesMagneticField, 0, 3);
mHasMagneticValues = true;
break;
}
if (mHasAccelerometerValues && mHasMagneticValues) {
if (SensorManager.getRotationMatrix(mMatrixR, mMatrixI, mValuesAccelerometer, mValuesMagneticField)) {
SensorManager.getOrientation(mMatrixR, mMatrixValues);
mAzimuthRadians.putValue(mMatrixValues[0]);
mAzimuth = (float) Math.toDegrees(mAzimuthRadians.getAverage());
updateBearing();
}
}
}
private void updateBearing()
{
if (!Float.isNaN(this.mAzimuth)) {
if(this.mLocation == null) {
Log.w(TAG, "Location is NULL bearing is not true north!");
mBearing = mAzimuth;
} else {
mBearing = getBearingForLocation(this.mLocation);
}
notifyListener();
}
}
private float getBearingForLocation(Location location) {
return mAzimuth + getGeomagneticField(location).getDeclination();
}
private GeomagneticField getGeomagneticField(Location location) {
GeomagneticField geomagneticField = new GeomagneticField(
(float)location.getLatitude(),
(float)location.getLongitude(),
(float)location.getAltitude(),
System.currentTimeMillis());
return geomagneticField;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onConnected(Bundle bundle) {
mConnected = true;
if (mActive) {
activate(mListener);
}
}
@Override
public void onConnectionSuspended(int i) {
mConnected = false;
}
@Override
public void onStart() {
if (mActive && mConnected) {
activate(mListener);
}
}
@Override
public void onStop() {
final OnLocationChangedListener listener = mListener;
deactivate();
mListener = listener;
mActive = true;
}
}
/*
Copyright 2016 Geno Roupsky
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import android.app.Fragment;
public class LifecycleFragment extends Fragment {
public interface LifecycleListener {
}
public interface OnStartListener extends LifecycleListener {
void onStart();
}
public interface OnStopListener extends LifecycleListener {
void onStop();
}
LifecycleListener listener;
public void setListener(LifecycleListener listener) {
this.listener = listener;
}
@Override
public void onStart() {
super.onStart();
if (listener instanceof OnStartListener) {
((OnStartListener) listener).onStart();
}
}
@Override
public void onStop() {
if (listener instanceof OnStopListener) {
((OnStopListener) listener).onStop();
}
super.onStop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment