개요
이 예제는 BroadcastReceiver를 활용하여 블루투스 기기가 안드로이드 기기에 연결되어 있는지, 아니면 연결이 해제되었는지를 실시간으로 감지하는 방법을 보여줍니다.
안드로이드 시스템은 블루투스 연결 상태가 바뀔 때마다 시스템 브로드캐스트를 발생시키며, 대표적인 액션은 다음과 같습니다.
- ACTION_ACL_CONNECTED — 블루투스 기기가 연결되었을 때 발생
- ACTION_ACL_DISCONNECT_REQUESTED — 연결 해제가 요청되었을 때 발생
- ACTION_ACL_DISCONNECTED — 블루투스 기기 연결이 해제되었을 때 발생
이 액션들을 IntentFilter에 등록해 수신하면 연결 상태 변화를 손쉽게 파악할 수 있습니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File ⇒ New Project로 이동한 후, 필요한 모든 정보를 입력하여 새 프로젝트를 생성합니다.
2단계 — 레이아웃 작성 (activity_main.xml)
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textStyle="bold"
android:text="더 나은 결과를 위해 기기의 블루투스 설정을 직접 열어 확인해 보세요."/>
</LinearLayout>
3단계 — 메인 액티비티 구현 (MainActivity.java)
src/MainActivity.java 파일에 아래 코드를 추가합니다. BroadcastReceiver를 등록하여 블루투스 연결 및 해제 이벤트를 수신하고, 토스트 메시지로 현재 상태를 화면에 표시합니다.
import android.bluetooth.BluetoothDevice;
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;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(broadcastReceiver, filter);
}
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
BluetoothDevice device;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
Toast.makeText(getApplicationContext(), "기기가 연결되었습니다.", Toast.LENGTH_SHORT).show();
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Toast.makeText(getApplicationContext(), "기기 연결이 해제되었습니다.", Toast.LENGTH_SHORT).show();
}
}
};
}
4단계 — 권한 설정 (AndroidManifest.xml)
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" />
<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 아이콘을 클릭합니다. 기기 목록에서 자신의 모바일 기기를 선택하면, 모바일 화면에 앱의 기본 화면이 표시됩니다.
이후 기기의 블루투스 설정 화면에서 다른 블루투스 기기를 연결하거나 해제해 보세요. 앱이 상태 변화를 감지하여 토스트 메시지로 알려주는 것을 확인할 수 있습니다.
참고 사항
- Android 12(API 31) 이상에서는 매니페스트에 BLUETOOTH_CONNECT 권한을 추가하고, 런타임 권한 요청 처리가 필요할 수 있습니다.
getParcelableExtra()는 API 33부터 deprecated되었으므로, 최신 환경에서는 타입 인자를 받는 오버로드나IntentCompat.getParcelableExtra()사용을 권장합니다.