NFC对蓝牙连接Android双向套接字问题

时间:2013-09-24 13:22:03

标签: android bluetooth nfc bidirectional

您好我想使用蓝牙和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 个答案:

答案 0 :(得分:1)

通过蓝牙地址假定您在未事先配对蓝牙设备的情况下进行连接。根据您是否要将两个设备配对,您可以通过两种方式实现:

  1. 没有配对。如how to create insecure server connection in Android中所述,在客户端上使用createInsecureRfcommSocketToServiceRecord()代替createRfcommSocketToServiceRecord()。在服务器上使用listenUsingInsecureRfcommWithServiceRecord()

  2. 与安全简单配对配对,通过NFC传递OOB。这是一个更加复杂的过程,超出了你的要求。