2012-12-03 295 views
1

我有一個名爲scan的按鈕,它掃描可用的藍牙設備並製作列表視圖。 當我按下該設備列表中的某個設備時,'調用ConnectThread(BluetoothDevice設備),但如何將單擊的設備地址發送到this.'m使用下面的代碼。在這能夠獲取名稱,但如何獲得地址。將設備地址發送到Android中的ConnectThread(藍牙設備設備) - 藍牙

ListView lv = getListView(); 

     // listening to single list item on click 
     lv.setOnItemClickListener(new OnItemClickListener() { 
      public void onItemClick(AdapterView<?> parent, View view, 
       int position, long id) { 

       mBluetoothAdapter.cancelDiscovery(); 
      // Toast.makeText(getApplicationContext(), "clicked device", 2).show(); 
       String address = mArrayAdapter.get(position); 
       device = mBluetoothAdapter.getRemoteDevice(address); 

       new ConnectThread(device); 
      } 
     }); 

ConnectThread代碼:

private class ConnectThread extends Thread { 
    private final BluetoothSocket mmSocket; 
    private final BluetoothDevice mmDevice; 

    public ConnectThread(BluetoothDevice device) { 
     // Use a temporary object that is later assigned to mmSocket, 
     // because mmSocket is final 
     BluetoothSocket tmp = null; 
     mmDevice = device; 
     Toast.makeText(getApplicationContext(), "device: " + device, 2).show(); 
     // Get a BluetoothSocket to connect with the given BluetoothDevice 
     try { 
      // MY_UUID is the app's UUID string, also used by the server code 
      tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 
     } catch (IOException e) { } 
     mmSocket = tmp; 
    } 
    public void run() { 
     // Cancel discovery because it will slow down the connection 
     mBluetoothAdapter.cancelDiscovery(); 

     try { 
      // Connect the device through the socket. This will block 
      // until it succeeds or throws an exception 
      mmSocket.connect(); 
     } catch (IOException connectException) { 
      // Unable to connect; close the socket and get out 
      try { 
       mmSocket.close(); 
      } catch (IOException closeException) { } 
      return; 
     } 

     // Do work to manage the connection (in a separate thread) 
     // manageConnectedSocket(mmSocket); 
    } 

    /** Will cancel an in-progress connection, and close the socket */ 
    public void cancel() { 
     try { 
      mmSocket.close(); 
     } catch (IOException e) { } 
    } 
} 

回答

1

我找到答案了這個問題。當我在列表視圖中單擊項目時使用下面的代碼。

 ListView lv = getListView(); 

     // listening to single list item on click 
     lv.setOnItemClickListener(new OnItemClickListener() { 
      public void onItemClick(AdapterView<?> parent, View view, 
       int position, long id) { 

       mBluetoothAdapter.cancelDiscovery(); 

       String info = mArrayAdapter.get(position); 
       String address = info.substring(info.length() - 17); 
       device = mBluetoothAdapter.getRemoteDevice(address); 
       new ConnectThread(device); 

      } 
     });