蓝牙( Bluetooth® )通讯第一篇,建立通信和发送文字音讯

一:简介

一:简介

      
当两台android设备健康连接后,搜索与连接小说在此地(蓝牙5.0搜索与连接),各自需求敞开一个服务端和客户端接收音信(类似于socket),两台设备亟需邦定同二个通信标识,日常是3个uuid。如:00001十一-0000-一千-7000-00805F九B3四FB

      
当两台android设备日常连接后,搜索与连接小说在这里(蓝牙( Bluetooth® )搜索与连接),各自须求开启2个服务端和客户端接收音信(类似于socket),两台设备亟需邦定同三个通讯标识,常常是多个uuid。如:00001十一-0000-一千-7000-0080伍F玖B3四FB

2:创立蓝牙( Bluetooth® )服务端

贰:创立蓝牙伍.0服务端

     1)在已配对的Bluetooth列表,选拔须要通讯的蓝牙( Bluetooth® )设备

     一)在已配对的蓝牙伍.0列表,选用需求通信的Bluetooth设备

    

    

bondDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mBluetoothAdapter.cancelDiscovery();
                ClsUtils.closeDiscoverableTimeout(mBluetoothAdapter);
                final BluetoothDevice bluetoothDevice = bondDevices.get(position);//用户选择的蓝牙设备
                Bundle bun = new Bundle();
                Constant.setBluetoothDevice(bluetoothDevice);
                Intent intent = new Intent(mContenxt, ClientSendMsgAct.class);
                intent.putExtras(bun);
                startActivity(intent);
            }
        });
bondDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mBluetoothAdapter.cancelDiscovery();
                ClsUtils.closeDiscoverableTimeout(mBluetoothAdapter);
                final BluetoothDevice bluetoothDevice = bondDevices.get(position);//用户选择的蓝牙设备
                Bundle bun = new Bundle();
                Constant.setBluetoothDevice(bluetoothDevice);
                Intent intent = new Intent(mContenxt, ClientSendMsgAct.class);
                intent.putExtras(bun);
                startActivity(intent);
            }
        });

   
二)运行贰个线程创设服务端,五个通讯的设施亟需运用同二个蓝牙5.0标识,如:Constant.PPAJEROIVATE_UUID

   
2)运营3个线程创设服务端,五个通讯的设施亟需选拔同3个蓝牙五.0标识,如:Constant.P福睿斯IVATE_UUID

 @Override
    public void run() {
        try {
            adapter = BluetoothAdapter.getDefaultAdapter();
            serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord("myBluetooth", Constant.PRIVATE_UUID);
            mHandler.obtainMessage(CREATE_SUCCESS).sendToTarget();
            while (status) {
                socket = serverSocket.accept();
                doWork();
            }
        } catch (Exception e) {
            e.printStackTrace();
            setActivityMsg(CREATE_FAIL, "创建服务线程出现异常:" + e.getMessage());
        }
    }
 @Override
    public void run() {
        try {
            adapter = BluetoothAdapter.getDefaultAdapter();
            serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord("myBluetooth", Constant.PRIVATE_UUID);
            mHandler.obtainMessage(CREATE_SUCCESS).sendToTarget();
            while (status) {
                socket = serverSocket.accept();
                doWork();
            }
        } catch (Exception e) {
            e.printStackTrace();
            setActivityMsg(CREATE_FAIL, "创建服务线程出现异常:" + e.getMessage());
        }
    }

叁:发送文书音讯

三:发送文书新闻

    一)发送文字音讯前,须要创制三个线程,使用DataOutputStream来发送音讯

    一)发送文字音信前,必要创立一个线程,使用DataOutputStream来发送音信

BluetoothDevice serverDevice;//用户选择的蓝牙设备,详见2.1(在已配对的蓝牙列表,选择需要通信的蓝牙设备)代码
BluetoothSocket socket = serverDevice.createInsecureRfcommSocketToServiceRecord(Constant.PRIVATE_UUID);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
String sendMessage = "nihao";
int f_len = sendMessage.getBytes("UTF-8").length; //消息长度
long totalLen = 4 + 1 + 1 + f_len;//数据的总长度
 byte[] data = new byte[f_len];
