2013-06-05 2 views
5

나는 Bluetooth를 통해 하나의 기기에 연결할 수 있도록 2 개 이상의 기기가 필요한 안드로이드 애플리케이션을 만들고 있습니다. 두 장치를 피어 - 투 - 피어 형식으로 연결하는 코드가 작동하지만 다른 연결하려고하면 "연결 거부"라는 IOException이 발생합니다. 소켓이 닫혀 있기 때문에 페어링을 완료 할 수 없기 때문입니다. 오류는 다음과 같습니다. 블루투스를 사용하여 두 개의 Android 기기를 세 번째 기기에 페어링

Socket closed. Unable to complete pairing. 
java.io.IOException: Connection refused 
    at android.bluetooth.BluetoothSocket.connectNative(Native Method) 
    at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:216) 
    at com.ablueworld.androidgridcomputingframework.BluetoothManager$ConnectAsyncTask.doInBackground(BluetoothManager.java:270) 
    at com.ablueworld.androidgridcomputingframework.BluetoothManager$ConnectAsyncTask.doInBackground(BluetoothManager.java:1) 
    at android.os.AsyncTask$2.call(AsyncTask.java:264) 
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
    at java.lang.Thread.run(Thread.java:856) 
Could not connect to this device 

나는 마우스 오른쪽 즉, 각 연결에 대해 다른 UUID를 가질 필요가 읽었습니다? 어쨌든, 새로운 연결마다 배열에서 다른 UUID를 가져 와서 아래와 같이 코드를 작성했습니다.

// Unique UUID for this application 
    private static int indexUUID = 0; 
    private static final UUID[] MY_UUID_SECURE = {UUID.fromString("98b97e6b-62ff-4a36-a81b-82256fd1d168"), 
                UUID.fromString("98b97e6b-62ff-4a36-a81b-82256fd1d169"), 
                UUID.fromString("98b97e6b-62ff-4a36-a81b-82256fd1d170"), 
                UUID.fromString("98b97e6b-62ff-4a36-a81b-82256fd1d171"), 
                UUID.fromString("98b97e6b-62ff-4a36-a81b-82256fd1d172")}; 
    private static final String NAME_SECURE = "GridFrameworkSecure"; 

    /** 
    * Method to connect securely to Bluetooth device using it's MAC address 
    * @param macAddress valid Bluetooth MAC address 
    */ 
    public boolean connectSecurelyToDevice(BluetoothAdapter btAdapter, String macAddress){ 
     BluetoothDevice device = btAdapter.getRemoteDevice(macAddress); 
     ConnectAsyncTask connectTask = new ConnectAsyncTask(); 
     BluetoothSocket deviceSocket = null; 
     try { 
      deviceSocket = connectTask.execute(device).get(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
      return false; 
     } catch (ExecutionException e) { 
      e.printStackTrace(); 
      return false; 
     } 
     if(deviceSocket!=null){ 
      if(serverBluetoothNode==null){ 
       try { 
        serverBluetoothNode = new BluetoothNode(deviceSocket); 
        Log.i("bluetooth manager", "You are now a slave node."); 


        return true; 
       } catch (IOException e) { 
        e.printStackTrace(); 
        return false; 
       } 
      } else { 
       Log.e("bluetooth manager", "You already have a master."); 
       return false; 
      } 
     } else return false; 
    } 

    /** 
    * Method to allow this Bluetooth device to accept connection from another Bluetooth device 
    */ 
    public void allowSecureConnectionFromRemoteDevice(BluetoothAdapter btAdapter){ 
     AcceptConnectionAsyncTask acceptTask = new AcceptConnectionAsyncTask(); 
     acceptTask.execute(btAdapter); 
    } 

    private class ConnectAsyncTask extends AsyncTask<BluetoothDevice, Void, BluetoothSocket> { 

     @Override 
     protected BluetoothSocket doInBackground(BluetoothDevice... params) { 
      BluetoothDevice device = params[0]; 
      BluetoothSocket socket = null; 

      // Get a BluetoothSocket for a connection with the 
      // given BluetoothDevice 
      try { 
       socket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE[indexUUID]); 
      } catch (IOException e) { 
       Log.e("Bluetooth Pairing", "create() failed", e); 
      } 

      Log.i("Bluetooth Pairing", "BEGIN ConnectThread SocketType: Secure"); 

      // Make a connection to the BluetoothSocket 
      try { 
       // This is a blocking call and will only return on a 
       // successful connection or an exception 
       socket.connect(); 
       Log.i("bluetooth manager", "You have connected a slave node to this one."); 

       return socket; 
      } catch (IOException e) { 
       Log.e("Bluetooth Pairing", "Socket closed. Unable to complete pairing.", e); 
       // Close the socket 
       try { 
        socket.close(); 
        indexUUID++; 
       } catch (IOException e2) { 
        Log.e("Bluetooth Pairing", "unable to close() socket during connection failure", e2); 
       } 
      } 

      return null; 
     } 

    } 

    private class AcceptConnectionAsyncTask extends AsyncTask<BluetoothAdapter, Void, Void> { 

     @Override 
     protected Void doInBackground(BluetoothAdapter... params) { 
      BluetoothServerSocket serverSocket = null; 
      String socketType = "Secure"; 

      // Create a new listening server socket 
      try { 
       serverSocket = params[0].listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE[indexUUID]); 
      } catch (IOException e) { 
       Log.e("Accept Bluetooth Pairing Thread", "Socket Type: " + socketType + "listen() failed", e); 
       indexUUID++; 
      } 

      Log.d("Accept Bluetooth Pairing Thread", "Socket Type: " + socketType + 
        "BEGIN mAcceptThread" + this); 

      BluetoothSocket socket = null; 

      // Listen to the server socket if we're not connected 
      while (true) { //mState != STATE_CONNECTED) { 
       try { 
        // This is a blocking call and will only return on a 
        // successful connection or an exception 
        socket = serverSocket.accept(); 
        Log.i("Slave", "server socket found");      

        // If a connection was accepted 
        if (socket != null) { 
         BluetoothNode node = null; 
         try { 
          node = new BluetoothNode(socket); 
          Log.i("connected to", node.getDeviceInformation()); 
          slaveBluetoothNodes.add(node); 

          indexUUID++; 
        serverSocket = params[0].listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE[indexUUID]); 

         } catch (IOException e) { 
          e.printStackTrace(); 

          indexUUID++; 
          serverSocket = params[0].listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE[indexUUID]); 
         } 
        } 
       } catch (IOException e) { 
        Log.e("Accept Bluetooth Pairing Thread", "Socket Type: " + socketType + "accept() failed", e); 

        try { 
         indexUUID++; 
         serverSocket = params[0].listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE[indexUUID]); 
        } catch (IOException e1) { 
         Log.e("Accept Bluetooth Pairing Thread", "Socket Type: " + socketType + "listen() failed", e1); 
        } 
       } 


      } 
     } 

    } 

