Android Fragments Android Studio中的步数计数器不计算步数

pkln4tw6  于 2023-02-13  发布在  Android
关注(0)|答案(1)|浏览(147)

我尝试在Android Studio中开发的应用遇到问题。我尝试在Fragment中使用STEP_COUNTER传感器开发计步器。我决定在TextView('mStepsSinceReboot ')中显示结果,但它一直为空。您知道如何让它工作吗?
一个假设是我应该使用一个服务,但在网上我只找到了不需要它的实现。
先谢谢你的回答。这是我的碎片的代码。

public class StepFragment extends Fragment implements SensorEventListener {

    private SensorManager mSensorManager;
    private Sensor mStepCounter;
    private boolean isSensorPresent;
    private TextView mStepsSinceReboot;

    public StepFragment() {
        // Required empty public constructor
    }

    public static StepFragment newInstance(String param1, String param2) {
        StepFragment fragment = new StepFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View v=inflater.inflate(R.layout.fragment_step, container, false);

        mStepsSinceReboot=v.findViewById(R.id.stepssincereboot);

        mSensorManager=(SensorManager) this.getActivity().getSystemService(getContext().SENSOR_SERVICE);
        if (mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)!=null){
            mStepCounter=mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);

            isSensorPresent=true;
        }
        else{
            isSensorPresent=false;
        }
        return v;
    }

        @Override
        public void onSensorChanged(SensorEvent event) {
            mStepsSinceReboot.setText(("Steps since reboot: "+String.valueOf(event.values[0])));
            Log.d("Passi", String.valueOf(mStepsSinceReboot));
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }

    @Override
    public void onResume(){
        super.onResume();
        if(isSensorPresent){
            mSensorManager.registerListener(this,mStepCounter,SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    @Override
    public void onPause(){
        super.onPause();
        if(isSensorPresent){
            mSensorManager.unregisterListener(this);
        }
    }

    @Override
        public void onDestroy(){
            super.onDestroy();

            mSensorManager=null;
            mStepCounter=null;
        }

}
zujrkrfu

zujrkrfu1#

你在清单文件中添加了权限吗?

<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>

相关问题