问题
I am trying to make a simple Android application to count steps. When I run the application the else is called in the onResume method meaning it did not find the sensor. I am testing on a 2016 Samsung J3 running Api 22. I am wondering is the problem in my code or is it that the phone does not have the sensor. If it is the phone is there a workaround for it?
public class MainActivity extends AppCompatActivity implements SensorEventListener
{
private TextView counterTextView;
private SensorManager sensorManager;
private boolean isWalking;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counterTextView = findViewById(R.id.counterTextView);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
@Override
protected void onResume()
{
super.onResume();
isWalking = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if(countSensor != null)
{
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
}
else
{
counterTextView.setText("WARNING SENSOR NOT FOUND");
}
}
@Override
protected void onPause()
{
super.onPause();
isWalking = false;
}
@Override
public void onSensorChanged(SensorEvent event)
{
if(isWalking)
{
counterTextView.setText(String.valueOf(event.values[0]));
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
}
回答1:
For anyone in the same situation as me, it was the device I was using. If you want to work with all devices you can use the accelerometer.
来源:https://stackoverflow.com/questions/53958841/android-step-counter