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

Bật đèn flash (Flashlight) lập trình trong Android

Bật đèn flash (Flashlight) lập trình trong Android

Hướng dẫn này minh họa cách bật/tắt đèn flash camera (torch) bằng Camera2 API trong Android.

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

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
    <ToggleButton
        android:id="@+id/onOffFlashlight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Turn Off"
        android:textOff="Turn On"
        android:checked="false"
        android:text="Turn On/Off Camera LED/ Flashlight Android" />
</LinearLayout>

Bước 3: Code MainActivity.java

import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {
    private CameraManager mCameraManager;
    private String mCameraId;
    private ToggleButton toggleButton;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Kiểm tra thiết bị có flash không
        boolean isFlashAvailable = getApplicationContext().getPackageManager()
            .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        
        if (!isFlashAvailable) {
            showNoFlashError();
            return;
        }
        
        mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            // Lấy ID camera đầu tiên (thường là camera sau)
            mCameraId = mCameraManager.getCameraIdList()[0];
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        
        toggleButton = findViewById(R.id.onOffFlashlight);
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switchFlashLight(isChecked);
            }
        });
    }
    
    private void showNoFlashError() {
        AlertDialog alert = new AlertDialog.Builder(this).create();
        alert.setTitle("Oops!");
        alert.setMessage("Flash not available in this device...");
        alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", (dialog, which) -> finish());
        alert.show();
    }
    
    private void switchFlashLight(boolean status) {
        try {
            mCameraManager.setTorchMode(mCameraId, status);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
}

Bước 4: Cấu hình quyền và feature trong AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera.flash" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị có đèn flash, chạy app. Sử dụng ToggleButton để bật/tắt đèn flash. Nếu thiết bị không có flash, sẽ hiển thị dialog thông báo và thoát app.

Lưu ý quan trọng:
  • Sử dụng FEATURE_CAMERA_FLASH (không phải FEATURE_CAMERA_FRONT) để kiểm tra flash
  • Camera2 API yêu cầu Android 5.0+ (API 21)
  • Quyền CAMERA là bắt buộc
  • Trên Android 6.0+, cần yêu cầu quyền runtime cho CAMERA

Cải tiến: Xử lý quyền runtime (Android 6.0+)

// Thêm vào onCreate trước khi truy cập camera
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) 
    != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}