java - 使用蓝牙将电脑连接到 Android 手机

标签 java bluetooth bluecove

我想在我的电脑和 Android 手机之间建立蓝牙连接,并想从我的电脑向 Android 手机发送一个字符串。 我正在使用 Bluecove 2.1.0。我能够发现附近的蓝牙设备现在我想配对设备并将字符串从电脑发送到 Android 手机 提前致谢 这是我用于搜索设备的代码

import java.io.OutputStream;
import java.util.ArrayList;

import javax.bluetooth.DataElement;
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.obex.ClientSession;
import javax.obex.HeaderSet;
import javax.obex.Operation;
import javax.obex.ResponseCodes;

    public class MyDiscoveryListener implements DiscoveryListener{

        private static Object lock=new Object();
        public ArrayList<RemoteDevice> devices;

        public MyDiscoveryListener() {
            devices = new ArrayList<RemoteDevice>();
        }

        public static void main(String[] args) {
                    MyDiscoveryListener listener =  new MyDiscoveryListener();

            try{
                LocalDevice localDevice = LocalDevice.getLocalDevice();
                DiscoveryAgent agent = localDevice.getDiscoveryAgent();
                agent.startInquiry(DiscoveryAgent.GIAC, listener);

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


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

               UUID[] uuidSet = new UUID[1];
                uuidSet[0]=new UUID(0x1105); //OBEX Object Push service

                int[] attrIDs =  new int[] {
                        0x0100 // Service name
                };

                for (RemoteDevice device : listener.devices) {
                    agent.searchServices(
                            attrIDs,uuidSet,device,listener);


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


                    System.out.println("Service search finished.");
                }

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



        @Override
        public void deviceDiscovered(RemoteDevice btDevice, DeviceClass arg1) {
            String name;
            try {
                name = btDevice.getFriendlyName(false);
            } catch (Exception e) {
                name = btDevice.getBluetoothAddress();
            }

            devices.add(btDevice);
            System.out.println("device found: " + name);

        }

        @Override
        public void inquiryCompleted(int arg0) {
            synchronized(lock){
                lock.notify();
            }
        }

        @Override
        public void serviceSearchCompleted(int arg0, int arg1) {
            synchronized (lock) {
                lock.notify();
            }
        }

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

                    if(serviceName.getValue().equals("OBEX Object Push")){
                        sendMessageToDevice(url);                
                    }
                } else {
                    System.out.println("service found " + url);
                }


            }
        }

        private static void sendMessageToDevice(String serverURL){
            try{
                System.out.println("Connecting to " + serverURL);

                ClientSession clientSession = (ClientSession) Connector.open(serverURL);
                HeaderSet hsConnectReply = clientSession.connect(null);
                if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
                    System.out.println("Failed to connect");
                    return;
                }

                HeaderSet hsOperation = clientSession.createHeaderSet();
                hsOperation.setHeader(HeaderSet.NAME, "Hello.txt");
                hsOperation.setHeader(HeaderSet.TYPE, "text");

                //Create PUT Operation
                Operation putOperation = clientSession.put(hsOperation);

                // Send some text to server
                byte data[] = "Hello World !!!".getBytes("iso-8859-1");
                OutputStream os =  (putOperation).openOutputStream();
                os.write(data);
                os.close();

                putOperation.close();

                clientSession.disconnect(null);

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




    }

最佳答案

终于找到了
这是我的 github 存储库的链接 https://github.com/kgarg1995/bluetoothtesting MyDiscoveryListener.java 执行所有操作

关于java - 使用蓝牙将电脑连接到 Android 手机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23259693/

相关文章:

java - java中如何响应android的多点触控

java - 是否有适用于 El Capitan 的 javax.bluetooth.* 实现?

java - 无法检测到蓝牙服务(java.lang.NumberFormatException : For input string: "0S" )

java - 我如何避免使用 Thread.sleep()?

java - Netty Http Client : how to separate client-start,发送请求,和client-shutdown分为不同的方法

java - 与父实体一起驱逐依赖集合

c++ - 无法向串口写入数据

android - 使用 BluetoothChat 与 ELM327 通信

java - BlueCove、笔记本电脑和带蓝牙的 Android 平板电脑

java - 使用构建器构建 "partially"可变对象?