facebook twitter hatena line email

Android/加速度センサー

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
  • AndroidHelloworld1.java
package info.nonip.AndroidHelloworld1;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.TextView;
public class AndroidHelloworld1Activity extends Activity implements SensorEventListener {

    private SensorManager manager;
    private TextView values;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        values = (TextView)findViewById(R.id.text1);
        manager = (SensorManager)getSystemService(SENSOR_SERVICE);
    }
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        // Listenerの解除
        manager.unregisterListener(this);
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // Listener登録
        List<Sensor> sensors = manager.getSensorList(Sensor.TYPE_ACCELEROMETER);
        if(sensors.size() > 0) {
            Sensor s = sensors.get(0);
            manager.registerListener(this, s, SensorManager.SENSOR_DELAY_UI);
        }
    }
    // jdk1.5以下はアノテーションを消さないとコンパイル不可能
    //@Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub
    }
    // jdk1.5以下はアノテーションを消さないとコンパイル不可能
    //@Override
    public void onSensorChanged(SensorEvent event) {
        // TODO Auto-generated method stub
        String str = "";
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            str = "X:" + event.values[0]
                    + "\nY:" + event.values[1]
                    + "\nZ:" + event.values[2];
            values.setText(str);
        }
    }
}
  • layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
</LinearLayout>