그러나 그렇다고하더라도, 나는 내가 다음과 같이 이미 두 번째 장치로 작동하는 블루투스 연결이 하나에 연결하기 위해 노력하고있어 세 번째 모바일에 다른 오류가 발생합니다.

Socket closed. Unable to complete pairing. 
java.io.IOException: Service discovery failed 
    at android.bluetooth.BluetoothSocket$SdpHelper.doSdp(BluetoothSocket.java:406) 
    at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:217) 
    at com.ablueworld.androidgridcomputingframework.BluetoothManager$ConnectAsyncTask.doInBackground(BluetoothManager.java:270) 
    at com.ablueworld.androidgridcomputingframework.BluetoothManager$ConnectAsyncTask.doInBackground(BluetoothManager.java:1) 
    at android.os.AsyncTask$2.call(AsyncTask.java:185) 
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:138) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 
    at java.lang.Thread.run(Thread.java:1019) 
Could not connect to this device 

아무도 알아낼 수 있습니까? 고맙습니다.

+2

+1 좋은 질문으로 –

+1

+1 메이트에게 감사드립니다. :) – jpmastermind

답변

0

BluetoothAdaptercancelDiscovery()으로 전화하여 소켓 연결을 생성하십시오. 이렇게하면 java.io.IOException: Service discovery failed에있는 문제가 해결 될 수 있습니다.

+0

연결하기 바로 전에 이미 Bluetooth Discovery를 끄고 있습니다. – jpmastermind

+0

이 질문을보십시오. http://stackoverflow.com/questions/8515572/service-discovery-failed-from-android-bluetooth-insecure-rfcomm – Neil

0

문제점에 대한 해결책을 찾아 냈습니다.

BluetoothDevice device = params[0]; 
    BluetoothSocket socket = null; 

    Log.i("Bluetooth Pairing", "BEGIN ConnectThread SocketType: Secure"); 

    // Get a BluetoothSocket for a connection with the 
    // given BluetoothDevice 
    for(int i=0; i<MY_UUID_SECURE.length; i++){ 
     try { 
      socket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE[i]); 
      // This is a blocking call and will only return on a 
      // successful connection or an exception 
      socket.connect(); 
      Log.i("bluetooth manager", "You have connected a slave node to this one."); 

      return socket; 
     } catch (IOException e) { 
      Log.e("Bluetooth Pairing", "create() failed", e); 
      Log.i("Bluetooth Pairing", "trying another UUID"); 
      try { 
       socket.close(); 
      } catch (IOException e2) { 
       Log.e("Bluetooth Pairing", "unable to close() socket during connection failure", e2); 
      } 
     } 
    } 

이를 : 마스터에 연결

UUID[] MY_UUID_SECURE = {UUID.fromString("98b97e6b-62ff-4a36-a81b-82256fd1d168"), 
                UUID.fromString("98b97e6b-62ff-4a36-a81b-82256fd1d169"), 
                UUID.fromString("98b97e6b-62ff-4a36-a81b-82256fd1d170"), 
                UUID.fromString("98b97e6b-62ff-4a36-a81b-82256fd1d171"), 
                UUID.fromString("98b97e6b-62ff-4a36-a81b-82256fd1d172")}; 

BluetoothServerSocket serverSocket = null; 
      BluetoothSocket socket = null; 

      try { 
       // Listen for all UUIDs in array 
       for (int i = 0; i < MY_UUID_SECURE.length; i++) { 
        serverSocket = btAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE[i]); 
        socket = serverSocket.accept(); 
        if (socket != null) { 
         BluetoothNode node = null; 
         node = new BluetoothNode(socket); 
         Log.i("connected to", node.getDeviceInformation()); 
         slaveBluetoothNodes.add(node); 

         // add node to database 
         databaseManager.insertToGridTree(node.getDeviceAddress(), "slave", "active", node.getDeviceName()); 
        }      
       } 
      } catch (IOException e) { 
       Log.e("Accept Bluetooth Pairing Thread", "accept() failed", e); 
      } 

그리고 슬레이브 장치에 대한 방법은 다음 듣고 연결을 할 수있는 방법은

, 나는 이런 식으로 작성했습니다 프로젝트가 이것을 파악하는 데 도움이되었습니다. https://github.com/polyclef/BluetoothChatMulti

희망 사항은 동일한 문제가있는 사용자에게 도움이되기를 바랍니다. :)

관련 문제