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

蓝牙:服务发现失败
EN

Stack Overflow用户
提问于 2013-08-22 10:47:12
回答 2查看 13.7K关注 0票数 4

我试图在我的安卓应用程序(在运行4.1.2:客户端的三星手机上)和我的笔记本电脑(Win7,64位:服务器)之间建立蓝牙连接。它总是失败,服务发现失败。

我读过关于这个的各种主题(这里那里),但是它并没有解决我的问题。

我有两个问题:

  • 什么是众所周知的UUID "00001101-0000-1000-8000-00805F9B34FB“。为什么/什么时候使用它?
  • 任何关于调查/解决我的问题的建议都将不胜感激。

备注:

  • 我试图建立一个安全和不安全的连接(两者都失败)
  • 我能把我的笔记本电脑和Settings>Bluetooth的设备配对
  • 正如注释中所建议的那样:我尝试使用一个随机生成的UUID (但两边的UUID相同),而不是众所周知的UUID,但我仍然有着完全相同的行为。

我有这些权限

代码语言:javascript
复制
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

编辑

我没有在客户端重新编码UUID,而是尝试了以下操作(但仍然得到相同的错误):

代码语言:javascript
复制
UUID uuid = bluetoothDevice.getUuids()[bluetoothDevice.getUuids().length-1].getUuid();

回显服务器的UUID始终是数组中的最后一个。

端编辑

以下是客户端的相关日志:

代码语言:javascript
复制
08-22 12:30:28.627: ERROR/BluetoothService.cpp(12008): stopDiscoveryNative: D-Bus error in StopDiscovery: org.bluez.Error.Failed (Invalid discovery session)
08-22 12:30:28.647: INFO/BluetoothSocket.cpp(18030): Setting Master socket option
08-22 12:30:28.647: VERBOSE/BluetoothSocket.cpp(18030): ...fd 43 created (RFCOMM, lm = 7)
08-22 12:30:28.687: DEBUG/BluetoothPolicyService(12008): getAllowBluetoothDataTransfer - showMsg: true
08-22 12:30:28.687: DEBUG/BluetoothPolicyService(12008): MDM: isProfileEnabled = true
08-22 12:30:28.697: DEBUG/BluetoothUtils(18030): isSocketAllowedBySecurityPolicy start : device null
08-22 12:30:28.727: ERROR/BluetoothEventLoop.cpp(12008): onCreateDeviceResult: D-Bus error: org.bluez.Error.AlreadyExists (Already Exists)
08-22 12:30:28.727: VERBOSE/BluetoothService.cpp(12008): discoverServicesNative
08-22 12:30:28.727: VERBOSE/BluetoothService.cpp(12008): ... Object Path = /org/bluez/12635/hci0/dev_00_09_DD_50_88_54
08-22 12:30:28.727: VERBOSE/BluetoothService.cpp(12008): ... Pattern = , strlen = 0
08-22 12:30:29.138: VERBOSE/BluetoothEventLoop.cpp(12008): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/12635/hci0/dev_00_09_DD_50_88_54
08-22 12:30:29.138: DEBUG/BluetoothEventLoop(12008): Device property changed
08-22 12:30:32.141: DEBUG/BluetoothA2DPStateReceiver(15827): BluetoothA2DPStateReceiver constructor call()
08-22 12:30:32.141: DEBUG/BluetoothA2DPStateReceiver(15827): onReceive(): action = android.bluetooth.device.action.ACL_CONNECTED
08-22 12:30:32.141: DEBUG/BluetoothA2DPStateReceiver(15827): ACTION_ACL_CONNECTED
08-22 12:30:32.141: DEBUG/BluetoothA2DPSinkInfo(15827): checkBlackListCarkit() : isBlackListCarkit false
08-22 12:30:32.161: DEBUG/BluetoothNotiBroadcastReceiver(15910): onReceive
08-22 12:30:40.749: ERROR/Bluetooth(18030): Cannot connect
    java.io.IOException: Service discovery failed
    at android.bluetooth.BluetoothSocket$SdpHelper.doSdp(BluetoothSocket.java:475)
    at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:241)
    at com.company.BlueToothTestActivity.open(BlueToothTestActivity.java:48)
    at com.company.BlueToothTestActivity$1.run(BlueToothTestActivity.java:29)
08-22 12:30:40.749: WARN/Bluetooth(18030): Unable to open connection !

下面是再现错误的代码(它是简化的版本,它编译和再现错误--至少在我的硬件上是这样)。

客户端

代码语言:javascript
复制
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import java.io.IOException;
import java.util.UUID;

public class BlueToothTestActivity extends Activity {

private String macAddress = "00:09:DD:50:88:54";  //hardcoded laptop macAddress
private BluetoothAdapter mBluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket socket;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);   
    Thread bluetoothClientThread = new Thread(){
        @Override
        public void run() {
            if(open()){
                Log.i("Bluetooth","Connection is open !");
            }else{
                Log.w("Bluetooth","Unable to open connection !");
            }
        }
    };
    bluetoothClientThread.start();
    initUI();
}

public boolean open() {
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    bluetoothDevice = mBluetoothAdapter.getRemoteDevice(macAddress);
    String BT_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    try {
        mBluetoothAdapter.cancelDiscovery();
        //socket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(BT_UUID));
        socket = bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(BT_UUID));
        socket.connect(); //Block 12 sec here, then throw the exception.
        return true;
    } catch (IOException e) {
        try {
            socket.close();
        } catch (IOException closeException) { }
        Log.e("Bluetooth", "Cannot connect", e);
        return false;
    }
}

private void initUI(){
    LinearLayout linearLayout = new LinearLayout(this);
    Button finish = new Button(this);
    finish.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            BlueToothTestActivity.this.finish();
        }
    });
    finish.setText("Exit");
    linearLayout.addView(finish);
    setContentView(linearLayout);
}
}

服务器是一个简单的回显服务器(基于Bluecove,我从这里获取了代码:http://www.miniware.net/mobile/articles/viewarticle.php?id=22)

服务器

代码语言:javascript
复制
import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.*;

// sample code from : http://www.miniware.net/mobile/articles/viewarticle.php?id=22   (Nikos Fotiou)
public class EchoServer {
    public final UUID uuid = new UUID("0000110100001000800000805F9B34FB",false);
    public final String name = "EchoServer";                       //the name of the service
    public final String url  =  "btspp://localhost:" + uuid + ";name=" + name  + ";authenticate=false;encrypt=false;";
    LocalDevice local = null;
    StreamConnectionNotifier server = null;
    StreamConnection conn = null;

    public EchoServer() {
    try {
        System.out.println("Setting device to be discoverable...");
        local = LocalDevice.getLocalDevice();
        local.setDiscoverable(DiscoveryAgent.GIAC);
        System.out.println("Start service:"+url);
        server = (StreamConnectionNotifier)Connector.open(url);
        System.out.println("Waiting for incoming connection...");
        conn = server.acceptAndOpen();  // stop and wait here
        System.out.println("Client Connected..."); //never reach this line
        DataInputStream din   = new DataInputStream(conn.openInputStream());
        while(true){
            String cmd = "";
            char c;
            while (((c = din.readChar()) > 0) && (c!='\n') ){
                cmd = cmd + c;
            }
            System.out.println("Received " + cmd);
        }
    } catch (Exception  e) {
        System.err.println("Exception Occured: " + e.toString());
        e.printStackTrace();
    }
}

public static void main (String args[]){
    EchoServer echoserver = new EchoServer();
}

}

服务器pom.xml

代码语言:javascript
复制
<dependencies>
    <dependency>
        <groupId>net.sf.bluecove</groupId>
        <artifactId>bluecove</artifactId>
        <version>2.1.1-SNAPSHOT</version>
    </dependency>
</dependencies>

<repositories>
    <repository>
        <id>pyx4me-web-snapshot</id>
        <url>http://www.pyx4me.com/maven2-snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
        <releases>
            <enabled>false</enabled>
        </releases>
    </repository>
</repositories>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-08-26 08:57:52

尝试使用的UUID是。它可以在如下代码中声明:

代码语言:javascript
复制
private static final UUID BLUETOOTH_SPP_UUID =
                UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

我用Windows 8笔记本电脑和Nexus S尝试了你的代码。首先,我不得不对Nexus上的设备进行配对。然后我启动服务器并使用蓝牙SPP应用程序来测试连接。效果完美无瑕。然后我启动了你的代码,它也起作用了。

当服务器端未启动时,我可以复制“服务发现失败”异常。另外,在我用createRfcommSocket方法扫描了所有30个通道之后,手机上的蓝牙堆栈被破坏了,我不得不重新启动设备。

总之,为了确保你能够沟通:

  1. 在笔记本电脑上,确保蓝牙处于可被发现的状态。
  2. (可选)关闭UAC并使用管理帐户确保您不会遇到任何安全漏洞(我不需要这样做,但在第二次启动时,防火墙必须为eclipse打开以启用调试)
  3. 重新启动电话
  4. 打电话来的一对
  5. 使用SPP UUID,而不是自定义UUID
  6. 通过在System.out.println(local.getBluetoothAddress());调用之前的某个地方添加acceptAndOpen(),确保使用正确的mac地址。
  7. 测试与第三方应用程序的连接从游戏商店。我在命令行模式下使用了这一个。只需要测试连接。
  8. 更新MAC地址并运行应用程序
  9. 应该管用的。

下面是我从运行中得到的输出:

代码语言:javascript
复制
Start service:btspp://localhost:0000110100001000800000805f9b34fb;name=EchoServer;authenticate=false;encrypt=false;
MAC 402CF454215C
Waiting for incoming connection...
Client Connected...
Exception Occured: java.io.EOFException
BlueCove stack shutdown completed
java.io.EOFException
    at java.io.DataInputStream.readChar(Unknown Source)
    at examples.bluetooth_spp_server.EchoServer.<init>(EchoServer.java:30)
    at examples.bluetooth_spp_server.EchoServer.main(EchoServer.java:42)

为了完整起见,以下是在各种条件下返回的错误

  • Windows蓝牙关闭:javax.bluetooth.BluetoothStateException: Bluetooth not detected
  • 安卓蓝牙关闭:java.io.IOException: Unable to start Service Discovery
  • Windows服务器未运行:java.io.IOException: Service discovery failed
  • 未配对:TimeoutException

理论上说,在启动安全连接时,配对应该会自动发生,但在现实中,配对对话框并不是在所有情况下都会出现在电话或Windows中。这是一个不确定性因素,如果失败发生,就需要考虑这个因素。

票数 8
EN

Stack Overflow用户

发布于 2013-08-26 22:47:08

a) UUID是一个串口UUID,主要用于使用不讲SDP协议的设备,例如小型嵌入式RFCOMM设备。

( b)检查你的手机是否打开了蓝牙。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18378340

复制
相关文章

相似问题

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