Header

  1. View current page

    Sogang Android Project

Profile_img_60x60_06
39 229

두서없이 정리하기

  • Bluetooth를 사용하기 위한 단계
  • Bluetooth과정.PNG 
  • 출처 : 고강태씨 PPT( 나중에 PPT로 받아서 보다 추가하는 것이 좋겠음)
  • 주요 4대 태스크

    • 블루투스 설정
    • 패어드(Paired) 및 디바이스 검색
    • 디바이스 연결
    • 블루투스 API
  • BluetoothAdapter

    • 블루투스 상호작용의 시작점
    • 이것을 통해 다른 디바이스를 검색하고 디바이스 목록을 쿼리할 수 있음
    • 이것을 통해 BluetoothDevice를 인스턴스화가 가능
    • 이것을 통해 다른 디바이스와의 커뮤니케니션을 listen할 BluetoothServerSocket을 생성
  • BluetoothDevice

    • 원격 블루투스의 디바이스를 나타냄
    •  BluetoothSocket을 통해 원격 디바이스와의 커넥션을 요청하여 그거의 이름, 주소, 클래스, 그리고 연결 상태와 같은 디바이스에 대한 정보를 쿼리할 수 있도록 사용
  • BluetoothSocket

    • 블루투스 소켓에 대한 인터페이스를 나타낸다. 이것을 통해 두디바이스간의 데이터를 교환하게 된다.
  • BluetoothServerSocket

    • connect 요청에 대한 listen하는 오픈 서버 소켓을 나타낸다.
    • connection이 수락될 때 BluetoothSocket을 리턴한다.
  • BluetoothClass

    • 블루투스 디바이스의 일반적인 특징과 기능들을 설명

 

  • Socket통신과 관련된 플로우차트가 있어야 겠다. 

 

  • PERMISSION (1)

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

     

  •  

     

    • BLUETOOTH 퍼미션

      • connection 요청 및 수락, 그리고 데이터 전송과 같은 커뮤니케이션을 위해서 BLUETOOTH 퍼미션이 필요
    • BULETOOTH_ADMIN 퍼미션

      • 디바이스 검색, 블루투스 설정 조작을 위해서는 BLUETOOTH_ADMIN 퍼미션이 필요
      • 대부분의 애플리케이션이 로컬 블루투스 디바이스를 검색하는 기능을 필요로 하고 있음
      • 이것을 사용하기 위해서는 BLUETOOTH 퍼미션이 필요함
  • BluetoothAdapter (2, 3)

    • BluetoothAdapter를 이용하여 블루투스 기능을 지원하는지 기능을 지원하면 블루투스 기능이 활성화 되었는지를 확인하고 활성화되지 않았으면 활성화될 수 있도록 보장해야 한다.
    • 1단계 : BluetoothAdapter 얻기

       

      BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

      if(mBluetoothAdapter == null) {

      // Device가 Bluetooth를 지원하지 않고 있음

      }

       

      • getDefaultAdapter : static으로 되어 있는 전역함수로 Bluetooth 어뎁터를 리턴한다. (하나만의 블루투스 어뎁터를 보장한다.)
      • null을 리턴하면 Bluetooth를 지원하지 않는 것임
    • 2단계 : 블루투스 활성화

       

      if(!mBluetoothAdapter.isEnabled()) {

      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

      startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

      }

       

      • isEnalbed : 활성화 여부 판단
      • ACTION_REQUEST_ENABLE : 시스템 설정을 통해 블루투스의 활성화를 요청할 수 있음
  • Bluetooth Finding (4)

    • BluetoothAdapter를 사용해서, 디바이스 검색 또는 연결된 디바이스의 목록을 쿼리하는 것을 통해 원격 블루투스 디바이스를 찾음
    • 디바이스 검색 단계

      • (로컬 영역 내의)활성화된 블루투스 디바이스를 찾아 정보를 요청하는 스캐닝 절차
      • 디바이스 이름, 클래스(?), 고유의 MAC 어드레스와 같은 정보를 요청할 수 있음
    • 디바이스 검색에 따라 디바이스와의 연결을 시도할 수 있으며, 원격 디바이스의 알려진 MAC 어드레스를 사용하면 검색을 수행하지 않고 연결될 수 있음
    • 패어드(Paired)와 커넥션(Connection)

      • Paired : 통신하려는 두 디바이스가 각기 서로의 존재를 인식하고, 인증을 위해 사용되는 공유된 링크 키를 가지고, 각기 상대방에 대해 암호화된 커넥션을 확립함
      • Connection : 디바이스들이 RFCOMM 채널을 현재 공유하고 각기 상대에게 데이터를 전송할 수 있다는 것을 의미(블루투스 API는 디바이스간에 서로 패어드된 이후에 RFCOMM 커넥션이 확립되어야 한다.)
    • 패어드 디바이스 커리

              // Get a set of currently paired devices
              Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

              // If there are paired devices, add each one to the ArrayAdapter
              if (pairedDevices.size() > 0) {
                  findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
                  for (BluetoothDevice device : pairedDevices) {
                      mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                  }
              } else {
                  String noDevices = getResources().getText(R.string.none_paired).toString();
                  mPairedDevicesArrayAdapter.add(noDevices);
              }
          }

      • getBondedDevices() : 이미 (패어드 상태로) 인식되어 있는 디바이스 집합을 커리하는 함수
    • 디바이스 검색(Discovering) - Client의 역할

      • startDiscovery() : 디바이스 검색을 수행하는 함수임, 12초에 한번씩 검색하며 비동기적인 프로세스로 진행
      • 발견된 디바이스에 대한 정보를 수신하기 위해 ACTION_FOUND 인텐트에 대한 BroadcastReceiver를 등록해야 함

            // The BroadcastReceiver that listens for discovered devices and
            // changes the title when discovery is finished
            private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();

                    // When discovery finds a device
                    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                        // Get the BluetoothDevice object from the Intent
                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        // If it's already paired, skip it, because it's been listed already
                        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                            mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                        }
                    // When discovery is finished, change the Activity title
                    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                        setProgressBarIndeterminateVisibility(false);
                        setTitle(R.string.select_device);
                        if (mNewDevicesArrayAdapter.getCount() == 0) {
                            String noDevices = getResources().getText(R.string.none_found).toString();
                            mNewDevicesArrayAdapter.add(noDevices);
                        }
                    }
                }
            };

      • discovery는 리소스의 소모 비용이 크므로, 연결할 디바이스가 발견되면 커넥션을 시도하기 전에 cancelDiscovery()를 사용해서 검색(discovery)을 항상 중지시키는 것을 확인해야 한다.
    • 검색 가능(discoverablility) 활성화 - Server의 역할

      • 다른 디바이스에서 이 기기가 검색될 수 있도록 활성화(discoverable)될 수 있도록 하기 위해서는 ACTION_REQUEST_DISCOVERABLE 액션 인텐트를 가진 startActivityForResult(Intent, int)를 호출하여야 한다.
      • 그에 따라 디폴트로 120초 동안 검색 가능하게 설정되게 된다.

                if (mBluetoothAdapter.getScanMode() !=
                    BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
                    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                    startActivity(discoverableIntent);
                }
      • 원격 디바이스(접속하려는 디바이스)는 디바이스 검색가능(discoverability)을 활성화 할 필요가 없다. discoverability을 활성화하는 것은 오직 여러분의 애플리케이션에 들어오는 커넥션을 수락할 서버 소켓을 보유하길 원할 때 뿐이다. 왜냐하면 원격 디바이스는 그것이 커넥션을 만들 수 있기 전에 디바이스를 검색할 수 있어야 하기 때문이다.
  • 지금 하는 부분

    • 페이링에서 에러가. - -;
    • connect1, connect2로 나눠놨는데... 그거 처리 다시 볼것

 

History

Last edited on 10/02/2010 15:15 by sss

Comments (0)

You must log in to leave a comment. Please sign in.