ภาพรวม
ตัวอย่างนี้สาธิตวิธีการตรวจสอบว่าหูฟัง (Headset/Headphones) ถูกเสียบอยู่ในอุปกรณ์ Android หรือไม่ โดยใช้ BroadcastReceiver รับ Intent ACTION_HEADSET_PLUG ด้วย Kotlin
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
สร้างโปรเจกต์ Android ใหม่ใน Android Studio
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอหลัก (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Headphones connection status"
android:textColor="@android:color/holo_purple"
android:textSize="16sp"
android:textStyle="bold" />
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity.kt
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private var broadcastReceiver: BroadcastReceiver? = null
private var headsetPluggedIn = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
val action = intent.action
if (Intent.ACTION_HEADSET_PLUG == action) {
val state = intent.getIntExtra("state", -1)
when (state) {
0 -> {
headsetPluggedIn = false
Toast.makeText(applicationContext, "Headphones not plugged in", Toast.LENGTH_LONG).show()
}
1 -> {
headsetPluggedIn = true
Toast.makeText(applicationContext, "Headphones plugged in", Toast.LENGTH_LONG).show()
}
}
}
}
}
val receiverFilter = IntentFilter(Intent.ACTION_HEADSET_PLUG)
registerReceiver(broadcastReceiver, receiverFilter)
}
override fun onDestroy() {
super.onDestroy()
broadcastReceiver?.let { unregisterReceiver(it) }
}
}
ขั้นตอนที่ 4: ตั้งค่า AndroidManifest.xml
ใช้การตั้งค่ามาตรฐาน (หมายเหตุ: โค้ดต้นฉบับมี typo `
ทดสอบการทำงาน
รันแอปบนอุปกรณ์จริง เสียบ/ถอดหูฟัง จะเห็น Toast แสดงสถานะการเชื่อมต่อ
ข้อมูลเพิ่มเติม
- Extra "state": 0 = ถอดออก, 1 = เสียบเข้า
- Extra "microphone": 1 = มีไมโครโฟน, 0 = ไม่มี
- Extra "name": ชื่ออุปกรณ์ (หากมี)
- Runtime Registration: ลงทะเบียนใน onCreate/onResume ยกเลิกใน onPause/onDestroy (ไม่ต้องประกาศใน Manifest)
- AudioManager: วิธีอื่นคือใช้
AudioManager.isWiredHeadsetOn()ตรวจสอบสถานะทันทีโดยไม่ต้องรอ Broadcast