Kotlin을 사용하면 BroadcastReceiver와 ACTION_HEADSET_PLUG 브로드캐스트를 통해 유선 헤드셋이 안드로이드 기기에 연결되어 있는지 손쉽게 확인할 수 있습니다. 이 글에서는 실제로 동작하는 예제 코드와 함께 단계별로 구현 방법을 자세히 살펴보겠습니다.
동작 원리
안드로이드 시스템은 헤드셋이 연결되거나 분리될 때마다 ACTION_HEADSET_PLUG라는 시스템 브로드캐스트를 발생시킵니다. 이 브로드캐스트에는 state라는 extra 값이 담겨 있으며, 값이 0이면 헤드셋이 분리된 상태, 1이면 연결된 상태를 의미합니다. 따라서 이 브로드캐스트를 수신하는 리시버만 등록해 두면 헤드셋의 연결 여부를 실시간으로 감지할 수 있습니다.
구현 단계
1단계 — 새 프로젝트 생성
Android Studio에서 File → New Project 메뉴로 이동한 뒤, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계 — 레이아웃 작성 (res/layout/activity_main.xml)
아래 코드를 activity_main.xml 파일에 추가합니다. 화면 중앙에는 헤드셋 연결 상태를 나타내는 TextView가 배치됩니다.
<?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 작성
다음으로 src/MainActivity.kt 파일에 아래 코드를 추가합니다. 여기서는 BroadcastReceiver를 등록하여 헤드셋 연결/분리 이벤트를 수신하고, 그 결과를 Toast 메시지로 화면에 표시합니다.
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() {
var broadcastReceiver: BroadcastReceiver? = null
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
val int: Int
if (Intent.ACTION_HEADSET_PLUG == action) {
int = intent.getIntExtra("state", -1)
if (int == 0) {
microphonePluggedIn = false
Toast.makeText(applicationContext, "Headphones not plugged in", Toast.LENGTH_LONG).show()
}
if (int == 1) {
microphonePluggedIn = true
Toast.makeText(applicationContext, "Headphones plugged in", Toast.LENGTH_LONG).show()
}
}
}
}
val receiverFilter = IntentFilter(Intent.ACTION_HEADSET_PLUG)
registerReceiver(broadcastReceiver, receiverFilter)
}
}코드를 간단히 설명하면 다음과 같습니다.
onReceive()에서 전달받은 인텐트의 action이ACTION_HEADSET_PLUG인지 먼저 확인합니다.getIntExtra("state", -1)로 현재 상태 값을 읽어옵니다. 0이면 분리, 1이면 연결 상태입니다.- 상태 값에 따라
microphonePluggedIn변수를 갱신하고, 사용자에게 알리는 Toast를 띄웁니다.
4단계 — AndroidManifest.xml 설정
마지막으로 AndroidManifest.xml에 아래 코드를 추가하여 MainActivity를 런처 액티비티로 지정합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.q11">
<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>앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰이 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 버튼을 클릭하세요. 실행 옵션 목록에서 본인의 모바일 기기를 선택하면, 해당 기기에 앱이 설치되고 기본 화면이 표시됩니다.
이후 헤드셋을 꽂거나 뽑을 때마다 ACTION_HEADSET_PLUG 브로드캐스트가 발생하고, 리시버가 이를 감지하여 "Headphones plugged in" 또는 "Headphones not plugged in"이라는 Toast 메시지가 화면에 나타나는 것을 확인할 수 있습니다.