Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách kiểm tra thiết bị Android hỗ trợ cảm biến Nhiệt độ môi trường (Ambient Temperature)

Giới thiệu

Ví dụ này minh họa cách kiểm tra xem thiết bị Android có hỗ trợ cảm biến Nhiệt độ môi trường (Ambient Temperature) hay không.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <TextView
        android:id="@+id/actionEvent"
        android:textSize="40sp"
        android:layout_marginTop="30dp"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />
</LinearLayout>

Bước 3: Viết logic (src/MainActivity.java)

package com.example.myapplication;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private SensorManager sensorManager;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView actionEvent = findViewById(R.id.actionEvent);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        // Kiểm tra TYPE_AMBIENT_TEMPERATURE (nhiệt độ môi trường)
        if (sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) != null) {
            actionEvent.setText("Hỗ trợ cảm biến Nhiệt độ môi trường");
        } else {
            actionEvent.setText("Không hỗ trợ cảm biến Nhiệt độ môi trường");
        }
    }
}

Cảm biến TYPE_AMBIENT_TEMPERATURE đo nhiệt độ không khí xung quanh. Rất ít điện thoại hỗ trợ (thường thấy trên thiết bị chuyên dụng hoặc một số Samsung cũ).

Chạy ứng dụng

Chạy trên thiết bị thật. Kết quả hầu như luôn là Không hỗ trợ trên điện thoại thông thường.

Cách kiểm tra thiết bị Android hỗ trợ cảm biến Nhiệt độ môi trường (Ambient Temperature)