[英]How to Implement Step Counter in Android Studio If Pedometer Sensor Not Available
我有一部三星手機,它顯然沒有計步器(計步器),因為當我使用 TYPE_STEP_COUNTER 時,它說沒有。 所以在網上搜索之后,我發現了一個使用加速度計檢查器的實現。 但問題是實現在檢測步驟上不是很准確。 我試圖校准這些數字,但仍然不是很可靠。 它將添加 x、y、z 軸的平方並計算根以獲得步長的大小。 所以我的問題是有沒有人這樣做過,以及他們是如何以一種很好的實施方式做到的。 謝謝這是我正在使用的代碼
public class StatsFragment extends Fragment implements SensorEventListener {
private static final String LOG_TAG = "STATS";
private TextView stepCountTextView;
private Button clearCounterButton;
private Sensor stepSensor;
private Integer stepCount = 0;
private double MagnitudePrevious = 0;
private SensorManager sensorManager;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stats, container, false);
stepCountTextView = view.findViewById(R.id.step_counter);
clearCounterButton = view.findViewById(R.id.clear_button);
sensorManager = (SensorManager) getActivity().getSystemService(getActivity().SENSOR_SERVICE);
stepSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
clearCounterButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
stepCount = 0;
stepCountTextView.setText(stepCount.toString());
}
});
return view;
}
@Override
public void onResume() {
super.onResume();
if(stepSensor != null) {
sensorManager.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI);
}
else {
Toast.makeText(getActivity(), "Sensor not available!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onPause() {
super.onPause();
//unregister sensor
sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent != null) {
float x_acceleration = sensorEvent.values[0];
float y_acceleration = sensorEvent.values[1];
float z_acceleration = sensorEvent.values[2];
double Magnitude = Math.sqrt(x_acceleration*x_acceleration + y_acceleration*y_acceleration
+ z_acceleration*z_acceleration);
double MagnitudeDelta = Magnitude - MagnitudePrevious;
MagnitudePrevious = Magnitude;
if (sensorEvent.values[0] > 6){
stepCount++;
}
stepCountTextView.setText(stepCount.toString());
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}
在 Android 10 上,您需要請求權限才能訪問步進傳感器。 將下面的添加代碼添加到Manifest.xml
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>
並在onCreateView方法中添加以下代碼:
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_DENIED){
//ask for permission
requestPermissions(new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, 0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.