申请打开蓝牙
<!-- 蓝牙权限 --> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
private final int BLUE_REQUEST_CODE = 551; public void showBLEDialog() {final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(enableIntent, BLUE_REQUEST_CODE); }
申请结果返回。。。。。
@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (requestCode == 551){if (resultCode != RESULT_OK){LgqLogPlus.e("蓝牙返回失败。啦啦啦啦"); // showOpenBlue();}else {}}
1、实现效果
2、主要实现方法
(1)创建服务端:
//先用本地蓝牙适配器创建一个serversocket
serSocket= bluetoothAdapter.listenUsingRfcommWithServiceRecord(bluetoothAdapter.getName(), UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
Utils.sonUiStateMsg("正在等待连接");
if(socket!=null){Utils.sonUiStateMsg("连接成功");}
//等待连接,该方法阻塞
socket=serSocket.accept();
(2)创建客户端
//创建一个socket尝试连接,UUID用正确格式的String来转换而成
socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
Utils.sonUiStateMsg("正在连接,请稍后......");
//该方法阻塞,一直尝试连接
socket.connect();
(3)接收消息线程:
class ReadMsg extends Thread{@Overridepublic void run(){byte[] buffer = new byte[1024];//定义字节数组装载信息int bytes;//定义长度变量InputStream in=null;try {//使用socket获得输入流in = socket.getInputStream();//一直循环接收处理消息while(true){if((bytes=in.read(buffer))!=0){byte[] buf_data = new byte[bytes];for (int i = 0; i < bytes; i++){buf_data[i]=buffer[i];}String msg=new String(buf_data);//最后得到String类型消息Utils.sonUiInfoMsg(msg);TestObServernotice.getInstance().notifyObserver(0,2,msg);}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();Utils.sonUiStateMsg("连接已断开");}finally{try {in.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
}
(4)发送消息方法
OutputStream out=socket.getOutputStream();
out.write(msg.getBytes());//将消息字节发出
3、实现demo
蓝牙搜索,发送消息demo:https://download.csdn.net/download/meixi_android/87165373
demo:Android蓝牙开发,实现发送信息,接收消息demo_蓝牙发送消息app,android蓝牙信息-Android代码类资源-CSDN下载
demo云盘:百度网盘 请输入提取码
在线bug交流:QQ1085220040