Android/공부

[Android] Bluetooth 시작하기

꾸끄꾸꾸 2020. 11. 30. 13:34
bluetooth 통신 기초
  • 블루투스 기능에 대한 기초 학습

 

 

1. 매니페스트 권한 주기

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

 

2. 블루투스 어댑터 연결하기

BluetoothAdapter mBluetoothAdapter;

 

2. bluetooth on

if (!mBluetoothAdapter.isEnabled()) {
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, REQUEST_ENABLE_CODE);
}

 

3. bluetooth off

if (mBluetoothAdapter.isEnabled()) {
	mBluetoothAdapter.disable();
}

 

4.  주변 블루투스 장치 검색

if (mBluetoothAdapter.isEnabled()) {
	Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
	for (BluetoothDevice device:devices) {
		pairedtv.append("\nDevice"+device.getName()+","+device);
	}
}

 

5.  내 장치를 다른 장치에서 검색 할 수 있도록 허용하기

if (!mBluetoothAdapter.isDiscovering()) {
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    startActivityForResult(intent, REQUEST_DISCOVER_CODE);
}