android - 计步器是否默认在后台运行?

标签 android android-sensors

我创建了一个 Activity 并从 Android 实现了基本计步器。

所有代码都在 Activity 中,我没有创建任何服务等。

所以问题是,即使我没有为它创建任何代码,该应用程序是否会在后台运行?

我做了一些测试,看起来确实如此,但我不能 100% 确定情况是否如此。

这是我的代码:

    private TextView count;

    // is inside my onCreate
    count = (TextView) findViewById(R.id.mTextField);
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);


    @Override
    protected void onResume() {
        super.onResume();
        activityRunning = true;
        Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        if(countSensor != null) {
            sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
        } else {
            Toast.makeText(this, "Count sensor not available!", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        activityRunning = false;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(activityRunning) {
            count.setText(String.valueOf(event.values[0]));
        }
    }

我知道 onPause() 方法设置了 activityRunning = false,但是我仍然可以关闭/锁定屏幕,四处走动并获得步骤。

我觉得这有点令人困惑。

最佳答案

您需要在onPause期间unrigester您的传感器

   @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }

此外,如果您取消注册,您确实需要使用您的boolean activityRunning

关于android - 计步器是否默认在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39720893/

相关文章:

android - 如何将onClick,onLongClick和onTouch实现到一个 View

android - 如何将图像从安卓设备上传到谷歌云存储?

android - 如何使用 DataBinding Framework MVVM 在 EditText 上设置错误

android - Android 中的 "gravity"和 "acceleration"传感器有什么区别?

android - 是否可以在 onCreate 方法中获取 Android 加速度计值?

android - Android Logcat 中仅显示橙色消息

java - 使 Seekbar 遵循 MPAndroidChart X 值

android - getOrientationMatrix 导致应用程序崩溃

android - 多选手势,如 Google 相册应用

android - 使用 getOrientation() 函数获取设备角度