Giới thiệu
Ví dụ minh họa cách phát hiện trạng thái cắm/rút tai nghe (headset/headphone) trên Android sử dụng BroadcastReceiver lắng nghe intent ACTION_HEADSET_PLUG bằng Kotlin.
Các bước thực hiện
Bước 1: Tạo dự án mới
Android Studio > File > New Project.
Bước 2: Layout (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="Trạng thái kết nối tai nghe"
android:textColor="@android:color/holo_purple"
android:textSize="16sp"
android:textStyle="bold" />
</RelativeLayout>
Bước 3: MainActivity.kt - BroadcastReceiver
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 microphonePluggedIn = 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) // 0: rút, 1: cắm
when (state) {
0 -> {
microphonePluggedIn = false
Toast.makeText(applicationContext, "Tai nghe đã rút ra", Toast.LENGTH_LONG).show()
}
1 -> {
microphonePluggedIn = true
Toast.makeText(applicationContext, "Tai nghe đã cắm vào", Toast.LENGTH_LONG).show()
}
}
}
}
}
val filter = IntentFilter(Intent.ACTION_HEADSET_PLUG)
registerReceiver(broadcastReceiver, filter)
}
override fun onDestroy() {
super.onDestroy()
broadcastReceiver?.let { unregisterReceiver(it) } // Quan trọng: hủy đăng ký
}
}
Bước 4: AndroidManifest.xml
Lưu ý: Intent ACTION_HEADSET_PLUG là broadcast sticky và không cần khai báo trong Manifest. Đăng ký động (registerReceiver) trong code là đủ. File manifest chỉ cần activity mặc định.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.headsetdetection">
<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 và kiểm tra
Chạy app, cắm/rút tai nghe (có dây hoặc USB-C/Jack). Toast sẽ hiển thị trạng thái tương ứng.
Lưu ý quan trọng
- Phải hủy đăng ký (unregisterReceiver) trong
onDestroyhoặconStopđể tránh memory leak và crash "IntentReceiver leaked". - Extra
"state": 0 = unplugged, 1 = plugged. Có thể có extra"microphone"(1 nếu tai nghe có mic). - Từ Android 10 (API 29), broadcast này có thể bị hạn chế. Cần test trên thiết bị thật.
- Bluetooth headset: Cần dùng
BluetoothHeadsetprofile hoặcACTION_SCO_AUDIO_STATE_CHANGED. - Cách kiểm tra trạng thái ngay lập tức (không chờ broadcast):
fun isHeadsetPlugged(context: Context): Boolean {
val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
return audioManager.isWiredHeadsetOn
}