首页 \ 问答 \ 服务发现失败了android蓝牙(Service discovery failed android bluetooth)

服务发现失败了android蓝牙(Service discovery failed android bluetooth)

我正在开发一个代码,用于与Micromax Tab的自定义蓝牙电路进行通信。 直到套接字创建它工作正常。 但是,当我尝试连接时,无法说服务发现失败或主机已关闭。 我尝试了所有可能提到相同问题的帖子。 但最终得到同样的错误。 我试图改变UUID,但没有任何作用。 有什么线索吗? 以下是我的代码:

final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
              Toast.makeText(this, "Bluetooth not found",Toast.LENGTH_LONG).show();
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
     // If there are paired devices
     if (pairedDevices.size() > 0) {
         // Loop through paired devices
         for (BluetoothDevice device : pairedDevices) {
             // Add the name and address to an array adapter to show in a ListView
             if(device.getName().equals("linvor"))
             {
                 mmDevice = device;
                 Toast.makeText(this, "Name: " + device.getName() + " And Address: " + device.getAddress(),Toast.LENGTH_LONG).show();
             }

         }
     }
     mBluetoothAdapter.cancelDiscovery();
     BluetoothSocket tmp = null;
    // UUID uuid = UUID.fromString("00001105-0000-1000-8000-00805F9B34FB");

     // MY_UUID is the app's UUID string, also used by the server code
      //  tmp = mmDevice.createRfcommSocketToServiceRecord(uuid);
     Method m = null;
    try {
        m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
        try {
            tmp = (BluetoothSocket) m.invoke(mmDevice, 1);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
        }
    } catch (NoSuchMethodException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
     try {
        tmp = (BluetoothSocket) m.invoke(mmDevice, 1);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
    }


     Toast.makeText(getBaseContext(), "Created socket",Toast.LENGTH_LONG).show();
     mmSocket = tmp;
     mBluetoothAdapter.cancelDiscovery();
     Toast.makeText(getBaseContext(), "Discovery cancelled",Toast.LENGTH_LONG).show();
     try {
         // Connect the device through the socket. This will block
         // until it succeeds or throws an exception
         mmSocket.connect();
         Toast.makeText(getBaseContext(), "Connected",Toast.LENGTH_LONG).show();
     } catch (IOException e1) {
         // Unable to connect; close the socket and get out
         Toast.makeText(getBaseContext(), e1.getMessage(),Toast.LENGTH_LONG).show();
         try {
             mmSocket.close();
         } catch (IOException e) { 
            Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
         }
     }

I am developing a code to communicate to custom bluetooth circuit from Micromax Tab. Till socket creation it works fine. But when i try to connect it fails saying either Service discovery failed or host is down. I tried all the possible posts referring to this topic mentioning same problem. But end up getting same errors. I tried to change UUID but nothing works. Any clues? Below is my code:

final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
              Toast.makeText(this, "Bluetooth not found",Toast.LENGTH_LONG).show();
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
     // If there are paired devices
     if (pairedDevices.size() > 0) {
         // Loop through paired devices
         for (BluetoothDevice device : pairedDevices) {
             // Add the name and address to an array adapter to show in a ListView
             if(device.getName().equals("linvor"))
             {
                 mmDevice = device;
                 Toast.makeText(this, "Name: " + device.getName() + " And Address: " + device.getAddress(),Toast.LENGTH_LONG).show();
             }

         }
     }
     mBluetoothAdapter.cancelDiscovery();
     BluetoothSocket tmp = null;
    // UUID uuid = UUID.fromString("00001105-0000-1000-8000-00805F9B34FB");

     // MY_UUID is the app's UUID string, also used by the server code
      //  tmp = mmDevice.createRfcommSocketToServiceRecord(uuid);
     Method m = null;
    try {
        m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
        try {
            tmp = (BluetoothSocket) m.invoke(mmDevice, 1);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
        }
    } catch (NoSuchMethodException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
     try {
        tmp = (BluetoothSocket) m.invoke(mmDevice, 1);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
    }


     Toast.makeText(getBaseContext(), "Created socket",Toast.LENGTH_LONG).show();
     mmSocket = tmp;
     mBluetoothAdapter.cancelDiscovery();
     Toast.makeText(getBaseContext(), "Discovery cancelled",Toast.LENGTH_LONG).show();
     try {
         // Connect the device through the socket. This will block
         // until it succeeds or throws an exception
         mmSocket.connect();
         Toast.makeText(getBaseContext(), "Connected",Toast.LENGTH_LONG).show();
     } catch (IOException e1) {
         // Unable to connect; close the socket and get out
         Toast.makeText(getBaseContext(), e1.getMessage(),Toast.LENGTH_LONG).show();
         try {
             mmSocket.close();
         } catch (IOException e) { 
            Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_LONG).show();
         }
     }

原文:https://stackoverflow.com/questions/17989555
更新时间:2024-02-23 20:02

最满意答案

我不知道你问题的所有细节,但我的直觉是你可能会在这里思考问题。 您计划在此数据结构中存储多少个对象? 如果您要在此处存储大量数据,我建议您使用实际数据库而不是数据结构。 您在此处描述的操作类型是关系数据库擅长的事物的经典示例。 MySQLPostgreSQL是大规模关系数据库的例子,它们可以在睡眠中做这种事情。 如果你想要一些重量较轻的SQLite可能会引起人们的兴趣。

如果您没有需要存储在此数据结构中的大量数据,我建议您保持简单,只有当您确定它不够快,无法满足您的需求时才进行优化。 作为第一个镜头,我建议使用java内置的List界面来存储你的人物,并使用Map来存储组。 你可以这样做:

// Use a list to keep track of People
List<Person> myPeople = new ArrayList<Person>();
Person steve = new Person("Steve");
myPeople.add(steve);
myPeople.add(new Person("Bob"));


// Use a Map to track Groups
Map<String, List<Person>> groups = new HashMap<String, List<Person>>();
groups.put("Everybody", myPeople);
groups.put("Developers", Arrays.asList(steve));

// Does a group contain everybody?
groups.get("Everybody").containsAll(myPeople); // returns true
groups.get("Developers").containsAll(myPeople); // returns false

这绝对不是最快的选择,但如果你没有大量的人来跟踪,你可能甚至不会注意到任何性能问题。 如果您确实有一些特殊条件会使常规列表和地图的使用速度变得不可行,请发布它们,我们可以根据这些条件提出建议。

编辑:

在阅读您的评论后,我似乎在第一次浏览时误读了您的问题。 看起来你对将人群映射给人们并不是那么感兴趣,而是将人们映射到群组。 你可能想要的是更像这样的东西:

Map<Person, List<String>> associations = new HashMap<Person, List<String>>();

Person steve = new Person("Steve");
Person ed = new Person("Ed");

associations.put(steve, Arrays.asList("Everybody", "Developers"));
associations.put(ed, Arrays.asList("Everybody"));

// This is the tricky part
boolean sharesGroups = checkForSharedGroups(associations, Arrays.asList(steve, ed));

那么如何实现checkForSharedGroups方法呢? 在你的情况下,因为围绕这个的数字非常低,我只是尝试一下天真的方法并从那里开始。

public boolean checkForSharedGroups(
                    Map<Person, List<String>> associations, 
                    List<Person> peopleToCheck){
    List<String> groupsThatHaveMembers = new ArrayList<String>();
    for(Person p : peopleToCheck){
        List<String> groups = associations.get(p);
        for(String s : groups){
            if(groupsThatHaveMembers.contains(s)){
                // We've already seen this group, so we can return
                return false;
            } else {
                groupsThatHaveMembers.add(s);
            }
        }
    }
    // If we've made it to this point, nobody shares any groups.
    return true;
}

这种方法在大型数据集上可能没有很好的性能,但它很容易理解。 因为它封装在它自己的方法中,所以如果事实证明你需要更好的性能,它也应该很容易更新。 如果你确实需要提高性能,我会考虑覆盖Person的equals方法 ,这将使关联映射中的查找更快。 从那里你也可以查看自定义类型而不是组的字符串,也可以使用重写的equals方法。 这将大大加快上面使用的包含方法。

我不太关心性能的原因是,就算法而言,你提到的数字并不是那么大。 因为此方法在找到两个匹配组后立即返回,在最坏的情况下,您将调用ArrayList.contains多次等于存在的组数。 在最好的情况下,它只需要被调用两次。 如果你经常非常频繁地调用checkForSharedGroups,那么性能可能只是一个问题,在这种情况下,你可能最好找到一种不经常调用它的方法,而不是优化方法本身。


I don't know all of the details of your problem, but my gut instinct is that you may be over thinking things here. How many objects are you planning on storing in this data structure? If you have really large amounts of data to store here, I would recommend that you use an actual database instead of a data structure. The type of operations you are describing here are classical examples of things that relational databases are good at. MySQL and PostgreSQL are examples of large scale relational databases that could do this sort of thing in their sleep. If you'd like something lighter-weight SQLite would probably be of interest.

If you do not have large amounts of data that you need to store in this data structure, I'd recommend keeping it simple, and only optimizing it when you are sure that it won't be fast enough for what you need to do. As a first shot, I'd just recommend using java's built in List interface to store your people and a Map to store groups. You could do something like this:

// Use a list to keep track of People
List<Person> myPeople = new ArrayList<Person>();
Person steve = new Person("Steve");
myPeople.add(steve);
myPeople.add(new Person("Bob"));


// Use a Map to track Groups
Map<String, List<Person>> groups = new HashMap<String, List<Person>>();
groups.put("Everybody", myPeople);
groups.put("Developers", Arrays.asList(steve));

// Does a group contain everybody?
groups.get("Everybody").containsAll(myPeople); // returns true
groups.get("Developers").containsAll(myPeople); // returns false

This definitly isn't the fastest option available, but if you do not have a huge number of People to keep track of, you probably won't even notice any performance issues. If you do have some special conditions that would make the speed of using regular Lists and Maps unfeasible, please post them and we can make suggestions based on those.

EDIT:

After reading your comments, it appears that I misread your issue on the first run through. It looks like you're not so much interested in mapping groups to people, but instead mapping people to groups. What you probably want is something more like this:

Map<Person, List<String>> associations = new HashMap<Person, List<String>>();

Person steve = new Person("Steve");
Person ed = new Person("Ed");

associations.put(steve, Arrays.asList("Everybody", "Developers"));
associations.put(ed, Arrays.asList("Everybody"));

// This is the tricky part
boolean sharesGroups = checkForSharedGroups(associations, Arrays.asList(steve, ed));

So how do you implement the checkForSharedGroups method? In your case, since the numbers surrounding this are pretty low, I'd just try out the naive method and go from there.

public boolean checkForSharedGroups(
                    Map<Person, List<String>> associations, 
                    List<Person> peopleToCheck){
    List<String> groupsThatHaveMembers = new ArrayList<String>();
    for(Person p : peopleToCheck){
        List<String> groups = associations.get(p);
        for(String s : groups){
            if(groupsThatHaveMembers.contains(s)){
                // We've already seen this group, so we can return
                return false;
            } else {
                groupsThatHaveMembers.add(s);
            }
        }
    }
    // If we've made it to this point, nobody shares any groups.
    return true;
}

This method probably doesn't have great performance on large datasets, but it is very easy to understand. Because it's encapsulated in it's own method, it should also be easy to update if it turns out you need better performance. If you do need to increase performance, I would look at overriding the equals method of Person, which would make lookups in the associations map faster. From there you could also look at a custom type instead of String for groups, also with an overridden equals method. This would considerably speed up the contains method used above.

The reason why I'm not too concerned about performance is that the numbers you've mentioned aren't really that big as far as algorithms are concerned. Because this method returns as soon as it finds two matching groups, in the very worse case you will call ArrayList.contains a number of times equal to the number of groups that exist. In the very best case scenario, it only needs to be called twice. Performance will likely only be an issue if you call the checkForSharedGroups very, very often, in which case you might be better off finding a way to call it less often instead of optimizing the method itself.

相关问答

更多
  • 为什么不使用DataTable? 它是一种强类型的表格数据结构。 您不需要在数据库的上下文中使用它。 Why not just use a DataTable? It's a strongly typed tabular datastructure. You don't need to use it in the context of a database.
  • 我认为GridBagLayout是实现这一设计的最佳选择。 这是一个完整的工作示例,如下所示: JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.gridx=0; gc.gridy=0; gc.fill = GridBagConstraints.HORIZONT ...
  • 我使用jQuery和以下构造。 employees是一个JS对象数组。 HTML表格是这样准备的:
    StartEndName
    然后使用以下每个 jQuery循环来附加行: $.each(employees, function(index, employee){ $('#clients > tbody').a ...
  • 我不知道你问题的所有细节,但我的直觉是你可能会在这里思考问题。 您计划在此数据结构中存储多少个对象? 如果您要在此处存储大量数据,我建议您使用实际数据库而不是数据结构。 您在此处描述的操作类型是关系数据库擅长的事物的经典示例。 MySQL和PostgreSQL是大规模关系数据库的例子,它们可以在睡眠中做这种事情。 如果你想要一些重量较轻的SQLite可能会引起人们的兴趣。 如果您没有需要存储在此数据结构中的大量数据,我建议您保持简单,只有当您确定它不够快,无法满足您的需求时才进行优化。 作为第一个镜头,我建 ...
  • 使用C结构来表示数据行,然后使用树(或可能是哈希)来表示索引。 您需要解决许多小问题,特别是为了使所有操作都高效,但这构成了内存表的基础。 对于简单的事情,树结构可能就足够了。 Use C structs to represent rows of data and then trees (or maybe hashes) for indexes. There are a lot of little problems you will need to solve, specially in order to ...
  • 为了获得干净的列,您需要使用flex: 1执行两个循环(每列一个) flex: 1 类似的东西: {Object.keys(myArray).map((key, index) => {key})} {Object. ...
  • 您可以使用DefaultTableModel。 它旨在与JTable一起使用,但没有理由不能单独使用它。 您需要添加方法来检索整行或列的数据。 You might be able to use the DefaultTableModel. It was intended to be used with a JTable, but there is no reason it can't be used alone. You would need to add methods to retrieve the d ...
  • 您可以在.NET中使用DataTable 。 它将允许您定义一组类型化列(请参阅Columns属性 )以及添加多个行(请参阅Rows属性 )。 完成后,您可以通过以下方式轻松访问任何行: 指数 列名 表示列的DataColumn实例 但是,请考虑以下事项: 匿名类型的 List (来自LINQ中的查询的投影)或强类型可能同样好,如果不是更好(不需要字符串来获取列),这取决于您的需要(如果你需要从用户输入决定的动态访问,那么使用DataTable会更好)。 如果您只是想要一个交叉矩阵的值,那么匿名类型是 ...
  • 一棵树肯定...... DOM是树结构。 Use the most general definition of a tree: struct HtmlElement { ... /* Tag name, attributes, etc */ struct HtmlElement *pFirstChild; struct HtmlElement *pNextSibling; };

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。