Android 蓝牙(BLE)连接,发送,接收消息

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/myBlueToothName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/my_bluetooth_name"/>

        <com.example.lihui.bluetooth.SlideButton
            android:id="@+id/myBlueToothStatus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:saveEnabled="false"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/device_bluetooth_name"/>

        <EditText
            android:id="@+id/deviceBlueToothN"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:editable="false"
            android:text=""/>

        <Button
            android:id="@+id/searchDivice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="搜寻设备"/>

    </LinearLayout>

    <Button
        android:id="@+id/connect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="连接设备蓝牙"/>

    <Button
        android:id="@+id/disconnect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="断开设备蓝牙"/>

    <EditText
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""/>

    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/device_send"/>

    <EditText
        android:id="@+id/receiveContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:editable="false"/>

    <Button
        android:id="@+id/receive"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/device_receive"/>


    <EditText
        android:id="@+id/controlContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""/>

    <Button
        android:id="@+id/control"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="控制模块"/>

</LinearLayout>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值