MainActivity
package com.example.lihui.bluetooth; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothProfile; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.UUID; public class MainActivity extends Activity { private static final String TAG = "blueTooth"; //设备的UUID private static final String SERVICE_UUID = "218856a5-5db3-476d-a28a-db30f85144e4"; //DATA_UUID private static final String DATA_UUID = "90f26d01-fccc-4b1f-ab89-266e7d8f26b0"; //CMD_UUID private static final String CMD_UUID = "90f26d00-fccc-4b1f-ab89-266e7d8f26b0"; //官方特征值 private static final String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb"; //设备蓝牙连接flag private static boolean deviceConFlag = false; //预定义搜索的蓝牙设备的UUID private UUID[] serviceUuids = {UUID.fromString(SERVICE_UUID)}; private BluetoothManager mBluetoothManager = null; private BluetoothAdapter mBluetoothAdapter = null; private BluetoothGatt mBluetoothGatt = null; private BluetoothDevice btDevice = null; private SlideButton myBlueToothStatus; private EditText deviceBlueToothName,content,controlContent,receiveContent; private Button connect,disconnect,send,control,searchDevice,receive; //搜寻指定设备蓝牙 Handler handler = new Handler(){ @Override public void handleMessage(Message msg){ if(msg.what == 0x110){ if(mBluetoothAdapter.isEnabled()){ myBlueToothStatus.setChecked(true); Log.i(TAG,"蓝牙设备已开启"); //5s后停止搜索 new Handler().postDelayed(new Runnable() { @Override public void run() { mBluetoothAdapter.stopLeScan(mLeScanCallback); } }, 1000 * 5); mBluetoothAdapter.startLeScan(serviceUuids, mLeScanCallback); }else{ myBlueToothStatus.setChecked(false); Toast.makeText(MainActivity.this,"蓝牙设备未开启",Toast.LENGTH_SHORT).show(); } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //权限控制 PermissionRequest.requestPermission(this); //画面控件初期化 myBlueToothStatus = findViewById(R.id.myBlueToothStatus); deviceBlueToothName = findViewById(R.id.deviceBlueToothN); content = findViewById(R.id.content); controlContent = findViewById(R.id.controlContent); connect = findViewById(R.id.connect); disconnect = findViewById(R.id.disconnect); send = findViewById(R.id.send); control = findViewById(R.id.control); searchDevice = findViewById(R.id.searchDivice); receive = findViewById(R.id.receive); receiveContent = findViewById(R.id.receiveContent); //初期化蓝牙adapter mBluetoothManager =(BluetoothManager)this.getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = mBluetoothManager.getAdapter(); myBlueToothStatus.setOnCheckedListener(new SlideButton.SlideButtonOnCheckedListener() { @Override public void onCheckedChangeListener(boolean isChecked) { if(!isChecked){ //关闭本机蓝牙模块 if(mBluetoothAdapter != null){ mBluetoothAdapter.disable(); } }else{ //打开本机蓝牙模块 if(mBluetoothAdapter != null){ mBluetoothAdapter.enable(); } } } }); //搜寻指定蓝牙设备名 searchDevice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handler.sendEmptyMessage(0x110); } }); connect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { mBluetoothGatt = btDevice.connectGatt(MainActivity.this, false, mGattCallback); } }).start(); } }); disconnect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mBluetoothGatt != null){ mBluetoothGatt.disconnect(); mBluetoothGatt.close(); mBluetoothGatt = null; deviceConFlag = false; } } }); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String msg = content.getText().toString(); sendMessage(msg,DATA_UUID); } }); receive.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setNotification(); } }); control.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String msg = controlContent.getText().toString(); sendMessage(msg,CMD_UUID); } }); } private void setNotification() { BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString(SERVICE_UUID)); BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(DATA_UUID)); mBluetoothGatt.setCharacteristicNotification(characteristic,true); BluetoothGattDescriptor descriptor = characteristic.getDescriptor( UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG)); descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mBluetoothGatt.writeDescriptor(descriptor); } private void sendMessage(final String msg,final String uuid) { if(mBluetoothGatt!=null){ BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString(SERVICE_UUID)); BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(uuid)); characteristic.setValue(msg); mBluetoothGatt.writeCharacteristic(characteristic); mBluetoothGatt.setCharacteristicNotification(characteristic, true); } } //蓝牙扫描回调接口 private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback(){ @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { if (device.getName() == null) { return; } Log.e("--->搜索到的蓝牙名字:", device.getName()); btDevice = device; deviceBlueToothName.setText(device.getName()); } }; // BLE回调操作 private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status,int newState){ super.onConnectionStateChange(gatt, status, newState); if (newState == BluetoothProfile.STATE_CONNECTED) { Log.i(TAG,"连接成功"); deviceConFlag = true; mBluetoothGatt.discoverServices(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { deviceConFlag = false; Log.d(TAG,"连接失败-->" + status); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { super.onServicesDiscovered(gatt, status); if (status == BluetoothGatt.GATT_SUCCESS) { //发现设备,遍历服务,初始化特征 } else { Log.d("TAG","onServicesDiscovered fail-->" + status); } } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status){ super.onCharacteristicRead(gatt, characteristic, status); if (status == BluetoothGatt.GATT_SUCCESS) { // 收到的数据 byte[] receiveByte = characteristic.getValue(); Log.i(TAG,receiveByte.toString()); }else{ Log.d(TAG,"接收数据失败-->" + status); } } @Override public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic){ super.onCharacteristicChanged(gatt, characteristic); Log.i(TAG,"接收到蓝牙设备的消息"); String value = characteristic.getValue().toString(); receiveContent.setText("接收到蓝牙设备的消息:"+value); } /** * 收到BLE终端写入数据回调 * @param gatt * @param characteristic * @param status */ @Override public void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicWrite(gatt, characteristic, status); if (status == BluetoothGatt.GATT_SUCCESS) { Log.i(TAG,"onCharacteristicWrite发送数据成功"); } else { Log.e(TAG,"onCharacteristicWrite发送数据失败"); } } @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { super.onDescriptorWrite(gatt, descriptor, status); if (status == BluetoothGatt.GATT_SUCCESS) { Log.i(TAG,"onDescriptorWrite发送数据成功"); }else{ Log.e(TAG,"onDescriptorWrite发送数据失败"); } } @Override public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) { super.onReadRemoteRssi(gatt, rssi, status); if (status == BluetoothGatt.GATT_SUCCESS) { Log.i(TAG,"onReadRemoteRssi读取数据成功"); }else{ Log.i(TAG,"onReadRemoteRssi读取数据失败"); } } @Override public void onDescriptorRead(BluetoothGatt gatt,BluetoothGattDescriptor descriptor, int status) { super.onDescriptorRead(gatt, descriptor, status); if (status == BluetoothGatt.GATT_SUCCESS) { Log.i(TAG,"onDescriptorRead读取数据成功"); }else{ Log.i(TAG,"onDescriptorRead读取数据失败"); } } }; }
activity_main.xml