Bluetooth device discovery in Android — startDiscovery()

泄露秘密 提交于 2019-11-29 23:57:39

What context does this method need to be placed within to function properly.

To put it simply, you should use startDiscovery() when you want your application to discover local Bluetooth devices... for instance, if you wanted to implement a ListActivity that scans and dynamically adds nearby Bluetooth devices to a ListView (see DeviceListActivity).

Your usage of the startDiscovery() method should look something like this:

  1. Define a class variable representing the local Bluetooth adapter.

    BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    
  2. Check to see if your device is already "discovering". If it is, then cancel discovery.

    if (mBtAdapter.isDiscovering()) {
        mBtAdapter.cancelDiscovery();
    }
    
  3. Immediately after checking (and possibly canceling) discovery-mode, start discovery by calling,

    mBtAdapter.startDiscovery();
    
  4. Be very careful in general about accidentally leaving your device in discovery-mode. Performing device discovery is a heavy procedure for the Bluetooth adapter and will consume a lot of its resources. For instance, you want to make sure you check/cancel discovery prior to attempting to make a connection. You most likely want to cancel discovery in your onDestroy method too.

Let me know if this helped... and if you are still having trouble, update your answer with your logcat output and/or any error messages you are getting, and maybe I can help you out a bit more.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!