如果用户翻过手机,我想通过停止我的文字到语音阅读来做出反应。对我的应用程序来说这将是一个很好的功能,但我怎么能检测到这个动作?我对运动传感器并不熟悉,我无法在任何地方找到这种特定的运动监听器,主要是屏幕方向。谢谢你的帮助!
答案 0 :(得分:1)
此示例活动演示了如何使用设备的重力传感器来检测设备何时翻转。在方法onSensorChanged()
中,术语factor
决定了“翻身”必须完成的程度。典型范围可能是0.7到0.95。
Android API 9中添加了对重力传感器的支持。并非所有设备都有重力传感器。
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private static final String TAG = "Demo";
private SensorManager mSensorManager;
private Sensor mGravitySensor;
private boolean mFacingDown;
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// nothing
}
@Override
public void onSensorChanged(SensorEvent event) {
final float factor = 0.95F;
if (event.sensor == mGravitySensor) {
boolean nowDown = event.values[2] < -SensorManager.GRAVITY_EARTH * factor;
if (nowDown != mFacingDown) {
if (nowDown) {
Log.i(TAG, "DOWN");
} else {
Log.i(TAG, "UP");
}
mFacingDown = nowDown;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mGravitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
if (mGravitySensor == null) {
Log.w(TAG, "Device has no gravity sensor");
}
}
@Override
protected void onResume() {
super.onResume();
if (mGravitySensor != null) {
mSensorManager.registerListener(this, mGravitySensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
}