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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="Orientation Sensor Test"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.myapplication;
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 androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager smanager;
private Sensor myOrientation;
private TextView mytext;
private SensorEventListener mylistener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smanager = (SensorManager) getSystemService(SENSOR_SERVICE);
myOrientation = smanager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
mytext = (TextView) findViewById(R.id.textView1);
mylistener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
mytext.setText("방향 센서의 값을 출력합니다. \n" + "\n 방향각 : " + sensorEvent.values[0] +
"\n 피치 : " + sensorEvent.values[1] + "\n 롤 : " + sensorEvent.values[2]);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
}
protected void onResume() {
super.onResume();
smanager.registerListener(mylistener, myOrientation, SensorManager.SENSOR_DELAY_UI);
}
protected void onPause() {
super.onPause();
smanager.unregisterListener(mylistener);
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
mytext.setText("방향 센서의 값을 출력합니다. \n" + "\n 방향각 : " + sensorEvent.values[0] +
"\n 피치 : " + sensorEvent.values[1] + "\n 롤 : " + sensorEvent.values[2]);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
실제 기기에서 테스트하면 방향각과 피치도 바뀌는 것을 확인할 수 있다.
'안드로이드 Android' 카테고리의 다른 글
[모바일프로그래밍] 13-4 NFC (0) | 2020.12.06 |
---|---|
[모바일프로그래밍] 13-3 방향 센서의 개념 (0) | 2020.12.06 |
[모바일프로그래밍] 13-1 센서의 종류 및 특징 (0) | 2020.12.06 |
Android 10에서 폴더 생성이 안 될 때 (0) | 2020.12.01 |
[모바일프로그래밍] 12-3 갤러리 (0) | 2020.11.28 |