본문 바로가기

안드로이드 Android

[모바일프로그래밍] 13-1 센서의 종류 및 특징

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="Sensor Example"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:text="Sensor List ?"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.java

package com.example.myapplication;

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String report = "Sensor List \n";
                SensorManager smanager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
                List<Sensor> sensors = smanager.getSensorList(Sensor.TYPE_ALL);

                report += "전체 센서의 수는 " + sensors.size() + "\n";
                Integer i = 1;
                for (Sensor s: sensors) {
                    report += " " + i++ + " 번째 센서 : 이름 " + s.getName() + "\n    power : " +
                        s.getPower() + "\n  해상도 : " + s.getResolution() +
                            "\n 범위 : " + s.getMaximumRange() + "\n\n";

                    TextView txtview = (TextView) findViewById(R.id.TextView1);
                    txtview.setText(report);
                }
            }
        });
    }
}