无法建立我的应用程序和远程蓝牙之间的蓝牙连接HC-05

问题描述:

我正在开发一款Android应用程序,它是一种用于一个Arduino设备的远程控制(通过蓝牙工作)。我已经可以将我的手机与远程蓝牙配对。此外,它似乎我可以建立我已经与ACTION_ACL_CONNECTED状态检查这样的连接:无法建立我的应用程序和远程蓝牙之间的蓝牙连接HC-05

private final BroadcastReceiver connectedReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) { 
      showToast("Conneeeeeeeeeeeeected"); 
     } 
    } 
}; 

问题是,当我按我的应用程序将一些数据发送到远程蓝牙按钮,没有任何反应( LED必须将其状态从OFF改变为ON)。你能检查一下有什么不对吗,也许这是我的ConnectThread?这里是我的代码:

public class MainActivity extends AppCompatActivity { 

private final static UUID MY_UUID = UUID.fromString("ecff8f1a-ac66-11e6-80f5-76304dec7eb7"); 

BluetoothSocket mmSocket; 

    Button whiteBtn; // after clicking this button, data from my phone are send to remote bluetooth 
whiteBtn = (Button) findViewById(R.id.white_btn); 
whiteBtn.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 
     whiteBtnOn(); 
    } 
}); 


@Override 
protected void onCreate(Bundle savedInstanceState) { 

    // Get Bluetooth Adapter 
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    if (mBluetoothAdapter == null) { 
     showToast("Bluetooth is not supported on this device"); 
    } 


    // Enable Bluetooth 
    if (!mBluetoothAdapter.isEnabled()) { 
     Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
    } 

    mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrListPaired); 
    pairedListView.setAdapter(mPairedDevicesArrayAdapter); 


    // Find out which devices have been already paired 
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 
    if (pairedDevices.size() > 0) { 
     showToast("Paired devices have been found"); 
     // Loop through the paired devices 
     for (BluetoothDevice device : pairedDevices) { 
      arrListPaired.add(device.getName() + '\n' + device.getAddress()); 
      mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrListPaired); 
     } 
     pairedListView.setAdapter(mPairedDevicesArrayAdapter); 
    } 

    // Click event for items from paired devices list (Possible actions: “Connect”, which establishes connection between my phone and remote Bluetooth, “Unpair”, “Cancel”) 

    pairedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) { 

      final String info = ((TextView) view).getText().toString(); 
      int address = info.indexOf(":"); 
      final String adr = info.substring(address - 2, info.length()); 
      final int positionToRemove = position; 

      final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
      builder.setMessage("What should we do?"); 
      //builder.setMessage("Unpair this device?"); 

      builder.setPositiveButton("Unpair", new OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialogInterface, int i) { 

        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adr); 

        // UNPAIR DEVICES 
        unpair(device); 
        arrListPaired.remove(positionToRemove); 
        mPairedDevicesArrayAdapter.notifyDataSetChanged(); 
        // END UNPAIR DEVICES 
       } 
      }); 

      builder.setNeutralButton("Cancel", new OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialogInterface, int i) { 
        dialogInterface.cancel(); 
       } 
      }); 

// Establish Connection between devices 
      builder.setNegativeButton("Connect", new OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialogInterface, int i) { 
        showToast("Establish connection"); 
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adr); 
        ConnectThread ct = new ConnectThread(device); 
        ct.start(); 
        IntentFilter filter = new IntentFilter(); 
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); 
        registerReceiver(connectedReceiver, filter); 
       } 

      }); 
      AlertDialog alertDialog = builder.create(); 
      alertDialog.show(); 
     } 
    }); 


     @Override 
protected void onPause() { 
    if (mBluetoothAdapter != null) { 
     if (mBluetoothAdapter.isDiscovering()) { 
      mBluetoothAdapter.cancelDiscovery(); 
     } 
    } 
    super.onPause(); 
} 

@Override 
protected void onDestroy() { 
    unregisterReceiver(mReceiver); 
    super.onDestroy(); 
} 


private void showToast(String message) { 
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); 
} 


private void pairDevice(BluetoothDevice device) { 
    try { 
     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED); 
     registerReceiver(receiver, filter); 

     Method method = device.getClass().getMethod("createBond", (Class[]) null); 
     method.invoke(device, (Object[]) null); 

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

    } 
} 

private void unpair(BluetoothDevice device) { 
    showToast("Unpaired button is clicked"); 
    try { 
     if(mmSocket!=null) {mmSocket.close();} 
     Method m = device.getClass().getMethod("removeBond", (Class[]) null); 
     m.invoke(device, (Object[]) null); 
    } catch (NoSuchMethodException e) { 
     e.printStackTrace(); 
    } catch (InvocationTargetException e) { 
     e.printStackTrace(); 
    } catch (IllegalAccessException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 



// Connecting threat 
private class ConnectThread extends Thread { 
    private final BluetoothDevice mmDevice; 

    public ConnectThread(BluetoothDevice device) { 
     BluetoothSocket tmp = null; 
     mmDevice = device; 

     try { 
      tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 
     } catch (IOException e) {} 
     mmSocket = tmp; 
    } 

    public void run() { 
     mBluetoothAdapter.cancelDiscovery(); 

     try { 
      mmSocket.connect(); 
     } catch (IOException connectException) { 

     try { 
       mmSocket.close(); 
      } catch (IOException closeException) {} 
      return; 
     } 
     //manageConnectedSocket(mmSocket); 
    } 
    public void cancel() { 
     try { 
      mmSocket.close(); 
     } catch (IOException e) {} 
    } 
} 


// Managing a connection 

    // Broadcast receiver for connected device 
private final BroadcastReceiver connectedReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) { 
      showToast("Conneeeeeeeeeeeeected"); 
     } 
    } 
}; 


// Send data after clicking on a button 
    private void whiteBtnOn() { 
     if (mmSocket != null) { 
      showToast("White btn is clicked"); 
      try { 
       mmSocket.getOutputStream().write("TO".toString().getBytes()); 
      } 
      catch (IOException e) {} 
     } 
    } 
    } 

} 

在此先感谢您的建议!

+0

从Arduino的最后,我有最简单的草图(点亮LED,如果有来自蓝牙一些进入信息): '/ * LEDs */ int led = 7; void setup(){ pinMode(led,OUTPUT); Serial.begin(9600); } 空隙环(){ 如果(Serial.available()){ digitalWrite(LED,HIGH); } } ' –

尝试使用UUID蓝牙SPP:

private final static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); 

代替:

private final static UUID MY_UUID = UUID.fromString("ecff8f1a-ac66-11e6-80f5-76304dec7eb7"); 
+0

谢谢,它对我很有帮助)但是因为我是新来的编码,请你解释我在哪里发现你的UUID是“00001101-0000-1000-8000-00805f9b34fb”我有,我使用在线生成器生成。谢谢 –

+0

“它为我工作)” - 所以你可以接受(并upvote)我的答案:)关于UUID:你应该使用不自定义和唯一的UUID,但UUID适当的蓝牙配置文件。 HC-05是BT SPP设备,因此您应该使用该配置文件的UUID。例如,查看[this](https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html)“提示:如果您要连接到蓝牙串行板,请尝试使用着名的SPP UUID 00001101-0000-1000-8000-00805F9B34FB。但是,如果您要连接到Android对等方,请生成您自己的唯一UUID。“ –

+0

感谢您的解释! –