ภาพรวม
บทความนี้สาธิตวิธีตรวจจับสถานะการเสียบหูฟัง (Headset/Headphones) ใน Android ผ่าน BroadcastReceiver ที่ฟัง Intent.ACTION_HEADSET_PLUG เหมาะสำหรับแอปเพลง, โทรศัพท์, หรือแอปที่ต้องปรับเสียงอัตโนมัติเมื่อเสียบ/ถอดหูฟัง
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
สร้างโปรเจกต์ Android ใหม่ใน Android Studio
ขั้นตอนที่ 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:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ตรวจจับการเสียบหูฟัง"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity (src/MainActivity.java) - เวอร์ชันปรับปรุง
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver headsetReceiver;
private AudioManager audioManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// ตรวจสอบสถานะปัจจุบันทันที
checkCurrentHeadsetState();
// ลงทะเบียน BroadcastReceiver
headsetReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {
int state = intent.getIntExtra("state", -1); // 0 = ถอด, 1 = เสียบ
int microphone = intent.getIntExtra("microphone", 0); // 1 = มีไมค์, 0 = ไม่มี
int name = intent.getIntExtra("name", 0); // ชื่ออุปกรณ์ (บางครั้ง)
String message;
if (state == 1) {
message = "หูฟังเสียบแล้ว" + (microphone == 1 ? " (มีไมโครโฟน)" : " (ไม่มีไมโครโฟน)");
} else {
message = "หูฟังถอดออกแล้ว";
}
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
// อัปเดต UI หรือปรับ Audio Route ที่นี่
updateAudioRouting(state == 1, microphone == 1);
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(headsetReceiver, filter);
}
private void checkCurrentHeadsetState() {
// ตรวจสอบสถานะปัจจุบันผ่าน AudioManager (API 11+)
boolean isWiredHeadsetOn = audioManager.isWiredHeadsetOn();
// หมายเหตุ: isWiredHeadsetOn() deprecated ใน API 31 แต่ยังใช้ได้
// วิธีใหม่ (API 23+): ใช้ getDevices()
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
AudioDeviceInfo[] devices = audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS);
for (AudioDeviceInfo device : devices) {
if (device.getType() == AudioDeviceInfo.TYPE_WIRED_HEADSET ||
device.getType() == AudioDeviceInfo.TYPE_WIRED_HEADPHONES) {
isWiredHeadsetOn = true;
break;
}
}
}
Toast.makeText(this, "สถานะเริ่มต้น: " + (isWiredHeadsetOn ? "เสียบอยู่" : "ไม่ได้เสียบ"), Toast.LENGTH_SHORT).show();
}
private void updateAudioRouting(boolean headsetConnected, boolean hasMic) {
// ตัวอย่าง: สลับ Audio Output ไปที่หูฟัง/สปีกเกอร์
if (headsetConnected) {
// audioManager.setSpeakerphoneOn(false); // ปิดสปีกเกอร์
} else {
// audioManager.setSpeakerphoneOn(true); // เปิดสปีกเกอร์
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (headsetReceiver != null) {
unregisterReceiver(headsetReceiver);
}
}
}
ขั้นตอนที่ 4: 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.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<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>
ข้อมูลเพิ่มเติม (Extras ใน Intent)
| Key | Type | ค่าที่เป็นไปได้ | คำอธิบาย |
|---|---|---|---|
| state | int | 0, 1 | 0 = ถอดหูฟัง, 1 = เสียบหูฟัง |
| microphone | int | 0, 1 | 1 = มีไมโครโฟน (Headset), 0 = ไม่มี (Headphones) |
| name | String | ชื่ออุปกรณ์ | ชื่อหูฟัง (ไม่เสมอไปว่ามีค่า) |
ข้อควรระวังและ Best Practices
- Unregister Receiver: ต้อง unregister ใน onDestroy() มิฉะนั้นจะ Memory Leak
- Sticky Broadcast: ACTION_HEADSET_PLUG เป็น Sticky Broadcast จะส่งสถานะล่าสุดทันทีที่ลงทะเบียน
- Bluetooth Headset: สำหรับ Bluetooth ใช้
BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGEDแทน - USB Audio: ต้องใช้
UsbManagerและAudioManagerร่วมกัน - Permission: ไม่ต้องการ Permission พิเศษสำหรับ Wired Headset
การทดสอบ
รันแอปบนอุปกรณ์จริง (Emulator ไม่รองรับ Hardware Headset Jack) → เสียบ/ถอดหูฟัง → จะเห็น Toast แสดงสถานะ