连接多台设备并实现通信功能
蓝牙连接多台设备
工作有需求,需要android手机通过蓝牙同时连接多台设备,并实时传输数据,废话不多,直接上代码。
public class BluetoothActivity extends AppCompatActivity
implements ConnectListener,MeasuringListener,DeviceListener{
private String TAG = this.getClass().getSimpleName()+"---";
public static final int PERMISSION_LOCATION = 100;
private List<BluetoothDevice> deviceList = new ArrayList<BluetoothDevice>();
private BluetoothDevice mBluetoothDevice;
private BluetoothService2 mBluetoothService;
private BluetoothAdapter mBluetoothAdapter;
private String deviceName1 = "NAME1";//蓝牙名称以此开头
private String deviceName2 = "NAME2";//蓝牙名称以此开头
private String deviceAddress1 = "D8:1A:**:**:**:**";
private String deviceAddress2 = "D8:2B:**:**:**:**";
private int deviceCount = 2;
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBluetoothService = ((BluetoothService2.LocalBinder) service).getService();
mBluetoothAdapter = mBluetoothService.initBluetoothAdapter(BluetoothActivity.this);
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBluetoothService = null;
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if (null != mBluetoothService){
unbindService(mServiceConnection);
Intent intent = new Intent();
intent.setAction("com.zhg.bluetooth.service");
intent.setPackage(getPackageName());
stopService(intent);
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
initUI();
initService();
requestPermission();
}
private void initUI(){
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= 23 && !isLocationOpen(BluetoothActivity.this)) {
Intent enableLocate = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(enableLocate);
}
} else {
Toast.makeText(this,"读取位置权限被禁用", Toast.LENGTH_SHORT).show();
}
break;
}
}
private void initService() {
Intent gattServiceIntent = new Intent(this, BluetoothService2.class);
gattServiceIntent.setAction("com.zhg.bluetooth.service");
startService(gattServiceIntent);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_LOCATION);
}
}
public void onBluetoothClick(View view){
switch (view.getId()){
case R.id.btn_disCover:
//扫描
if (null != mBluetoothAdapter){
mBluetoothAdapter.startDiscovery();
}else {
Log.e(TAG,"134 bluetoothAdapter is null");
}
break;
case R.id.btn_connect:
//链接
// mBluetoothService.connect(device);//连接单个蓝牙
mBluetoothService.connect(deviceList);//连接多个蓝牙
break;
case R.id.btn_disConnect:
//断开链接
mBluetoothService.disConnect();
break;
case R.id.btn_sendCMD:
mBluetoothService.writeCharacteristic(deviceAddress2);
break;
case R.id.btn_sendCMD1:
mBluetoothService.writeCharacteristic(deviceAddress1);
break;
default:
break;
}
}
private boolean isLocationOpen(final Context context){
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//gps定位
boolean isGpsProvider = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//网络定位
boolean isNetWorkProvider = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return isGpsProvider|| isNetWorkProvider;
}
BluetoothDevice device;
@Override
public void onBluetoothDevice(BluetoothDevice device) {
Log.i(TAG,"deviceName is "+device.getName()+"===="+device.getAddress());
if (device.getName()!=null) {
if (device.getName().startsWith(deviceName1) || device.getName().startsWith(deviceName2)){
deviceList.add(device);
if (deviceList.size()==deviceCount) {
mBluetoothAdapter.cancelDiscovery();
}
// this.device =device;//连接一台蓝牙时
// mBluetoothAdapter.cancelDiscovery();
}
}
}
}
public class BluetoothService2 extends Service {
private final String TAG = this.getClass().getName() + ">>>";
private IBinder mBinder = new LocalBinder();
private BluetoothAdapter mBluetoothAdapter;
Map<String,BluetoothGattCharacteristic> map = new HashMap<>();
private ConnectListener mConnectListener;
private MeasuringListener mMeasuringListener;
private DeviceListener mDeviceListener;
MeasuringModel measuringModel = new MeasuringModel();
ConnectModel connectModel = new ConnectModel();
private ArrayMap<String, BluetoothGatt> connMap = new ArrayMap<String, BluetoothGatt>();
@Override
public void onDestroy() {
super.onDestroy();
if (null != mBinder) {
mBinder = null;
}
}
public class LocalBinder extends Binder {
public BluetoothService2 getService() {
return BluetoothService2.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
close();
mBinder = null;
return super.onUnbind(intent);
}
/**
* 关闭
*/
public void close() {
if (null != mReceiver) {
unregisterReceiver(mReceiver);
}
disConnect();
}
public BluetoothAdapter initBluetoothAdapter(Context context) {
BluetoothManager mBluetoothManager;
mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
if (null != mBluetoothManager) {
mBluetoothAdapter = mBluetoothManager.getAdapter();
}
if (null == mBluetoothAdapter) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (null == mBluetoothAdapter) {
return null;
}
}
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
context.startActivity(enableBtIntent);
}
}
registerBroadcast();
return mBluetoothAdapter;
}
private void registerBroadcast(){
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, intentFilter);
}
public void discoveryBluetooth() {
if (null == mBluetoothAdapter) {
Log.e(TAG,"method discoveryBluetooth \n mBluetoothAdapter is null");
return;
}
mBluetoothAdapter.startDiscovery();
}
/**
* 连接蓝牙
* @param deviceList
*/
public boolean connect(List<BluetoothDevice> deviceList) {
if (deviceList!=null && deviceList.size()>0) {
for (int i = 0; i < deviceList.size(); i++) {
BluetoothDevice bluetoothDevice = deviceList.get(i);
if (null == bluetoothDevice || null==bluetoothDevice.getAddress() || null == mBluetoothAdapter) {
Log.e(TAG, "method connect \n connect Bluetooth bluetoothDevice, address or BluetoothAdapter is null : that not initial");
return false;
}
BluetoothGatt gatt = connMap.get(bluetoothDevice.getAddress());
if (gatt != null) {
gatt.disconnect();
gatt.close();
connMap.remove(bluetoothDevice.getAddress());
}
bluetoothDevice.connectGatt(this, false, mGattCallback);
}
}
return true;
}
/**
* 断开蓝牙链接
*/
public void disConnect() {
if (connMap!=null && connMap.size()>0) {
for(BluetoothGatt mBluetoothGatt : connMap.values()){
if (null == mBluetoothAdapter || null == mBluetoothGatt) {
continue;
}
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
}
}
}
public void writeCharacteristic(String address) {
BluetoothGatt bluetoothGatt = connMap.get(address);
BluetoothGattCharacteristic bluetoothGattCharacteristic = map.get(address);
// hex = hex.replaceAll(" ","");
if (null == bluetoothGattCharacteristic || null == bluetoothGatt){
Log.e(TAG, "method writeCharacteristic \n write fail : characteristic or bluetoothGatt is null");
return;
}
bluetoothGatt.setCharacteristicNotification(bluetoothGattCharacteristic, true);
bluetoothGattCharacteristic.setValue("11111".getBytes());
bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
}
/**
* 蓝牙链接回调
*/
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String address = gatt.getDevice().getAddress();
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
System.out.println("连接成功: "+address);
connMap.put(address, gatt);
gatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
if (null != mConnectListener){
connectModel.setConnectStatus(BluetoothProfile.STATE_DISCONNECTED);
connectModel.setConnectMessage("disConnected");
mConnectListener.onBluetoothConnect(connectModel);
}
break;
default:
Log.e(TAG,"method : onConnectionStateChange \n newState is fail : newstate = "+newState);
break;
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (BluetoothGatt.GATT_SUCCESS == status) {
displayGattServices(gatt.getServices(),gatt.getDevice().getAddress());
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
Log.i(TAG,"write is successful");
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
Log.i(TAG, gatt.getDevice().getName()+": --receive Data is successful = "+new String(characteristic.getValue()));
measuringModel.setMeasuringData(BluetoothValueUtil.getInstance().bytesToDemicals(characteristic.getValue()));
mMeasuringListener.onCharacteristicChanged(measuringModel);
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
}
};
/**
* 获取特征值(特征UUID) 用来做与蓝牙通讯的唯一通道
*
* @param gattServices BluetoothGattService
*/
private void displayGattServices(List<BluetoothGattService> gattServices, String address) {
if (gattServices == null) {
Log.e(TAG,"BluetoothGattService list is null");
return;
}
for (BluetoothGattService gattService : gattServices) {
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
for (BluetoothGattCharacteristic characteristic : gattCharacteristics) {
int property = characteristic.getProperties();
if ((property & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0 || (property & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0 ){
if (characteristic.getUuid().toString().equals("0003cdd2-0000-1000-8000-00805f9b0131")) {
map.put(address,characteristic);
notification(characteristic,address);
}
}
if ((property & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
notification(characteristic,address);
}
if ((property & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
notification(characteristic,address);
}
}
}
SystemClock.sleep(2000);
connectModel.setConnectStatus(BluetoothProfile.STATE_CONNECTED);
connectModel.setConnectMessage("已链接");
mConnectListener.onBluetoothConnect(connectModel);
}
private void notification(BluetoothGattCharacteristic gattCharacteristic,String address) {
boolean success = connMap.get(address).setCharacteristicNotification(gattCharacteristic, true);
if (!success) {
Log.e(TAG, "BluetoothGatt setCharacteristicNotification is fail : bluetoothGattCharacteristicUUID = " + gattCharacteristic.getUuid());
return;
}
for (BluetoothGattDescriptor dp : gattCharacteristic.getDescriptors()) {
if (dp == null) {
continue;
}
if ((gattCharacteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
}
connMap.get(address).writeDescriptor(dp);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case BluetoothDevice.ACTION_FOUND:
break;
}
}
};
}
本项目csdn下载地址:https://download.youkuaiyun.com/download/haoguangbei/12658068
github地址:https://github.com/haogb123456/BluetoothDemo1
注:本项目在他人原有项目上进行的功能上新增,详情见github链接。