Giới thiệu
Ví dụ này minh họa cách bật/tắt đèn flash sau camera (torch) theo cách lập trình sử dụng CameraManager API (Camera2) trong Android Kotlin.
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, điền thông tin.
Bước 2: Giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<ToggleButton
android:id="@+id/onOffFlashlight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:checked="false"
android:textOff="Turn On"
android:textOn="Turn Off" />
</RelativeLayout>
Bước 3: MainActivity.kt
import android.content.Context
import android.content.pm.PackageManager
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.Build
import android.os.Bundle
import android.widget.CompoundButton
import android.widget.Toast
import android.widget.ToggleButton
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var cameraManager: CameraManager
private lateinit var cameraId: String
private lateinit var toggleButton: ToggleButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
// Kiểm tra thiết bị có flash không
val hasFlash = packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)
if (!hasFlash) {
showNoFlashError()
return
}
cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
try {
cameraId = cameraManager.cameraIdList[0] // Thường là camera sau
} catch (e: CameraAccessException) {
e.printStackTrace()
Toast.makeText(this, "Cannot access camera", Toast.LENGTH_SHORT).show()
finish()
return
}
toggleButton = findViewById(R.id.onOffFlashlight)
toggleButton.setOnCheckedChangeListener { _, isChecked ->
switchFlashLight(isChecked)
}
}
private fun showNoFlashError() {
AlertDialog.Builder(this)
.setTitle("Oops!")
.setMessage("Flash not available on this device")
.setPositiveButton("OK") { _, _ -> finish() }
.show()
}
private fun switchFlashLight(on: Boolean) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, on)
}
} catch (e: CameraAccessException) {
e.printStackTrace()
Toast.makeText(this, "Error: ${e.message}", Toast.LENGTH_SHORT).show()
}
}
override fun onStop() {
super.onStop()
// Tắt flash khi app ẩn để tiết kiệm pin
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, false)
}
} catch (_: Exception) { /* ignore */ }
}
}
Bước 4: AndroidManifest.xml (cần quyền CAMERA và feature flash)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.q11">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.flash" android:required="false" />
<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
⚠️ Chỉ test trên thiết bị thật (Real device) vì emulator thường không có flash.
Kết nối thiết bị, nhấn Run. Nhấn ToggleButton để bật/tắt đèn flash.
Lưu ý: Từ Android 6.0 (API 23), setTorchMode yêu cầu quyền CAMERA (dangerous permission). Cần request runtime permission nếu targetSdk >= 23.