蓝牙的使用

//蓝牙记得先添加了两个权限
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

public class MainActivity extends Activity {

    private ListView listView;
    private BluetoothAdapter defaultAdapter;
    private ArrayList<BluetoothDevice> deviceList = new ArrayList<BluetoothDevice>();
    private MyBluetoothAdapter myBluetoothAdapter;
    private BroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);
        // 获取蓝牙适配对象
        defaultAdapter = BluetoothAdapter.getDefaultAdapter();
        // 如果蓝牙状态不可用
        // 打开蓝牙设备
        defaultAdapter.enable();
        // 注册广播
        registBluetoothReceiver();

        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {
                try {
                    BluetoothDevice bluetoothDevice = deviceList.get(position);
                    // 未配对,就去配对
                    if (bluetoothDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                        String address = bluetoothDevice.getAddress();
                        // 获取远程设备
                        BluetoothDevice remoteDevice = defaultAdapter
                                .getRemoteDevice(address);
                        // 配对操作
                        // 先获取字节码文件对象
                        Class<BluetoothDevice> clz = BluetoothDevice.class;
                        // 获取方法
                        Method method = clz.getMethod("createBond", null);
                        // 执行配对该方法
                        method.invoke(remoteDevice, null);
                    } else if (bluetoothDevice.getBondState() == bluetoothDevice.BOND_BONDED) {
                        Intent intent = new Intent(MainActivity.this,
                                ChatActivity.class);
                        intent.putExtra("address", bluetoothDevice.getAddress());
                        startActivity(intent);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });
    }

    /**
     * 注册蓝牙广播
     */
    private void registBluetoothReceiver() {
        // 定义一个广播接收器
        receiver = new MyBluetoothReceiver();
        // 创建一个意图过滤器
        IntentFilter filter = new IntentFilter();
        // 注册一个搜素到蓝牙的一个意图action
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        // 添加一个action 监听配对状态改变的一个事件
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);

        registerReceiver(receiver, filter);

    }

    public void search(View v) {
        // 搜寻蓝牙设备 已配对和没有配对的设备
        searchBondedDevices();

        // 搜索未配对设备
        searchUnBondedDevices();
        // 展示设备
        setAdapter();
    }

    /**
     * 搜索未配对设备
     */
    private void searchUnBondedDevices() {
        new Thread() {
            public void run() {
                // 如果当前正在搜素,先停止,开始本次搜索
                if (defaultAdapter.isDiscovering()) {
                    defaultAdapter.cancelDiscovery();
                }
                // 开始搜索,就可以搜索到未配对的设备
                defaultAdapter.startDiscovery();
            };
        }.start();
    }

    /**
     * 设置数据适配器
     */
    private void setAdapter() {
        // 如果适配器为空,创建,设置适配器
        if (myBluetoothAdapter == null) {
            myBluetoothAdapter = new MyBluetoothAdapter(this, deviceList);
            listView.setAdapter(myBluetoothAdapter);
        } else {
            // 刷新适配器
            myBluetoothAdapter.notifyDataSetChanged();
        }

    }

    /**
     * 搜寻已经配对的设备
     */
    private void searchBondedDevices() {
        Set<BluetoothDevice> bondedDevices = defaultAdapter.getBondedDevices();
        for (BluetoothDevice bluetoothDevice : bondedDevices) {
            //如果deviceList集合中不包含已经存在的蓝牙则记录
            if (!deviceList.contains(bluetoothDevice))
                deviceList.add(bluetoothDevice);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            // 反注册广播
            unregisterReceiver(receiver);
            receiver = null;
        }
    }

    // 接收所注册过的action的消息
    class MyBluetoothReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 获取事件类型
            String action = intent.getAction();
            // 获取蓝牙设备
            BluetoothDevice bluetoothDevice = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                // 发现蓝牙设备,发送了这样一个形式的广播
                // sendBroadcast(intent);
                // intent.putExtra(name, value);
                // 获取到蓝牙设备

                // 添加到一开始定义的集合中
                if (!deviceList.contains(bluetoothDevice)) {
                    deviceList.add(bluetoothDevice);
                }
                // 刷新数据适配器
                setAdapter();
            } else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                int bondState = bluetoothDevice.getBondState();
                switch (bondState) {
                    case BluetoothDevice.BOND_NONE:
                        Toast.makeText(MainActivity.this, "配对失败", 0).show();
                        break;
                    case BluetoothDevice.BOND_BONDING:
                        Toast.makeText(MainActivity.this, "正在配对", 0).show();
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        Toast.makeText(MainActivity.this, "配对成功", 0).show();
                        // 重新搜索
                        // searchBondedDevices();
                        // searchUnBondedDevices();
                        // 刷新适配器
                        deviceList.remove(bluetoothDevice);
                        deviceList.add(0, bluetoothDevice);
                        setAdapter();
                        break;
                    default:
                        break;
                }
            }

        }
    }
}

//自定义适配器
public class MyBluetoothAdapter extends BaseAdapter {
    private ArrayList<BluetoothDevice> deviceList;
    private Context context;

    public MyBluetoothAdapter(Context context,
                              ArrayList<BluetoothDevice> deviceList) {
        this.context = context;
        this.deviceList = deviceList;
    }

    @Override
    public int getCount() {
        return deviceList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = View.inflate(context, R.layout.device_item, null);
        TextView tv_address = (TextView) view.findViewById(R.id.tv_address);
        TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
        TextView tv_state = (TextView) view.findViewById(R.id.tv_state);

        tv_address.setText(deviceList.get(position).getAddress());
        tv_name.setText(deviceList.get(position).getName());
        int bondState = deviceList.get(position).getBondState();
        switch (bondState) {
            case BluetoothDevice.BOND_NONE:
                tv_state.setText("未配对");
                tv_state.setTextColor(Color.BLACK);
                break;
            case BluetoothDevice.BOND_BONDING:
                tv_state.setText("正在配对");
                tv_state.setTextColor(Color.RED);
                break;
            case BluetoothDevice.BOND_BONDED:
                tv_state.setText("已配对");
                tv_state.setTextColor(Color.BLUE);
                break;
            default:
                break;
        }

        return view;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值