蓝牙BroadcastReceiver将不会收到意图

时间:2018-09-26 14:56:14

标签: android bluetooth

我正在运行运行Android One(SDK版本O)的小米MI A1。 我有我的戴尔笔记本电脑和另一台同时启用了蓝牙的小米Mi Note 3。

我有一堂课,应该启用蓝牙,然后扫描附近的可用设备。 所以,我有什么:

public class BluetoothTestService {

    private Context mContext;
    private BroadcastReceiver mBroadcastReceiver;
    private BluetoothAdapter mBluetoothAdapter;

    //...

    private void scanBluetoothDevices(SingleEmitter<Boolean> emitter) {
        if (mContext == null) {
            return;
        }

        BluetoothManager bt = (BluetoothManager) mContext.getSystemService(
                Context.BLUETOOTH_SERVICE);
        if (bt != null) {
            mBluetoothAdapter = bt.getAdapter();
        }
        if (mBluetoothAdapter == null) {
            // Device does not support Bluetooth
            return;
        } 
        else {
            if (!mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.enable();
            }
        }

        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context c, Intent intent) {
                Log.w(TAG, "Received: " + intent.getAction());
                final String action = intent.getAction();
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    Log.w(TAG, "Found device while discovering");
                     // ...
                }
            }
        };

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_CLASS_CHANGED);
        mContext.registerReceiver(mBroadcastReceiver, filter);

        if (ContextCompat.checkSelfPermission(
                mContext, Manifest.permission.ACCESS_COARSE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
            if (mBluetoothAdapter.isDiscovering()) {
                mBluetoothAdapter.cancelDiscovery();
            }
            mBluetoothAdapter.startDiscovery();
        }
        else {
            // ...
        }
    }

我检查了所有代码段中的所有入口,看来应该可以正常工作。问题是,没有获得我的BroadcastReceiver应该处理的Intent(例如ACTION_DISCOVERY_STARTED)。里面的Log.w()甚至无法运行一次。 我还拥有清单文件中的所有权限:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

有什么问题吗?

0 个答案:

没有答案