广播接收器无法在蓝牙搜索中工作

时间:2019-01-04 22:44:42

标签: java android android-intent bluetooth

我想使用广播接收器获取我的手机附近所有已启用的蓝牙设备的列表,调用registerReceiver(mReceiver,filter)但不调用onReceive且没有任何反应。

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

public class MainActivity extends AppCompatActivity {

private ListView listView;
private ArrayList<String> mDeviceList = new ArrayList();
private BluetoothAdapter mBluetoothAdapter;


public static final int MULTIPLE_PERMISSIONS = 10;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = (ListView) findViewById(R.id.listView);
    getAllBluetoothDevices();
}

@Override
protected void onDestroy() {
    unregisterReceiver(mReceiver);
    super.onDestroy();
}

public final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            mDeviceList.add(device.getName() + "\n" + device.getAddress());
            Log.e("BT", device.getName() + "\n" + device.getAddress());
            listView.setAdapter(new ArrayAdapter<String>(context,
                    android.R.layout.simple_list_item_1, mDeviceList));
        }
    }
};

   /*Discover Devices*/
private void getAllBluetoothDevices() {

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    mBluetoothAdapter.startDiscovery();

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

0 个答案:

没有答案