androidセンサ取得方向まとめ
2.2で画面の方向を反転横に設定できます:setRequestedOrientation(8);システムはこのパラメータの設定を公開していないので、ソースコードにはSCREEN_が定義されています.ORIENTATION_REVERSE_LANDSCAPEというパラメータですが、画面の方向を反転した横画面である右横画面に固定することはできません.画面方向を右横に設定する場合は、activityをandroid:theme="@android:style/theme.Translucent"に設定する必要があります.そうしないとsetRequestedOrientation(8)が設定されていても.右の横画面にも表示されません.
回転角度によって画面の方向を取得できますが、2.1の場合は右横線に設定することはできません.以下にソースコードから切り取ったセンサーによって角度によって画面の方向を取得することを記録します.
センサーの監視:
方向の変化は絶えず変化するので、回転角度の処理で方向を得るにはhandlerが必要です.
回転角度によって画面の方向を取得できますが、2.1の場合は右横線に設定することはできません.以下にソースコードから切り取ったセンサーによって角度によって画面の方向を取得することを記録します.
センサーの監視:
class SubSensorListener implements SensorEventListener {
private static final int _DATA_X = 0;
private static final int _DATA_Y = 1;
private static final int _DATA_Z = 2;
public static final int ORIENTATION_UNKNOWN = -1;
private Handler handler;
public SubSensorListener (Handler handler) {
this.handler = handler;
}
public void onAccuracyChanged(Sensor arg0, int arg1) {}
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
int orientation = ORIENTATION_UNKNOWN;
float X = -values[_DATA_X];
float Y = -values[_DATA_Y];
float Z = -values[_DATA_Z];
float magnitude = X * X + Y * Y;
// Don't trust the angle if the magnitude is small compared to the y value
if (magnitude * 4 >= Z * Z) {
float OneEightyOverPi = 57.29577957855f;
float angle = (float) Math.atan2(-Y, X) * OneEightyOverPi;
orientation = 90 - (int) Math.round(angle);
// normalize to 0 - 359 range
while (orientation >= 360) {
orientation -= 360;
}
while (orientation < 0) {
orientation += 360;
}
}
if (handler != null) {
handler.obtainMessage(123, orientation, 0).sendToTarget();
}
}
方向の変化は絶えず変化するので、回転角度の処理で方向を得るにはhandlerが必要です.
@Override
public void handleMessage(Message msg) {
if (msg.what == 123) {
int orientation = msg.arg1;
if (orientation > 45 && orientation < 135) {
// SCREEN_ORIENTATION_REVERSE_LANDSCAPE
activity.setRequestedOrientation(8);
} else if (orientation > 135 && orientation < 225) {
// SCREEN_ORIENTATION_REVERSE_PORTRAIT
activity.setRequestedOrientation(9);
} else if (orientation > 225 && orientation < 315) {
// SCREEN_ORIENTATION_LANDSCAPE
activity.setRequestedOrientation(0);
} else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) {
// SCREEN_ORIENTATION_PORTRAIT
activity.setRequestedOrientation(1);
}
}
}