본문 바로가기
컴퓨터이야기

[안드로이드] 블루투스 장치목록 가져오기, 장치 연결/해제 이벤트 받기

by 행중이 2014. 7. 17.
반응형

 

안드로이드 장치에서  블루투스 장치목록 가져오기, 장치 연결/해제 이벤트 받기

 

먼저 AndroidManifest.xml 파일에 use-permission에

"android.permission.BLUETOOTH" 와 "android.permission.BLUETOOTH_ADMIN" 두개를 추가합니다.


  



블루투스 기기의 리스트는 BluetoothAdapter의 getBondedDevices() 메소드로 가져올 수 있습니다.

아래의 주석을 참고 하시면 코딩에 도움이 되실 겁니다.


 

                     //블루투스 Adapter를 가져온다
				BluetoothAdapter mBlueToothAdapter = BluetoothAdapter.getDefaultAdapter();
				
			
				if(mBlueToothAdapter == null){
					// 만약 블루투스 adapter가 없으면, 블루투스를 지원하지 않는 기기이거나 블루투스 기능을 끈 기기이다.
				}else{
					// 블루투스 adapter가 있으면, 블루투스 adater에서 페어링된 장치 목록을 불러올 수 있다.
					Set pairDevices = mBlueToothAdapter.getBondedDevices();
					
					//페어링된 장치가 있으면
					if(pairDevices.size()>0){
						for(BluetoothDevice device : pairDevices){
							//페어링된 장치 이름과, MAC주소를 가져올 수 있다.
							 Log.d("TEST", device.getName().toString() +" Device Is Connected!");
							 Log.d("TEST", device.getAddress().toString() +" Device Is Connected!");
						}
					}else{
						Toast.makeText(getApplicationContext(), "no Device", Toast.LENGTH_SHORT).show();
					}
				}
				
				//브로드캐스트리시버를 이용하여 블루투스 장치가 연결이 되고, 끊기는 이벤트를 받아 올 수 있다.
				BroadcastReceiver bluetoothReceiver =  new BroadcastReceiver(){
					public void onReceive(Context context, Intent intent) {
						 String action = intent.getAction();
						//연결된 장치를 intent를 통하여 가져온다.
						BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
						
						 //장치가 연결이 되었으면
						if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
							 Log.d("TEST", device.getName().toString() +" Device Is Connected!");
						//장치의 연결이 끊기면 
						}else if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){ 
							 Log.d("TEST", device.getName().toString() +" Device Is DISConnected!");
							
						}
					}			
				};
				
				//MUST unregisterReceiver(bluetoothReceiver) in onDestroy()
				IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
				registerReceiver(bluetoothReceiver, filter);
				filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
				registerReceiver(bluetoothReceiver, filter);


브로드캐스트 리시버는 액티비티가 종료되는 onDestroy()에서 반드시 unregisterReceiver를 해주어야 합니다.

안그러면 백그라운드에서 계속 돌게되어 메모리를 잡아먹는 현상이..



반응형

댓글