Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีตรวจสอบว่าอุปกรณ์ Android มีเซ็นเซอร์นิ้วมือ (Fingerprint Sensor) หรือไม่

ภาพรวม

บทความนี้สาธิตวิธีตรวจสอบว่าอุปกรณ์มี Hardware Fingerprint Sensor หรือไม่ ผ่าน FingerprintManager.isHardwareDetected() (API 23+) และ BiometricManager (API 28+ แนะนำ)

ขั้นตอนที่ 1: สร้างโปรเจกต์

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: Layout (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:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="24dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/actionEvent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textAlignment="center"
        android:lineSpacingExtra="8dp" />

</LinearLayout>

ขั้นตอนที่ 3: โค้ดหลัก (java/MainActivity.java)

package com.example.myapplication;

import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;

import java.security.KeyStore;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class MainActivity extends AppCompatActivity {

    private TextView resultTextView;

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

        resultTextView = findViewById(R.id.actionEvent);

        StringBuilder info = new StringBuilder();

        // วิธีที่ 1: FingerprintManager (API 23-27, Deprecated API 28+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            FingerprintManager fingerprintManager = getSystemService(FingerprintManager.class);
            boolean hasHardware = fingerprintManager.isHardwareDetected();
            boolean hasEnrolled = fingerprintManager.hasEnrolledFingerprints();

            info.append("=== FingerprintManager (Legacy) ===\n");
            info.append("มี Hardware: ").append(hasHardware ? "ใช่" : "ไม่").append("\n");
            info.append("ลงทะเบียนนิ้วมือ: ").append(hasEnrolled ? "ใช่" : "ไม่").append("\n\n");
        }

        // วิธีที่ 2: BiometricManager (API 28+ แนะนำ)
        BiometricManager biometricManager = BiometricManager.from(this);
        int authResult = biometricManager.canAuthenticate(
            BiometricManager.Authenticators.BIOMETRIC_STRONG |
            BiometricManager.Authenticators.BIOMETRIC_WEAK |
            BiometricManager.Authenticators.DEVICE_CREDENTIAL
        );

        info.append("=== BiometricManager (Modern) ===\n");
        switch (authResult) {
            case BiometricManager.BIOMETRIC_SUCCESS:
                info.append("พร้อมใช้งาน Biometric (นิ้วมือ/ใบหน้า/ไอริส)\n");
                break;
            case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
                info.append("ไม่มี Hardware Biometric\n");
                break;
            case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
                info.append("Hardware ไม่พร้อมใช้งาน (กำลังใช้งานอื่น/อุปกรณ์เสีย)\n");
                break;
            case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
                info.append("มี Hardware แต่ยังไม่ได้ลงทะเบียน Biometric\n");
                break;
            case BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED:
                info.append("ต้องอัปเดต Security Patch\n");
                break;
            case BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED:
                info.append("ไม่รองรับ Biometric Authentication\n");
                break;
            default:
                info.append("สถานะไม่ทราบ: ").append(authResult).append("\n");
        }

        // ตรวจสอบ Feature ใน PackageManager
        PackageManager pm = getPackageManager();
        boolean hasFingerprintFeature = pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
        boolean hasFaceFeature = pm.hasSystemFeature(PackageManager.FEATURE_FACE);

        info.append("\n=== PackageManager Features ===\n");
        info.append("FEATURE_FINGERPRINT: ").append(hasFingerprintFeature ? "มี" : "ไม่มี").append("\n");
        info.append("FEATURE_FACE: ").append(hasFaceFeature ? "มี" : "ไม่มี").append("\n");

        resultTextView.setText(info.toString());
    }
}

ขั้นตอนที่ 4: AndroidManifest.xml - Permissions

<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<!-- สำหรับ FingerprintManager แบบเก่า -->
<uses-permission android:name="android.permission.USE_FINGERPRINT" />

Dependency (build.gradle)

dependencies {
    // Biometric API (AndroidX)
    implementation "androidx.biometric:biometric:1.1.0"
    // หรือเวอร์ชันใหม่กว่า
    implementation "androidx.biometric:biometric-ktx:1.2.0-alpha04"
}

เปรียบเทียบ API

FeatureFingerprintManager (Deprecated)BiometricManager (แนะนำ)
API Level23 (Marshmallow)28 (Pie) + AndroidX Backport
รองรับ Face/Irisไม่ใช่
รองรับ Device Credential (PIN/Pattern)ไม่ใช่ (API 30+)
UI Dialog สำเร็จรูปต้องสร้างเองมี BiometricPrompt
Crypto Integrationยากง่าย (CryptoObject)

ใช้ BiometricPrompt (แนะนำ)

BiometricPrompt biometricPrompt = new BiometricPrompt(this,
    ContextCompat.getMainExecutor(this),
    new BiometricPrompt.AuthenticationCallback() {
        @Override
        public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
            // สำเร็จ - decrypt data, login, etc.
        }

        @Override
        public void onAuthenticationError(int errorCode, CharSequence errString) {
            // ผิดพลาด
        }
    });

BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder()
    .setTitle("ยืนยันตัวตน")
    .setSubtitle("ใช้ลายนิ้วมือหรือ Face Unlock")
    .setNegativeButtonText("ยกเลิก")
    .build();

biometricPrompt.authenticate(promptInfo);

ทดสอบ

รันบนอุปกรณ์จริง จะแสดงสถานะ Hardware, Enrollment, และ Biometric Support แบบละเอียด