2013-09-24 47 views
0

嗨我想連接兩個Android手機應用程序使用藍牙和NFC。NFC對藍牙連接Android雙向插槽問題

我目前正在通過NFC從一臺設備向另一臺設備發送UUID和MAC; 的問題是,當你要打開我得到以下錯誤插座: 產生java.io.IOException:服務發現失敗

在應用程序的客戶端:

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



    JSONObject oneObject = null; 

    //NFC 
    Intent intent = getIntent(); 

    Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); 

    NdefMessage message = (NdefMessage)messages[0]; 
    NdefRecord record = message.getRecords()[0]; 

    payload = new String(record.getPayload()); 
    String add = null;  
    String uuid = null; 

    try { 
      oneObject = new JSONObject(payload); 
      add = oneObject.getString("MAC"); 
      uuid = oneObject.getString("UUID"); 
    } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

    TextView textView = (TextView) findViewById(R.id.textView); 
    textView.setText(payload); 

    UUID uuid2 = UUID.fromString(uuid); 

    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); 
    this.bluetooth = bluetooth; 

    BluetoothDevice device = bluetooth.getRemoteDevice(add); 
    connectToServerSocket(device, uuid2); 
} 

private void connectToServerSocket(BluetoothDevice device, UUID uuid) { 
     try{ 
     BluetoothSocket clientSocket = device.createRfcommSocketToServiceRecord(uuid); 

     // Block until server connection accepted. 
     clientSocket.connect(); 

     // Start listening for messages. 
     StringBuilder incoming = new StringBuilder(); 
     listenForMessages(clientSocket, incoming); 

     // Add a reference to the socket used to send messages. 
     transferSocket = clientSocket; 

     } catch (IOException e) { 
     Log.e("BLUETOOTH", "Blueooth client I/O Exception", e); 
     } 
    } 

而且在服務器端:

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

    //Bluetooth 


    //NFC 
    jsonObj = getMacAddress(); 
    payload = jsonObj.toString(); 

    nfcAdapter = NfcAdapter.getDefaultAdapter(this); 

    String mimeType = "application/com.example.cpayvendingcomm"; 
    byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII")); 
    NdefMessage nfcMessage = new NdefMessage(
     new NdefRecord[] 
     { 
      // Create the NFC payload. 
      new NdefRecord(
      NdefRecord.TNF_MIME_MEDIA, 
      mimeBytes, 
      new byte[0], 
      payload.getBytes()), 
      // Add the AAR (Android Application Record) 
      //NdefRecord.createApplicationRecord("com.paad.nfcbeam") 
     }); 

    nfcAdapter.setNdefPushMessage(nfcMessage, this); 

    initBluetooth(); 

} 

private static final int ENABLE_BLUETOOTH = 1; 

private void initBluetooth() { 
     if (!bluetooth.isEnabled()) { 
     // Bluetooth isn't enabled, prompt the user to turn it on. 
     Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(intent, ENABLE_BLUETOOTH); 
     } else { 
     // Bluetooth is enabled, initialize the UI. 
     initBluetoothUI(); 
     BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); 
     this.bluetooth = bluetooth; 
     startServerSocket(bluetooth); 
     } 

} 

private void initBluetoothUI() { 
    // TODO Auto-generated method stub 

} 

private ArrayList<BluetoothDevice> deviceList = 
      new ArrayList<BluetoothDevice>(); 

BroadcastReceiver discoveryResult = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
     String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME); 

     BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 

     deviceList.add(remoteDevice); 

     Log.d(TAG, "Discovered " + remoteDeviceName); 
     } 
    }; 

    private BluetoothSocket transferSocket; 

    private UUID startServerSocket(BluetoothAdapter bluetooth) { 
     UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c545"); 
     String name = "bluetoothserver"; 

     try { 
      final BluetoothServerSocket btserver = 
      bluetooth.listenUsingRfcommWithServiceRecord(name, uuid); 

      Thread acceptThread = new Thread(new Runnable() { 
      public void run() { 
       try { 
       // Block until client connection established. 
       BluetoothSocket serverSocket = btserver.accept(); 
       // Start listening for messages. 
       StringBuilder incoming = new StringBuilder(); 
       listenForMessages(serverSocket, incoming); 
       // Add a reference to the socket used to send messages. 
       transferSocket = serverSocket; 
       } catch (IOException e) { 
       Log.e("BLUETOOTH", "Server connection IO Exception", e); 
       } 
      } 
      }); 
      acceptThread.start(); 
     } catch (IOException e) { 
      Log.e("BLUETOOTH", "Socket listener IO Exception", e); 
     } 
     return uuid; 
     } 





    // Listener for messages 
    private boolean listening = false; 

    private void listenForMessages(BluetoothSocket socket, StringBuilder incoming) { 
     listening = true; 

     int bufferSize = 1024; 
     byte[] buffer = new byte[bufferSize]; 

     try { 
     InputStream instream = socket.getInputStream(); 
     int bytesRead = -1; 

     while (listening) { 
      bytesRead = instream.read(buffer); 
      if (bytesRead != -1) { 
      String result = ""; 
      while ((bytesRead == bufferSize) && 
        (buffer[bufferSize-1] != 0)){ 
       result = result + new String(buffer, 0, bytesRead - 1); 
       bytesRead = instream.read(buffer); 
      } 
      result = result + new String(buffer, 0, bytesRead - 1); 
      incoming.append(result); 
      } 
      socket.close(); 
     } 
     } catch (IOException e) { 
     Log.e(TAG, "Message received failed.", e); 
     } 
     finally { 
     } 
    } 

回答

1

傳遞藍牙地址假定您正在連接,而無需事先配對藍牙設備。根據是否要將兩個設備配對,可以採用兩種方法實現:

  1. 沒有配對。如how to create insecure server connection in Android中所述,在客戶端上使用createInsecureRfcommSocketToServiceRecord()而不是createRfcommSocketToServiceRecord()。在服務器上使用listenUsingInsecureRfcommWithServiceRecord()

  2. 配對安全簡單配對,通過NFC傳遞OOB。這是一個更爲複雜的過程,超出了你的要求。