基本知識
加速度センサーは、重力の影響を受ける x、y、z 軸の加速度値を返すことができます。
電話機をテーブルの上に平らに置きます。x、y、z 軸はデフォルトで 9.81、電話機の下向きの Z 軸は -9.81 です。
携帯電話を左に傾けると x 軸が正となり、右に傾けると x 軸が負になります。
携帯電話を上に傾けると y 軸が負になり、下に傾けると x 軸が正になります。
以下の図はxyz軸の値を上から下に順番に示したもので、携帯電話が右に傾いている状態であることがわかります。
実用
新しいプロジェクトを作成し、レイアウト ファイル activity_main.xml を変更します。コードは次のとおりです。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textViewx"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textViewy"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textViewz"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity コードを次のように変更します。
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager sm;
TextView textViewx;
TextView textViewy;
TextView textViewz;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewx = (TextView) findViewById(R.id.textViewx);
textViewy = (TextView) findViewById(R.id.textViewy);
textViewz = (TextView) findViewById(R.id.textViewz);
// 获取传感器管理器
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
// 调用方法获取需要的传感器
Sensor mSensorOrientation = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// 注册监听器
//SENSOR_DELAY_FASTEST最灵敏
//SENSOR_DELAY_GAME 游戏的时候,不过一般用这个就够了
//SENSOR_DELAY_NORMAL 比较慢。
//SENSOR_DELAY_UI 最慢的
sm.registerListener(this, mSensorOrientation, android.hardware.SensorManager.SENSOR_DELAY_UI);
}
// 该方法在传感器的值发生变化的时候调用
@Override
public void onSensorChanged(SensorEvent event) {
float X = event.values[0];
float Y = event.values[1];
float Z = event.values[2];
textViewx.setText(X+"");
textViewy.setText(Y+"");
textViewz.setText(Z+"");
}
// 当传感器的进度发生改变时回调,sensor是传感器对象,accuracy是传感器新的精度
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// 在activity变为不可见的时候,传感器依然在工作,这样很耗电,所以我们根据需求可以在onPause方法里面停掉传感器的工作
@Override
public void onPause() {
// 取消监听器的注册
sm. unregisterListener(this);
super.onPause();
}
}
携帯電話で実行すると、3 つの値の小数部分が変化し続けることがわかりますが、これは正常です。