본문 바로가기
Android

[Android] Android 12 기준 블루투스 연결 감지하기

by 준그래머 2024. 6. 5.
반응형

Android 12에서 블루투스 연결 감지 권한

 

블루투스 권한  |  Connectivity  |  Android Developers

이 페이지는 Cloud Translation API를 통해 번역되었습니다. 블루투스 권한 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 앱에서 블루투스 기능을 사용하려면 여

developer.android.com

권한을 추가해 주고

<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

사용자에게 권한을 받아야 한다.

if(checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED){
    requestPermissions(new String[]{Manifest.permission.BLUETOOTH_CONNECT}, 1000);
    return;
}

 

 

블루투스 연결 및 해지 감지 브로드 캐스트 받기

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(BluetoothDevice.ACTION_ACL_CONNECTED)) { // 블루투스 기기 연결
        }
        else if(intent.getAction().equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) { // 블루투스 기기 해제
        }
    }
};

IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
registerReceiver(receiver, filter);

 

 

블루투스 연결 및 해지 상태 확인 하기

public boolean isBluetoothConnected(Context context) {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
        // Bluetooth가 지원되지 않거나 활성화되지 않은 경우
        return false;
    }

    // 블루투스가 활성화 되어 있는지 리턴
    return bluetoothAdapter.getProfileProxy(context, new BluetoothProfile.ServiceListener() {
        @Override
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            ...
        }

        @Override
        public void onServiceDisconnected(int profile) {
            
        }
    }, BluetoothProfile.HEADSET);
}

단 여기서 BluetoothProfile.HEADSET로 되어 있어 HEADSET 타입의 기기만 연결된 기기 리스트로 불러온다.

 

 

전체 코드

public class MainActivity extends AppCompatActivity {

    private TextView tvState, tvName, tvAddress;

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // Get device name and address
                if(tvName!=null) {
                    String deviceName = device.getName();
                    tvName.setText(deviceName);
                }
                if(tvState!=null){
                    tvState.setText("연결됨");
                }
                if(tvAddress!=null){
                    String deviceAddress = device.getAddress();
                    tvAddress.setText(deviceAddress);
                }

            }
            else if(intent.getAction().equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
                if(tvName!=null) {
                    tvName.setText("");
                }
                if(tvState!=null){
                    tvState.setText("연결되지 않음");
                }
                if(tvAddress!=null) {
                    tvAddress.setText("");
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.BLUETOOTH_CONNECT}, 1000);
            return;
        }

        tvState = findViewById(R.id.tv_state);
        tvName = findViewById(R.id.tv_name);
        tvAddress = findViewById(R.id.tv_address);

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(receiver, filter);

        isBluetoothConnected(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        tvState = findViewById(R.id.tv_state);
        tvName = findViewById(R.id.tv_name);
        tvAddress = findViewById(R.id.tv_address);

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(receiver, filter);

        if(isBluetoothConnected(this)){
            tvState.setText("연결됨");
        }
        else {
            tvState.setText("연결되지 않음");
            tvAddress.setText("");
            tvName.setText("");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    public boolean isBluetoothConnected(Context context) {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            // Bluetooth가 지원되지 않거나 활성화되지 않은 경우
            return false;
        }

        // 블루투스가 활성화 되어 있는지 리턴
        return bluetoothAdapter.getProfileProxy(context, new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                boolean isConnected = !proxy.getConnectedDevices().isEmpty();
                if(isConnected) {
                    StringBuilder deviceNames = new StringBuilder();
                    StringBuilder deviceAddresses = new StringBuilder();
                    int index = 0;
                    for(BluetoothDevice device : proxy.getConnectedDevices()){
                        deviceNames.append(device.getName());
                        deviceAddresses.append(device.getAddress());
                        if(index < proxy.getConnectedDevices().size()-1) {
                            deviceNames.append(", ");
                            deviceAddresses.append(", ");
                        }
                    }
                    tvName.setText(deviceNames);
                    tvAddress.setText(deviceAddresses);
                }
            }

            @Override
            public void onServiceDisconnected(int profile) {

            }
        }, BluetoothProfile.HEADSET);
    }
}
반응형