时间:2021-05-20
在项目中经常用到蓝牙的应用,在这里特意写了一个demo。并且封装了代码,可以主动连接和被动连接一起使用,也可以分开使用。方便后面以后查询使用,也重新踩了部分坑。
项目地址:android实现蓝牙聊天功能
1、程序简单的界面
2、客户端,主动连接
package com.bluetooth.tool; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; //蓝牙连接管理类 public class BluetoothManage { private static final Object mLock = new Object(); //蓝牙类的具体实现核心成员 private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); //蓝牙类的具体数据核心成员 private BluetoothSocket mTransferSocket = null; //当前连接的蓝牙地址 String mstrName = "";//当前连接用到的IP地址 String mstrAddress = "";//当前连接用到的IP地址 //读线程 ReadThread mReadThread = null; //从数据核心成员拿到的输入输出 InputStream mInputStream = null; OutputStream mOutputStream = null; private static BluetoothManage manage = null; public static BluetoothManage getInstance(){ synchronized (BluetoothManage.class){ if(manage == null) manage = new BluetoothManage(); } return manage; } public boolean sendData(int nLength, byte[] data) { if (mOutputStream == null) return false; try { mOutputStream.write(data, 0, nLength); return true; } catch (IOException e) { e.printStackTrace(); } return false; } ConnectListener mConnectListener = null; public void regConnectListener(ConnectListener arg0) { mConnectListener = arg0; } TopDataIOListener mIOListener = null; public void regIOListener(TopDataIOListener arg0) { mIOListener = arg0; } public void unRegIOListener() { mIOListener = null; } public boolean setSelectedDevice(String strDevice) { String[] strings = strDevice.split("\\|"); if (strings.length == 2) { mstrName = strings[0]; mstrAddress = strings[1]; return true; } return false; } public String getSelectedDeviceName() { if (mstrAddress.length() == 0) { return null; } return String.format("%s|%s", mstrName, mstrAddress); } public void connect() { if (mstrAddress.length() == 0) return; final BluetoothDevice device = mBtAdapter.getRemoteDevice(mstrAddress); new Thread(new Runnable() { @Override public void run() { synchronized (mLock) { String strLogString = ""; try { try { mTransferSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); } catch (IOException e1) { mTransferSocket = null; } if (mTransferSocket == null) { if (null != mConnectListener) mConnectListener.OnConnectStatusCallBack(false); return; } long nStartMillTime = System.currentTimeMillis(); //连接 try { mTransferSocket.connect(); } catch (IOException e1) { try { mTransferSocket.close(); } catch (IOException e2) { e2.printStackTrace(); } //等待一定时间 mTransferSocket = null; try { long havePassTime = System.currentTimeMillis() - nStartMillTime; if (havePassTime < 6000) { Thread.sleep(7000 - havePassTime); } } catch (InterruptedException e) { e.printStackTrace(); } } //连接失败 if (mTransferSocket == null) { if (null != mConnectListener) mConnectListener.OnConnectStatusCallBack(false); return; } try { mInputStream = mTransferSocket.getInputStream(); mOutputStream = mTransferSocket.getOutputStream(); mReadThread = new ReadThread(); mReadThread.start(); if (null != mConnectListener) mConnectListener.OnConnectStatusCallBack(true); } catch (IOException e1) { //断开连接 try { if (mTransferSocket != null) mTransferSocket.close(); } catch (IOException e2) { e2.printStackTrace(); } mTransferSocket = null; e1.printStackTrace(); if (null != mConnectListener) mConnectListener.OnConnectStatusCallBack(false); } } catch (Exception e) { //总体异常 if (null != mConnectListener) mConnectListener.OnConnectStatusCallBack(false); } } }//run() }).start(); } //读取数据 class ReadThread extends Thread { public void run() { int nMaxBufLength = 1024; byte[] buffer = new byte[nMaxBufLength]; int byteRead = -1; synchronized (mLock) { while (!isInterrupted()) { try { if (mInputStream != null) { byteRead = mInputStream.read(buffer); if (byteRead > 0 && byteRead <= buffer.length) { if (mIOListener != null) mIOListener.OnIOCallBack(byteRead, buffer); } else { //连接已断开 if (mConnectListener != null) { mConnectListener.OnDisConnectCallBack(); } break; } } else { break; } } catch (IOException e) { //连接已断开 if (mConnectListener != null) { mConnectListener.OnDisConnectCallBack(); } break; } }//while(!isInterrupted()) }//synchronized (mLock) } } //断开蓝牙 public void disConnect() { mConnectListener = null; //结束读线程 if (mReadThread != null) { mReadThread.interrupt(); mReadThread = null; } //取消所有连接 if (mTransferSocket != null) { try { mTransferSocket.close(); if (mInputStream != null) mInputStream.close(); if (mOutputStream != null) mOutputStream.close(); mInputStream = null; mOutputStream = null; mTransferSocket = null; } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { } } } }主动连接应该是比较简单的,一个类就能实现,包括数据的收发。
3、蓝牙服务端,接收蓝牙连接
/** * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://.bluetooth.tool; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.Log; /** * 蓝牙服务,接收蓝牙连接 */ public class BluetoothChat { // Debugging private static final String TAG = "BluetoothChat"; private static final boolean D = true; public static final int MESSAGE_STATE_CHANGE = 1; public static final int MESSAGE_READ = 2; public static final int MESSAGE_WRITE = 3; public static final int MESSAGE_DEVICE_NAME = 4; public static final int MESSAGE_TOAST = 5; // Key names received from the BluetoothChatService Handler public static final String DEVICE_NAME = "device_name"; public static final String TOAST = "toast"; private String mConnectedDeviceName = null; private static StringBuffer mOutStringBuffer; private static BluetoothChatService mChatService = null; private static Context mContext; private volatile static BluetoothChat mBluetoothChat = null; TopDataIOListener mIOListener = null; public static BluetoothChat GetInstance(Context context) { if (mBluetoothChat == null && mContext == null) { synchronized (BluetoothChat.class){ mBluetoothChat = new BluetoothChat(); mContext = context; } } return mBluetoothChat; } public void onStart() { if (mChatService == null) setupChat(); if (mChatService != null) { if (mChatService.getState() == BluetoothChatService.STATE_NONE) { mChatService.start(); } } } private void setupChat() { mChatService = new BluetoothChatService(mContext,mHandler); mOutStringBuffer = new StringBuffer(""); } public void onDestroy() { if (mChatService != null) mChatService.stop(); } public void sendMessage(String message) { if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) { Log.i("Show", ""); return; } if (message.length() > 0) { byte[] send = message.getBytes(); mChatService.write(send); mOutStringBuffer.setLength(0); } } private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_STATE_CHANGE: if (D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1); switch (msg.arg1) { case BluetoothChatService.STATE_CONNECTED: break; case BluetoothChatService.STATE_CONNECTING: break; case BluetoothChatService.STATE_LISTEN: break; case BluetoothChatService.STATE_NONE: break; } break; case MESSAGE_WRITE: byte[] writeBuf = (byte[]) msg.obj; String writeMessage = new String(writeBuf); break; case MESSAGE_READ: byte[] readBuf = (byte[]) msg.obj; //收到的蓝牙数据,回传给界面显示 if (mIOListener != null) mIOListener.OnIOCallBack(readBuf.length, readBuf); break; case MESSAGE_DEVICE_NAME: mConnectedDeviceName = msg.getData().getString(DEVICE_NAME); Log.i(TAG, "MESSAGE_DEVICE_NAME " + mConnectedDeviceName); break; case MESSAGE_TOAST: break; } } }; public void regIOListener(TopDataIOListener arg0) { mIOListener = arg0; } }还有一个蓝牙的广播。这里就不贴代码了。
4、权限
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <!-- 部分手机6.0以上 蓝牙startDiscovery方法需要加上这个权限 --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>蓝牙服务接收广播注册
5、在上面注释看到了有个bug注释
就是部分手机6.0以上 蓝牙蓝牙startDiscovery方法需要加上这个权限android.permission.ACCESS_COARSE_LOCATION。不然启动搜索蓝牙无效。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
bluetooth网络连接未连接的解决方法是首先要确保你的设备和被连接的设备都要支持蓝牙,比如手机和蓝牙耳机都要具备蓝牙功能。然后要把两个设备的蓝牙功能打开,并
要看此创维电视机有没有蓝牙功能。如果没有蓝牙功能的话,是没办法和蓝牙耳机连接的。如果电视机有蓝牙功能的话,可以和蓝牙耳机连接上的。步骤如下: 1、打开电视机找
电视外接音响的方法是: 1、蓝牙连接:分别打开电视机和音箱的蓝牙功能,然后在电视机上搜索当前可识别的蓝牙设备,之后进行配对连接,便可以完美实现外置音箱代替喇叭
要看此创维电视机有没有蓝牙功能。如果没有蓝牙功能的话,是没办法和蓝牙耳机连接的。如果电视机有蓝牙功能的话,可以和蓝牙耳机连接上的。步骤如下: 1、打开电视机找
最近在做一个项目,需要用到android手机连接打印机进行打印的功能,目前在网上找到的教程介绍的都是蓝牙连接热敏打印机(pos机大小的打印机)和蓝牙打印机,如果