data = sendMessage.getBytes("UTF-8");
dataOutputStream.writeLong(totalLen); //1.写入数据的总长度
dataOutputStream.writeByte(type);//2.写入类型
dataOutputStream.writeByte(f_len); //3.写入消息的长度
dataOutputStream.write(data);    //4.写入消息数据
dataOutputStream.flush();
BluetoothDevice serverDevice;//用户选择的蓝牙设备,详见2.1(在已配对的蓝牙列表,选择需要通信的蓝牙设备)代码
BluetoothSocket socket = serverDevice.createInsecureRfcommSocketToServiceRecord(Constant.PRIVATE_UUID);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
String sendMessage = "nihao";
int f_len = sendMessage.getBytes("UTF-8").length; //消息长度
long totalLen = 4 + 1 + 1 + f_len;//数据的总长度
 byte[] data = new byte[f_len];
data = sendMessage.getBytes("UTF-8");
dataOutputStream.writeLong(totalLen); //1.写入数据的总长度
dataOutputStream.writeByte(type);//2.写入类型
dataOutputStream.writeByte(f_len); //3.写入消息的长度
dataOutputStream.write(data);    //4.写入消息数据
dataOutputStream.flush();

 如今是测试,每发送一条音讯运转3个线程,音讯发送也不频仍,所以不会有震慑

 近期是测试,每发送一条音讯运维八个线程,新闻发送也不频仍,所以不会有影响

 BluetoothClientThread bluetoothClientThread = new BluetoothClientThread(clientHandler,mContext,msg,socket);
 new Thread(bluetoothClientThread).start();
 BluetoothClientThread bluetoothClientThread = new BluetoothClientThread(clientHandler,mContext,msg,socket);
 new Thread(bluetoothClientThread).start();

 贰)接收文字音讯是在最早大家创制的,服务端线程里面

 2)接收文字新闻是在最早我们创立的,服务端线程里面

socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
long totalLen = dataInputStream.readLong();//总长度
byte type = dataInputStream.readByte();//类型
 byte len = dataInputStream.readByte();//消息长度
byte[] ml = new byte[len];
int size = 0;
 int receivelen = 0;
 while (receivelen < len) {
   size = dataInputStream.read(ml, 0, ml.length);
    receivelen += size;
 }
msg = new String(ml, "UTF-8");
setActivityMsg(MSG, msg);//将消息回调到activity,并且刷新接收到的消息
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
long totalLen = dataInputStream.readLong();//总长度
byte type = dataInputStream.readByte();//类型
 byte len = dataInputStream.readByte();//消息长度
byte[] ml = new byte[len];
int size = 0;
 int receivelen = 0;
 while (receivelen < len) {
   size = dataInputStream.read(ml, 0, ml.length);
    receivelen += size;
 }
msg = new String(ml, "UTF-8");
setActivityMsg(MSG, msg);//将消息回调到activity,并且刷新接收到的消息

三)发送图片消息

三)发送图片音信

出殡图片音信要求分为两步发送,第二回发图片名称,大小等,首回才发正式发送图片,和soket1样。

出殡图片音讯须求分为两步发送,第2次发图片名称,大小等,第3回才发正式发送图片,和soket1样。

  a)发送图片名称,大小

  a)发送图片名称,大小

 fins=new FileInputStream(Constant.FILE_PATH+imagePath);
long fileDataLen = fins.available(); //文件的总长度
int f_len=imagePath.getBytes("UTF-8").length; //文件名长度
 byte[] data=new byte[f_len];
data=imagePath.getBytes("UTF-8");
 long totalLen = 4+1+1+f_len+fileDataLen;//数据的总长度
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeLong(totalLen); //1.写入数据的总长度
 dataOutputStream.writeByte(type);//2.写入类型
dataOutputStream.writeByte(f_len); //3.写入文件名的长度
 dataOutputStream.write(data);    //4.写入文件名的数据
 dataOutputStream.flush();
 fins=new FileInputStream(Constant.FILE_PATH+imagePath);
