Android之蓝牙开发初编(发现蓝牙,配对蓝牙,连接蓝牙)

本文介绍了Android平台下进行蓝牙开发的基本步骤,包括如何添加蓝牙权限,如何搜索附近的蓝牙设备,以及如何进行蓝牙设备的配对和连接操作。通过这些基础知识,开发者可以初步掌握Android蓝牙应用的开发技巧。

1.添加蓝牙权限:

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

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


2.搜索蓝牙(使用BluetoochAdapter)

  BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();//获取蓝牙
if (adapter==null){
     ToastUtil.showToast(context,"该设备不支持蓝牙");
     return;
    }
if (!adapter.isEnabled()){//是否打开蓝牙设备
    Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    context.startActivityForResult(intent,REQUEST_ENABLE);
    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
    context.startActivity(discoverableIntent);
}else {
    Set<BluetoothDevice> sets=adapter.getBondedDevices();
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    context.registerReceiver(mreceiver, filter);
    if (sets.size()>0){//获取已经配备设备
        for (BluetoothDevice device:sets){
        bluetoothDevices.add(device);
        bd=device;
        new ConnectThread().start();
     }
     }else {
         adapter.startDiscovery();
     }
}




3.蓝牙广播:

private static BroadcastReceiver mreceiver = new BroadcastReceiver() {
	        @Override
	        public void onReceive(Context context, Intent intent) {
	            String action = intent.getAction();
	            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
	                bd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	//发现蓝牙设备
	                Log.d("xxx", "find:" + bd.getName());
	                if (bd.getName()!=null){
	                    if (bd.getName().contains("BF4030")){//查找设备名为:BF4030进行配对
	                        if (bd.getBondState()==BluetoothDevice.BOND_NONE){//如果没有配对
	                           //进行配对
	                            try {
	                                Method mm = bd.getClass().getMethod("createBond", (Class[]) null);
	                                mm.invoke(bd, (Object[]) null);//这里会弹出输入pin窗口
	                            }catch (Exception e){
	                                e.printStackTrace();
	                            }
	                        }else if (bd.getBondState()==BluetoothDevice.BOND_BONDED){
	                            new ConnectThread().start();//已经配对进行连接
	                        }
	                    }
	                }
	            }else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){//配对状态的改变
	                bd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	                switch (bd.getBondState()){
	                    case BluetoothDevice.BOND_BONDING:
	                        LogUtil.ShowLog(TAG,"正在配对...");
	                        break;
	                    case BluetoothDevice.BOND_BONDED:
	                        LogUtil.ShowLog(TAG,"完成配对.");
	                        new ConnectThread().start();
	                        break;
	                    case BluetoothDevice.BOND_NONE:
	                        LogUtil.ShowLog(TAG,"取消配对.");
	                        break;
	                }
	            }else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
	                LogUtil.ShowLog(TAG,"已经连接上蓝牙设备");
	            }else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){
	                LogUtil.ShowLog(TAG,"已经断开蓝牙设备");
	            }
	        }
	    };


4.连接蓝牙设备(根据BluetoochDevice)

public static class ConnectThread extends Thread {
        static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
        public ConnectThread() {
            BluetoothSocket tmp = null;
            try {
                tmp=bd.createRfcommSocketToServiceRecord(UUID.fromString(SPP_UUID));
            } catch (IOException e) {
                e.printStackTrace();
            }
            bluesocket = tmp;
        }

        @Override
        public void run() {
            adapter.cancelDiscovery();//取消蓝牙发现
            try {
                if (!bluesocket.isConnected()){
                    bluesocket.connect();//发起连接
                    //连接成功后读取数据
                    handler.sendEmptyMessage(101);//连接成功
                    new ConnectedThread().start();
                }
            } catch (IOException e) {
                handler.sendEmptyMessage(103);//断开连接
            }
        }
    }
 private static class ConnectedThread extends Thread {
        private final InputStream mis;
        private ConnectedThread() {
            InputStream tmpis = null;
            try {
                tmpis = bluesocket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mis = tmpis;
        }

        @Override
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;
            while (true) {
                try {
                    if (bluesocket.isConnected()){
                        bytes = mis.read(buffer);//读取得到的信息发送消息
                        handler.obtainMessage(102,bytes,-1,buffer).sendToTarget();
                    }else {
                        handler.sendEmptyMessage(103);//断开连接
                        return;
                    }
                } catch (IOException e) {
                    handler.sendEmptyMessage(103);//断开连接
                    return;
                }
            }
        }
    }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值