在PC(客户端)上初始化Android(服务器)和bluecove之间的蓝牙连接

在PC(客户端)上初始化Android(服务器)和bluecove之间的蓝牙连接,第1张

概述我知道还有其他主题,但就我而言,我希望 Android设备将蓝牙连接初始化服务器.我按照文档编写,我用这种方式编写了服务器: private class AcceptThread implements Runnable { private final BluetoothServerSocket mmServerSocket; public AcceptThread() { 我知道还有其他主题,但就我而言,我希望 Android设备将蓝牙连接初始化为服务器.我按照文档编写,我用这种方式编写了服务器:

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:连接失败;

我该如何解决这个问题?

解决方法 使用时我设法找到了一些电话ServiceRecords:

UUID[] uuIDSet = new UUID[1];    uuIDSet[0]=new UUID(0x0100);    int[] attrIDs = { 0x0100 };    System.out.println("\nSearching for service...");    agent.searchServices(attrIDs,clIEnt);

并且您将在serviceSearch之后两次调用lock.notify(),并在servicesdiscovered函数中将其删除.

您还应该查看服务记录并查找您感兴趣的记录.该URL将说明btgoep://或btspp://

搜索for循环时,使用此代码列出服务名称

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.然后它没有注册服务记录.但在那之后它运作得很好.

总结

以上是内存溢出为你收集整理的在PC(客户端)上初始化Android(服务器)和bluecove之间的蓝牙连接全部内容,希望文章能够帮你解决在PC(客户端)上初始化Android(服务器)和bluecove之间的蓝牙连接所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1124297.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存