OrientationEventListenerを使った端末の回転角度取得|Android開発

OrientationEventListenerを使って端末の向き(回転角度)を取得する方法です。
画面(Activity)の向きに関係なく取得可能です。つまり、AndroidManifest.xmlで向きを固定しても通知されます。

変数定義

private int mDeviceDegree;
private OrientationEventListener mOrientationEventListener;

生成

Activity.onCreate()などで生成します。

mOrientationEventListener = new OrientationEventListener(this) {

    @Override
    public void onOrientationChanged(int orientation) {
        mDeviceDegree = ((orientation + 45) / 90) * 90;
    }
};

onOrientationChangedのパラメータorientationには0~359の角度が渡されます。
ここでは取得したいデバイスの向きを4パターンとして、90度単位に丸めた角度をmDeviceDegreeに格納しています。

変更通知の開始

Activity.onResume()などで開始します。

mOrientationEventListener.enable();

変更通知の停止

Activity.onPause()などで停止します。

mOrientationEventListener.disable();

通知は頻繁に行われるため、何か処理をおこなう場合はパフォーマンスに注意しましょう。

このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です