LoginSignup
2
2

More than 3 years have passed since last update.

【Android】加速度センサーの値を表示する方法

Posted at

プログラミング勉強日記

2021年1月21日
Androidに搭載されている加速度センサーを使ってx軸、y軸、z軸の各軸にかかる加速度を測定する方法をまとめる。

加速度センサーについて

 加速度センサーは以下のようにx軸、y軸、z軸のそれぞれに対して単位Gの値として情報を素得できる。垂直で縦に持つ場合は、以下のようになり-y方向に重力加速度がかかるので、加速度センサーの値は(x, y, z)=(0, -1, 0)

image.png

出展: iOSイベント処理ガイド

加速度センサーの値を表示するプログラム

MainActivity.java
package sample;

import android.app.Activity;
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.widget.TextView;
import android.view.View;

public class MainActivity extends Activity implements SensorEventListener {

    private TextView myText;
    // SensorManagerインスタンス
    private SensorManager sma;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myText = findViewById(R.id.my_text);
        // SensorManagerのインスタンスを取得する
        sma = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        sma.registerListener(this, sma.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_FASTEST);
    }


    // センサーの値が変化すると呼ばれる
    public void onSensorChanged(SensorEvent event) {
        double x = event.values[0];
        double y = event.values[1];
        double z = event.values[2];

        String str =   " X= " + x + "\n"
                     + " Y= " + y + "\n"
                     + " Z= " + z;
        myText.setText(str);
    }

    // センサーの精度が変更されると呼ばれる
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


        <TextView
            android:id="@+id/my_text"
            android:layout_width="343dp"
            android:layout_height="119dp"
            android:paddingLeft="30dp"
            android:paddingTop="25dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

実行結果
image.png

参考文献

スマートフォンの加速度センサについて

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2