您的位置:首页 > 移动开发 > Android开发

Android之BroadcastReceiver的用法

2015-11-27 15:23 603 查看
BroadcastReceiver为Android的四大组件之一,用于接收系统或自定义的广播事件。以下使用Android自带示例BluetoothChat说明其用法。在该示例中,应用接收系统发送的蓝牙设备发现广播和设备发现完成广播。当然也可以加入对其他广播事件的注册及其处理。使用分为两步:

1. 注册广播接收器

        // Register for broadcasts when a device is discovered

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

        this.registerReceiver(mReceiver, filter);

        // Register for broadcasts when discovery has finished

        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

        this.registerReceiver(mReceiver, filter);

2. 定义广播接收器,重写onReceive方法

    // The BroadcastReceiver that listens for discovered devices and

    // changes the title when discovery is finished

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override

        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);

                // If it's already paired, skip it, because it's been listed already

                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {

                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());

                }

            // When discovery is finished, change the Activity title

            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

                setProgressBarIndeterminateVisibility(false);

                setTitle(R.string.select_device);

                if (mNewDevicesArrayAdapter.getCount() == 0) {

                    String noDevices = getResources().getText(R.string.none_found).toString();

                    mNewDevicesArrayAdapter.add(noDevices);

                }

            }

        }

    };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: