Back to project page steppy.
The source code is released under:
GNU General Public License
If you think the Android project steppy listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package net.daverix.steppy; //from w w w .j a v a2s . c o m import android.app.Service; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Binder; import android.os.IBinder; import android.util.Log; import java.util.HashSet; import java.util.Set; public class SteppyService extends Service implements SteppyInteractor { private static final int MAX_BATCHED_DELAY = 10000000; private final Set<OnStepsCountedListener> mListeners = new HashSet<>(); private final IBinder mBinder = new SteppyBinder(); private SensorManager mSensorManager; private long mStepsCounted; private boolean mIsListening; @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public void onCreate() { super.onCreate(); mIsListening = false; mStepsCounted = 0; mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public void startListening() { if(mIsListening) return; final Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER); boolean batchMode = mSensorManager.registerListener(mSensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL, MAX_BATCHED_DELAY); if(!batchMode) { Log.e("SteppyService", "Batch mode not possible"); } mIsListening = true; } private SensorEventListener mSensorEventListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { mStepsCounted = (int) event.values[0]; notifyStepsChanged(); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; private void notifyStepsChanged() { synchronized (mListeners) { for(OnStepsCountedListener listener : mListeners) { listener.onStepsCounted(this); } } } @Override public void stopListener() { mIsListening = false; mSensorManager.unregisterListener(mSensorEventListener); } @Override public void registerOnStepsCountedListener(OnStepsCountedListener listener) { if(listener == null) throw new IllegalArgumentException("listener is null"); synchronized (mListeners) { mListeners.add(listener); } } @Override public void unregisterOnStepsCountedListener(OnStepsCountedListener listener) { if(listener == null) throw new IllegalArgumentException("listener is null"); synchronized (mListeners) { mListeners.remove(listener); } } @Override public long getCountedSteps() { return mStepsCounted; } @Override public boolean isListening() { return mIsListening; } public class SteppyBinder extends Binder { public SteppyInteractor getSteppyInteractor() { return SteppyService.this; } } }