long fileDataLen = fins.available(); //文件的总长度
int f_len=imagePath.getBytes("UTF-8").length; //文件名长度
 byte[] data=new byte[f_len];
data=imagePath.getBytes("UTF-8");
 long totalLen = 4+1+1+f_len+fileDataLen;//数据的总长度
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeLong(totalLen); //1.写入数据的总长度
 dataOutputStream.writeByte(type);//2.写入类型
dataOutputStream.writeByte(f_len); //3.写入文件名的长度
 dataOutputStream.write(data);    //4.写入文件名的数据
 dataOutputStream.flush();

  b)正式发送图片

  b)正式发送图片

 FileInputStream fins=new FileInputStream("实际图片路径");
while((size=fins.read(buffer, 0, 1024*10))!=-1)
                {
                    dataOutputStream.write(buffer, 0, size);
                    dataOutputStream.flush();
                    sendlen+=size;
                    i++;
                    if(i%10==0){
                        long time2=Calendar.getInstance().getTimeInMillis();
                        tspeed=sendlen/(time2-time1)*1000/1024;
                    }
                    downbl = ((sendlen * 100) / fileDataLen);
                    Message msg = mHandler.obtainMessage(SEND_PROGRESS);
                    Bundle bun = new Bundle();
                    bun.putFloat("tspeed",downbl);
                    msg.setData(bun);
                    mHandler.sendMessage(msg);//更新发送进度
                }
 FileInputStream fins=new FileInputStream("实际图片路径");
while((size=fins.read(buffer, 0, 1024*10))!=-1)
                {
                    dataOutputStream.write(buffer, 0, size);
                    dataOutputStream.flush();
                    sendlen+=size;
                    i++;
                    if(i%10==0){
                        long time2=Calendar.getInstance().getTimeInMillis();
                        tspeed=sendlen/(time2-time1)*1000/1024;
                    }
                    downbl = ((sendlen * 100) / fileDataLen);
                    Message msg = mHandler.obtainMessage(SEND_PROGRESS);
                    Bundle bun = new Bundle();
                    bun.putFloat("tspeed",downbl);
                    msg.setData(bun);
                    mHandler.sendMessage(msg);//更新发送进度
                }

4)接收图片消息

肆)接收图片音信

收到和殡葬一样,需求分为两步,第一步,接收图片名称,第二步,接收图片流

接收和发送壹样,须求分为两步,第二步,接收图片名称,第1步,接收图片流

a)接收图片名称

a)接收图片名称

byte len = dataInputStream.readByte();//文件名长度
 byte[] fn = new byte[len];
dataInputStream.read(fn);//读取文件名
 String filename = new String(fn, "UTF-8");
byte len = dataInputStream.readByte();//文件名长度
 byte[] fn = new byte[len];
dataInputStream.read(fn);//读取文件名
 String filename = new String(fn, "UTF-8");

b)接收图片流

b)接收图片流

byte[] buffer = new byte[1024 * 1024];
long datalength = totalLen - 1 - 4 - 1 - fn.length;//文件数据
long receivelen = 0;
while (receivelen < datalength) {
                    size = dataInputStream.read(buffer);
                    fileOutputStream.write(buffer, 0, size);
                    receivelen += size;
                    i++;
                    if (i % 10 == 0) {
                        long time2 = Calendar.getInstance().getTimeInMillis();
                        tspeed = receivelen / (time2 - time1) * 1000 / 1024;
       }
    downbl = (receivelen * 100) / datalength;
 }
byte[] buffer = new byte[1024 * 1024];
long datalength = totalLen - 1 - 4 - 1 - fn.length;//文件数据
long receivelen = 0;
while (receivelen < datalength) {
                    size = dataInputStream.read(buffer);
                    fileOutputStream.write(buffer, 0, size);
                    receivelen += size;
                    i++;
                    if (i % 10 == 0) {
                        long time2 = Calendar.getInstance().getTimeInMillis();
                        tspeed = receivelen / (time2 - time1) * 1000 / 1024;
       }
    downbl = (receivelen * 100) / datalength;
 }

 

 

接到文字音信,文本新闻代码停止了。

收取文字音讯,文本音讯代码停止了。

demo代码下载:github

demo代码下载:github