読者です 読者をやめる 読者になる 読者になる

IT練習ノート

IT関連で調べたこと(実際は嵌ったこと)を書いています。

android端末の傾き情報の取得

もうちょっときれいにまとめたかったのですが。。

アクティビティ

package com.example.sensor01;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("UseSparseArrays")
public class MySensor extends ActionBarActivity implements SensorEventListener {

    private SensorManager sMng = null;
    private Map<Integer, Boolean> a = new HashMap<Integer, Boolean>();
    private float[] magneticValues = null;
    private float[] accelerometerValues = null;
    private int MATRIX_SIZE = 16;
    private float[] IN = new float[MATRIX_SIZE];
    private float[] OUT = new float[MATRIX_SIZE];
    private float[] I = new float[MATRIX_SIZE];
    
    
    @Override
    public void onSensorChanged(SensorEvent event) {
        switch(event.sensor.getType()){
        case Sensor.TYPE_MAGNETIC_FIELD:
            magneticValues = event.values.clone();
        break;
        case Sensor.TYPE_ACCELEROMETER:
            accelerometerValues = event.values.clone();
        break;
        }
        
        if( magneticValues != null && accelerometerValues != null) {
            
            SensorManager.getRotationMatrix(IN, I, accelerometerValues, magneticValues);
            SensorManager.remapCoordinateSystem(IN, SensorManager.AXIS_X, SensorManager.AXIS_Y, OUT);
            float[] values = new float[3];
            SensorManager.getOrientation(OUT, values);
            TextView azimuthTV = (TextView)this.findViewById(R.id.textViewAzimuth);
            azimuthTV.setText(String.format("%3.2f", Math.toDegrees(values[0])));
            TextView pitchTV = (TextView)this.findViewById(R.id.textViewPitch);
            pitchTV.setText(String.format("%3.2f", Math.toDegrees(values[1])));
            TextView rollTV = (TextView)this.findViewById(R.id.textViewRoll);
            rollTV.setText(String.format("%3.2f", Math.toDegrees(values[2])));
        }
        
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //no implementation
    }

    @Override
    protected void onResume(){
        super.onResume();      
        for (int type : new int[]{Sensor.TYPE_MAGNETIC_FIELD, Sensor.TYPE_ACCELEROMETER}){
            List<Sensor> s = sMng.getSensorList(type);
            if (!s.isEmpty()){
                sMng.registerListener(this, s.get(0), SensorManager.SENSOR_DELAY_UI);
                a.put(type, true);
            }
        }
    }
    @Override
    protected void onPause(){
        super.onPause();
        if(a.values().contains(true)) {
            sMng.unregisterListener(this);
            for (int t : a.keySet()) {
                a.put(t, false);
            }
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_sensor);

        sMng = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my_sensor, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_my_sensor, container, false);
            return rootView;
        }
    }


}

実行結果

f:id:naotoogawa:20140525171659p:plain

参考にした情報