2013-02-14 116 views
0

我扫描设备,我想连接到另一个设备“HC-07”,如果它是在范围内或启用我的Android设备。我尝试了一些,但没有连接...任何帮助吗?我用uuid串行连接另一个蓝牙设备...发现后我如何连接到蓝牙设备?

private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){ 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 
     String action = intent.getAction(); 
     if(BluetoothDevice.ACTION_FOUND.equals(action)) { 
      device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 

      short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);//find rssi dBm 

      int pair_state = device.getBondState(); 

      if(device.getName()=="HC-07"){ 
       try { 
       openBT(); 
       Toast.makeText(getBaseContext(),"HC-07 found", Toast.LENGTH_SHORT).show(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
        } 
       } 

      if (pair_state == 12){ pair_str="Paired"; 

      btArrayAdapter.add("Dev name: "+ device.getName() + "\n" + "Mac: " + device.getAddress() + "\n" + "Signal RSSI: " + rssi + "dBm" + "\n"+pair_str); 

      } 

      btArrayAdapter.notifyDataSetChanged(); 

     } 
    }}; 

    void openBT() throws IOException 
    { 
     UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); 
     mmSocket = device.createRfcommSocketToServiceRecord(uuid);  
     mmSocket.connect(); 
     mmOutputStream = mmSocket.getOutputStream(); 
    } 

回答

0

你仔细看了一下提供的BluetoothChat示例吗?这将向您展示如何扫描并连接到蓝牙设备以及如何使用API​​来完成此操作。 http://developer.android.com/resources/samples/BluetoothChat/index.html

检查这方面的例子:

Bluetooth Basics

http://developer.android.com/resources/samples/BluetoothChat/index.html

Code samples for Android Bluetooth programming

http://marakana.com/forums/android/examples/50.html

+0

我readed,但很复杂,我....简单容易一些代码办法? – 2013-02-14 09:21:10

+0

我想要自动连接,如果我的设备是列表... – 2013-02-14 09:23:09

+0

我编辑我的答案 – jlopez 2013-02-14 09:23:09