Android中怎样使用计步器传感器 "TYPE_STEP_DETECTOR"

本文档介绍了从Android 4.4版本开始如何利用Sensor监听器`TYPE_STEP_DETECTOR`来集成计步器功能,详细步骤包括初始化Sensor和创建SensorListener。
摘要由CSDN通过智能技术生成
在Android 4.4以后的版本已经可以直接支持计步器sensor,参考下面的文章。
http://developer.android.com/about/versions/android-4.4.html#UserInput
http://motzcod.es/post/82515321689/part-1-my-stepcounter-android-step-sensors
http://baroqueworksdev.blogspot.com/2013/12/how-to-use-sensor-of-typestepdetector.html


Initialize Sensor
We have to get a Sensor's Object from SensorManager.
Set the type "Sensor.TYPE_STEP_DETECTOR".
public class StepCounterActivity extends Activity {
    private SensorManager mSensorManager;
    private Sensor mStepSensor;
    private TextView mTextView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        mTextView = (TextView) findViewById(R.id.text_step);
 
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mStepSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
 
    }
 
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(mSensorEventListener, mStepSensor,
                SensorManager.SENSOR_DELAY_NORMAL);
    }
 
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(mSensorEventListener);
    }

Create a SensorListener
We can get a trigger from onSensorChanged.
private SensorEventListener mSensorEventListener = new SensorEventListener() {
    private int mStep;
 
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
 
    }
 
    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.values[0] == 1.0f) {
            mStep++;
        }
        mTextView.setText(Integer.toString(mStep));
    }
};



评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值