2011-09-19 45 views
4

我知道還有其他的話題,但在我的情況下,我想Android設備初始化藍牙連接作爲服務器。我跟着文檔,我這樣寫道服務器:初始化Android(服務器)和電腦(客戶端)上的bluecove之間的藍牙連接

private class AcceptThread implements Runnable { 
    private final BluetoothServerSocket mmServerSocket; 

    public AcceptThread() { 

     BluetoothServerSocket tmp = null; 
     try { 
      tmp = mBluetooth.listenUsingRfcommWithServiceRecord(
        "myService", mUuid); 
     } catch (IOException e) { } 
     mmServerSocket = tmp; 
    } 

    public void run() { 
     BluetoothSocket socket = null; 
     // Keep listening until exception occurs or a socket is returned 
     while (true) { 
      try { 
       System.out.println("SERVER SOCKET LISTENING"); 
       socket = mmServerSocket.accept(); 
      } catch (IOException e) { 
       break; 
      } 
      // If a connection was accepted 
      if (socket != null) { 
       System.out.println("SIGNAL RECEIVED"); 
       // Do work to manage the connection (in a separate thread) 
       Toast.makeText(getApplicationContext(), "SIGNAL RECEIVED", Toast.LENGTH_LONG).show(); 
       try { 
        mmServerSocket.close(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       break; 
      } 
     } 
    } 

    /** Will cancel the listening socket, and cause the thread to finish */ 
    public void cancel() { 
     try { 
      mmServerSocket.close(); 
     } catch (IOException e) { } 
    } 
} 

在另一邊我有發現遠端設備和服務bluecove API。

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.io.PrintWriter; 
import java.util.Vector; 

import javax.bluetooth.DeviceClass; 
import javax.bluetooth.DiscoveryAgent; 
import javax.bluetooth.DiscoveryListener; 
import javax.bluetooth.LocalDevice; 
import javax.bluetooth.RemoteDevice; 
import javax.bluetooth.ServiceRecord; 
import javax.bluetooth.UUID; 
import javax.microedition.io.Connector; 
import javax.microedition.io.StreamConnection; 

/** 
* A simple SPP client that connects with an SPP server 
*/ 
public class SampleSPPClient implements DiscoveryListener{ 

    //object used for waiting 
    private static Object lock=new Object(); 

    //vector containing the devices discovered 
    private static Vector vecDevices=new Vector(); 

    private static String connectionURL=null; 

    public static void main(String[] args) throws IOException { 

     SampleSPPClient client=new SampleSPPClient(); 

     //display local device address and name 
     LocalDevice localDevice = LocalDevice.getLocalDevice(); 
     System.out.println("Address: "+localDevice.getBluetoothAddress()); 
     System.out.println("Name: "+localDevice.getFriendlyName()); 

     //find devices 
     DiscoveryAgent agent = localDevice.getDiscoveryAgent(); 

     System.out.println("Starting device inquiry..."); 
     agent.startInquiry(DiscoveryAgent.GIAC, client); 

     try { 
      synchronized(lock){ 
       lock.wait(); 
      } 
     } 
     catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 


     System.out.println("Device Inquiry Completed. "); 

     //print all devices in vecDevices 
     int deviceCount=vecDevices.size(); 

     if(deviceCount <= 0){ 
      System.out.println("No Devices Found ."); 
      System.exit(0); 
     } 
     else{ 
      //print bluetooth device addresses and names in the format [ No. address (name) ] 
      System.out.println("Bluetooth Devices: "); 
      for (int i = 0; i <deviceCount; i++) { 
       RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(i); 
       System.out.println((i+1)+". "+remoteDevice.getBluetoothAddress()+" ("+remoteDevice.getFriendlyName(true)+")"); 
      } 
     } 

     System.out.print("Choose Device index: "); 
     BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in)); 

     String chosenIndex=bReader.readLine(); 
     int index=Integer.parseInt(chosenIndex.trim()); 

     //check for spp service 
     RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(index-1); 
     UUID[] uuidSet = new UUID[1]; 
     uuidSet[0]=new UUID("4e3aea40e2a511e095720800200c9a66", false); 

     System.out.println("\nSearching for service..."); 
     agent.searchServices(null,uuidSet,remoteDevice,client); 

     try { 
      synchronized(lock){ 
       lock.wait(); 
      } 
     } 
     catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 

     if(connectionURL==null){ 
      System.out.println("Device does not support Simple SPP Service."); 
      System.exit(0); 
     } 

     //connect to the server and send a line of text 
     StreamConnection streamConnection=(StreamConnection)Connector.open(connectionURL); 

     //send string 
     OutputStream outStream=streamConnection.openOutputStream(); 
     PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream)); 
     pWriter.write("Test String from SPP Client\r\n"); 
     pWriter.flush(); 


     //read response 
     InputStream inStream=streamConnection.openInputStream(); 
     BufferedReader bReader2=new BufferedReader(new InputStreamReader(inStream)); 
     String lineRead=bReader2.readLine(); 
     System.out.println(lineRead); 


    }//main 

    //methods of DiscoveryListener 
    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) { 
     //add the device to the vector 
     if(!vecDevices.contains(btDevice)){ 
      vecDevices.addElement(btDevice); 
     } 
    } 

    //implement this method since services are not being discovered 
    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) { 
     System.out.println(servRecord[0].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false)); 
     if(servRecord!=null && servRecord.length>0){ 
      connectionURL=servRecord[0].getConnectionURL(ServiceRecord.AUTHENTICATE_ENCRYPT,false); 
     } 
     synchronized(lock){ 
      lock.notify(); 
     } 
    } 

    //implement this method since services are not being discovered 
    public void serviceSearchCompleted(int transID, int respCode) { 
     synchronized(lock){ 
      lock.notify(); 
     } 
    } 


    public void inquiryCompleted(int discType) { 
     synchronized(lock){ 
      lock.notify(); 
     } 

    }//end method 



} 

客戶端發現了設備和服務,但是當檢索來自ServiceRecord的URL建立失敗的連接。它檢索一個Url,其中的通道錯誤,並引發異常:javax.bluetooth.BluetoothConnectionException:連接失敗;

我該如何解決問題?

+0

難道真的那麼難嗎? –

回答

1

我設法找到一些手機ServiceRecords使用時:

UUID[] uuidSet = new UUID[1]; 
    uuidSet[0]=new UUID(0x0100); 
    int[] attrIds = { 0x0100 }; 

    System.out.println("\nSearching for service..."); 
    agent.searchServices(attrIds, uuidSet, remoteDevice, client); 

而且你會serviceSearch後兩次調用lock.notify(),刪除它在servicesDiscovered功能。

你也應該通過服務記錄,並尋找一個你感興趣的URL將說明btgoep://或btspp://

當通過對循環使用搜索這個代碼列出服務名稱

for(int i = 0; i < servRecord.length; i++) 
{ 
    String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false); 
    DataElement serviceName = srs[i].getAttributeValue(0x0100); 
    if (serviceName != null) { 
     System.out.println("service " + serviceName.getValue() + " found " + url); 
    } else { 
     System.out.println("service found " + url); 
    } 

我有確切的問題,它看起來像Android的API不與SDP註冊ServiceRecord所以Bluecove API可以找到它。 無論我使用什麼UUID,只會發現我的手機註冊爲默認的,我的音頻網關和電話簿OBEX推等。

編輯--- 我有同樣的問題,但意識到我還沒有真正調用listenUsingInsecureRFCOMMSocket呢。然後它沒有註冊服務記錄。 但之後,它工作得很好。

相關問題