蓝牙通信,连接,扫描,打开,广播,绑定

1.首先获取本设备蓝牙的适配器(蓝牙的实例,主要的操作对象):

            BluetoothAdapter adapter =BluetoothAdapter.getDefaultAdapter();

2.判断本设备是否支持蓝牙,如果支持,判断是否已经打开,若未打开则打开:

    if(adapter!=null){
        if(!adapter.isEnabled()){
             adapter.enable();//打开蓝牙设备不带提示框

         }
    }

3.蓝牙设备开启扫描功能和被发现功能:

    adapter.startDiscovery();//开启发现功能
    Intent enabler=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    enabler.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//300秒内被发现
    startActivityForResult(enabler,0);//打开被发现功能

4.蓝牙扫描功能开启后,如果发现设备就会触发广播事件(BluetoothDevice.ACTION_FOUND)

    BroadcastReceiver receiver=new BroadcastReceiver(){
        public void onReceive(Context context,Intent intent){
            if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction())){
                //表示搜索到设备   

                  Log.e("Tag", "find device:" + device.getName()
                        + device.getAddress());//打印连接设备的物理地址和名字
                BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXIRA_DEVICE);//获取扫描到的蓝牙设备对象

                if(device.getBondState()!=BluetoothDevice.BOND_BONDED){
                    //如果搜索到的设备与本设备没有配对,则进行此项操作进行配对操作

                }else if(device.getBondState()==BluetoothDevice.BOND_BONDED){
                    //如果搜索到的设备与本设备已经配对过,在这里可以直接连接操作         

                }   
            }

        }
    }

5.蓝牙之间如果需要通信,发送套接字,谷歌提供了BluetoothSocket 这个类,蓝牙通信就要有服务器端和客户端,蓝牙socket连接的时候可以不要进行配对,直接连接,:

*通过同一个UUID进行连接:

服务器端:

BluetoothServerSocket socket = adapter.listenUsingInsecureRfcommWithServiceRecode("XXXXX",UUID);//第一个参数是服务器的名字,第二个是uuid,方法返回BluetoothServerSocket对象

BluetoothSocket serverSocket= socket.accept();//开始接受连接,注意方法是阻塞线程的,所以应该在子线程操作,此时服务器端一直等待客户端的连接才能继续执行下一步,返回对象是连接的serverSocket

客户端:

//当扫描到设备时,在广播中获取到扫描到的设备device获取device对象
BluetoothSocket clientSocket= device.createRfcommSocketToServiceRecord(UUID.fromString(SPP_UUID));//通过与服务器端同一个UUID创建蓝牙客户端套接字
clientSocket.connect();//进行连接,注意此连接同样是阻塞的,所以要在子线程中操作,当连接成功后才能进行下一步操作

收发消息:

//当连接成功后,服务器端和客户端就能发送或者接受消息了,发送消息是通过输入输出流来进行发送

//服务器端发送:

if(serverSocket.isConnected()){//判断socket是否连接
    OutputStream op=serverSocket.getOutPutStream();//获取服务器端的输出流
    op.write("hello world".getBytes());//往输出流中写东西
}

//客户端接收消息:

//根据上面获取的 clientSocket
if(clientSocket.isConnected()){
    InputStream in=clientSocket.getInputStream();//获取输入流
    //读取输入流中的数据
    int len=0;
    byte[] data=new byte[1024];
    while((len=in.read(data))!=-1){
        byte[] b=new byte[len];
        for (int i=0;i

同理,客户端发送内容,服务器接收内容也一样,如果需要实时的接收或者发送,就需要在子线程中开启一个循环,来不断的获取输入流,不断的读取数据;

6.蓝牙进行配对,在扫描结束发现设备的广播中,如果发现新设备且未配对,获取新设备的对象device,调用device.createBond();方法完成配对:

/**
 * Start the bonding (pairing) process with the remote device.
 * 

This is an asynchronous call, it will return immediately. Register * for {@link #ACTION_BOND_STATE_CHANGED} intents to be notified when * the bonding process completes, and its result. *

Android system services will handle the necessary user interactions * to confirm and complete the bonding process. *

Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}. * * @return false on immediate error, true if bonding will begin */ @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN) public boolean createBond() { if (sService == null) { Log.e(TAG, "BT not enabled. Cannot create bond to Remote Device"); return false; } try { return sService.createBond(this, TRANSPORT_AUTO); } catch (RemoteException e) {Log.e(TAG, "", e);} return false; }

源码中,表示这个方法是异步的,如果发生错误,则返回为false,否则返回为true,同时当绑定进程完成后会发送ACTION_BOND_STATE_CHANGED 这个广播,所以如果需要监听绑定状态,需要注册这个广播;

BroadcastReceiver BondReceiver=new BroadcastReceiver(){
    public void onReceive(Context context,Intent intent){
        String action =intent.getAction ();
        BluetoothDevice device;
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        }
        if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
            //表示配对信息
                switch(device.getBondState()){
                    case BluetoothDevice.BOND_BONDING://正在配对
                    break;
                    case BluetoothDevice.BOND_BONDED://配对结束
                    break;
                    case BluetoothDevice.BOND_NONE://取消配对
                    break;
            }
        }
    }

}

7.如果已经配对过,系统里有该设备的mac地址就可以直接进行连接:

BluetoothDevice device=adapter.getRemoteDevice(address);
device.connect();

8.蓝牙开启,关闭,正在打开监听广播,会触发BluetoothDevice.ACTION_STATE_CHANGED

if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
        BluetoothAdapter.ERROR);
switch (state) {
    case BluetoothAdapter.STATE_OFF:
        Log.d("aaa", "STATE_OFF 手机蓝牙关闭");
        break;
    case BluetoothAdapter.STATE_TURNING_OFF:
        Log.d("aaa", "STATE_TURNING_OFF 手机蓝牙正在关闭");
        break;
    case BluetoothAdapter.STATE_ON:
        Log.d("aaa", "STATE_ON 手机蓝牙开启");
        break;
    case BluetoothAdapter.STATE_TURNING_ON:
        Log.d("aaa", "STATE_TURNING_ON 手机蓝牙正在开启");
        break;
}

蓝牙操作结束

你可能感兴趣的:(android)