亲测在小米.魅族.华为上可用,该app采用后台service计歩服务,所以只要app不被手机杀死在后台也是可以正常计歩的。上图:
1.需要在AndroidManifest.xml中添加权限
<!--计歩需要的权限-->
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-feature android:name="android.hardware.sensor.accelerometer" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-feature
android:name="android.hardware.sensor.stepcounter"
android:required="true" />
<uses-feature
android:name="android.hardware.sensor.stepdetector"
android:required="true" />
2.检测手机是否支持计歩
@TargetApi(Build.VERSION_CODES.KITKAT)
public static boolean isSupportStepCountSensor(Context context) {
// 获取传感器管理器的实例
SensorManager sensorManager = (SensorManager) context
.getSystemService(context.SENSOR_SERVICE);
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
Sensor detectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
return countSensor != null || detectorSensor != null;
}
3.功能使用
private boolean isBind = false;
private Messenger mGetReplyMessenger = new Messenger(new Handler(this));
private Messenger messenger;
private void setupService() {
Intent intent = new Intent(this, StepService.class);
isBind = bindService(intent, conn, Context.BIND_AUTO_CREATE);
startService(intent);
}
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case Constant.MSG_FROM_SERVER:
cc.setCurrentCount(10000, msg.getData().getInt("step"));
break;
}
return false;
}
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
try {
messenger = new Messenger(service);
Message msg = Message.obtain(null, Constant.MSG_FROM_CLIENT);
msg.replyTo = mGetReplyMessenger;
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
GitHub地址:https://github.com/linglongxin24/DylanStepCount
您可能感兴趣的文章:android实现计步功能初探Android计步模块实例代码(类似微信运动)Android实现简易计步器功能隔天步数清零查看历史运动纪录Android计步功能的实现代码Android实现计步进度的环形ProgressAndroid实现计步传感器功能