首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android蓝牙中的服务发现失败异常

Android蓝牙中的服务发现失败异常
EN

Stack Overflow用户
提问于 2013-02-15 08:16:47
回答 1查看 1.5K关注 0票数 1

在过去的两天里,我尝试解决了这个问题。我在这个论坛上看到了很多关于这个问题的解决方案,并且尝试了很多类似于ThisThis的解决方案,但是没有luck.For

服务器代码()

代码语言:javascript
复制
public class Main {


    private final LocalDevice mLocalDevice;
    public static void main(String[] args) throws IOException, InterruptedException
    {
        new Main().start();
    }

    public Main() throws IOException
    {
        mLocalDevice = LocalDevice.getLocalDevice();
        mLocalDevice.setDiscoverable(DiscoveryAgent.GIAC);
    }

    public void start() throws IOException
    {
        StreamConnectionNotifier connectionNotifier =(StreamConnectionNotifier) Connector.open("btspp://localhost:" +
                                                                 "0000110100001000800000805F9B34FB;name=BtExample;" +
                                                                     "authenticate=false;encrypt=false;master=false");

        System.out.println("accepting on " + mLocalDevice.getBluetoothAddress());
        StreamConnection streamConnection = connectionNotifier.acceptAndOpen();
        DataInputStream is = streamConnection.openDataInputStream();

        byte[] bytes = new byte[1024];
        int r;
        while ((r = is.read(bytes)) > 0)
        {
             System.out.println(new String(bytes, 0, r));
        }
        streamConnection.close();
    }

}

客户端代码:

代码语言:javascript
复制
    try {
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        Log.d("BT", "getting local device");
          // remote MAC here:
        BluetoothDevice device =mBtAdapter.getRemoteDevice("My_Computer_bluetooth_Address");
        Log.d("BT", "remote device: "+ device.getName().toString());
        Log.d("BT", "connecting to service");

        //Process process = Runtime.getRuntime().exec("su -c 'sdptool records " + device.getAddress() + "'");
        //Log.d("BT", process.toString());
        //Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
        //socket = (BluetoothSocket) m.invoke(device, 1);//I also tried this,but same exception occurs
        //sock=socket;
        BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(
            UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
        Log.d("BT", "about to connect");

        mBtAdapter.cancelDiscovery();
        socket.connect();
        Log.d("BT", "Connected!");

        socket.getOutputStream().write("Hello, world!".getBytes());

} catch (Exception e) {
        Log.e("BT", "Error connecting to device", e);
}

Logcat异常视图:

代码语言:javascript
复制
02-15 14:12:02.022: D/BT(4798): getting local device
02-15 14:12:02.023: D/BT(4798): remote device: SHUVRO-PC    //my PC name
02-15 14:12:02.023: D/BT(4798): connecting to service
02-15 14:12:02.024: I/BluetoothSocket_MTK(4798): [JSR82] Bluetooth Socket Constructor
02-15 14:12:02.024: I/BluetoothSocket_MTK(4798): [JSR82] type=1 fd=-1 auth=false encrypt=false port=-1
02-15 14:12:02.026: D/BT(4798): about to connect
02-15 14:12:02.055: I/BluetoothSocket_MTK(4798): [JSR82] connect: do SDP
02-15 14:12:08.057: I/BluetoothSocket_MTK(4798): [JSR82] SdpHelper::onRfcommChannelFound: channel=-1
02-15 14:12:08.059: E/BT(4798): Error connecting to device
02-15 14:12:08.059: E/BT(4798): java.io.IOException: Service discovery failed
02-15 14:12:08.059: E/BT(4798):     at android.bluetooth.BluetoothSocket$SdpHelper.doSdp(BluetoothSocket.java:813)
02-15 14:12:08.059: E/BT(4798):     at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:382)
02-15 14:12:08.059: E/BT(4798):     at com.bluetoothTest.BluetoothTestActivity.onClick(BluetoothTestActivity.java:82)
02-15 14:12:08.059: E/BT(4798):     at android.view.View.performClick(View.java:3517)
02-15 14:12:08.059: E/BT(4798):     at android.view.View$PerformClick.run(View.java:14155)
02-15 14:12:08.059: E/BT(4798):     at android.os.Handler.handleCallback(Handler.java:605)
02-15 14:12:08.059: E/BT(4798):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-15 14:12:08.059: E/BT(4798):     at android.os.Looper.loop(Looper.java:137)
02-15 14:12:08.059: E/BT(4798):     at android.app.ActivityThread.main(ActivityThread.java:4508)
02-15 14:12:08.059: E/BT(4798):     at java.lang.reflect.Method.invokeNative(Native Method)
02-15 14:12:08.059: E/BT(4798):     at java.lang.reflect.Method.invoke(Method.java:511)
02-15 14:12:08.059: E/BT(4798):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
02-15 14:12:08.059: E/BT(4798):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
02-15 14:12:08.059: E/BT(4798):     at dalvik.system.NativeStart.main(Native Method)
EN

回答 1

Stack Overflow用户

发布于 2014-03-14 09:55:46

下面是我在客户端用于建立(安全或不安全)连接的最后代码。在我的用例中:一个重要的pinCode意味着目标设备需要一个安全的连接,否则目标设备就会接受一个不安全的连接。

我认为这段代码需要API级别的15+。

代码语言:javascript
复制
private BluetoothAdapter mBluetoothAdapter;
public final String BT_UUID = "00001101-0000-1000-8000-00805F9B34FB";
private BluetoothDevice bluetoothDevice;
private BluetoothSocket socket;

...

public void establishBluetoothConnection(String pinCode) throws IOException {
    //needed because "bluetooth device discovery" may initiated by any other
    // process and there are good chances that the socket.connect() fail when bluetooth discovery process is running.
    mBluetoothAdapter.cancelDiscovery(); 

    if ("".equals(pinCode) || pinCode == null || "0000".equals(pinCode)) {
        socket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(BT_UUID));
    } else {
        setPin(pinCode);
        socket = bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(BT_UUID));
    }
    socket.connect(); //blocking up to timeout of about 12 sec. throws IOException in case of failure
}



/**
 * hack to set the pin code programatically. The android API don't have a public method to set the pin code.
 * that's why we use this hack. In case of failure: android will prompt the user to enter the pin code manually.
 */
private void setPin(String pinCode) {
    try {
        byte[] ar = pinCode.getBytes();
        Method m2 = bluetoothDevice.getClass().getMethod("setPin", new Class[]{byte[].class});
        m2.invoke(bluetoothDevice, ar);
    } catch (NoSuchMethodException e) {
        Log.e("Bluetooth", "Failed to set pin code", e);
    } catch (InvocationTargetException e) {
        Log.e("Bluetooth", "Failed to set pin code", e);
    } catch (IllegalAccessException e) {
        Log.e("Bluetooth", "Failed to set pin code", e);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14890569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档