繁体   English   中英

除了使用BroadcastReceiver,还有其他发现蓝牙的方法吗?

[英]Is there any other way to discover Bluetooth apart from using BroadcastReceiver?

我已经在服务中为BluetoothDevice.ACTION_FOUND创建了BroadcastReceiver,以扫描和记录可用的Bluetooth设备。 该服务的一部分是每30秒检查一次以前找到的蓝牙设备是否仍然可用。 目前,它为我的Leaked IntendReceiver引发了一个错误,我可以修复该错误,但是我只是不确信这是正确的方法。 我正在创建一个新线程来处理蓝牙扫描,创建了一个每30秒运行一次的while循环,并在该循环内注册了BroadcastReceiver,使线程进入睡眠状态,直到睡眠时间超过onReceive时,我才能得到当前扫描的结果,然后我取消注册BroadcastReceiver并重复循环。

我在while循环的每个完成之后都注销了BroadcastReceiver,因为下一次扫描会向我提供当前可用设备的列表,然后将其与上一次扫描的数据进行比较。

它可以满足我的要求,但是我强烈感觉到它不是正确的设计。 您能给我建议另一种方法吗? 谢谢..

以下是来自服务的相关代码-

 class ScanBT extends Thread 
{
     static final long DELAYBT = 30000;

        @Override       
        public void run()
          {

            isBTRunning = true;
            Looper.prepare(); 
            BluetoothAdapter mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();

            try { 
                Log.d(TAG, "BT Scanning started");

                while(isBTRunning)
                { 

                if (!mBluetoothAdapter.isEnabled())
                {
                        mBluetoothAdapter.enable();                     
                        Thread.sleep(15000);                    
                }

                IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
                registerReceiver(mReceiver, filter);

                mBluetoothAdapter.startDiscovery();
                Log.d(TAG,"Inside while loop for BT");
                Thread.sleep(DELAYBT);
                unregisterReceiver(mReceiver);
             }
                Looper.loop();
            }
            catch (InterruptedException e) {
                Log.d(TAG, "BT Scanning stopped");
                    Looper.myLooper().quit();
            }

          }     
}

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                        BTDevice =  device.getName(); 
                BTAddress = device.getAddress();
                Log.d(TAG,"BT Found name: " + BTDevice);
                Log.d(TAG,"BT Found address: " + BTAddress);
                        //Code to compare with previous scan results
            }
        }
    };

弄清楚了。 没有其他方法可以实现这一目标。 为了控制性能,我现在只注册一次接收器,然后在睡眠间隔为60秒的循环内启动发现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM