前一篇文章写了如何显示BLE设备,在子项点击事件中只弹出了一个吐司提示点击的是哪个模块的地址,这一篇就将它改成发送指令

public class MainActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemClickListener{@Overridepublic void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {BluetoothDevice device= (BluetoothDevice) mListViewAdapter.getItem(i);if (device==null)return;Intent intent=new Intent(this,BleAtActivity.class);intent.putExtra("name",device.getName());intent.putExtra("address",device.getAddress());startActivity(intent);}}

跳转到BleAtActivity后,在这个页面放置四个按钮用于发送,连接,断开和改名

ble_at_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><Button
        android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/send_button"/><Button
        android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/connect_button"/><Button
        android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/disconnect_button"/><Button
        android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/edit_name"/></LinearLayout>

延续之前的代码风格,用init函数写onCreate,由于只写发送,不接收,所以代码量很少,也没什么特别的,注意BluetoothLeService不是系统的类,是需要自定义的,用到了其中的一些连接的方法和发送的方法,在后面有全文(Ctrl键+F搜索BluetoothLeService.java和BleSppGattAttributes.java,直接复制即可),我一直没有机会重写它,有机会一定要自己写一个


public class BleAtActivity extends Activity implements View.OnClickListener{private int mLedStatus=0;private Button button;private Button connectButton;private Button disconnectButton;private Button editNameButton;private String mAddressString;private String mNameString;private BluetoothLeService mBluetoothLeService;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.ble_at_layout);initView();initData();initEvent();}@Overrideprotected void onDestroy() {super.onDestroy();unbindService(mServiceConnection);mBluetoothLeService = null;}private void initView(){button=findViewById(R.id.send_button);connectButton=findViewById(R.id.connect_button);disconnectButton=findViewById(R.id.disconnect_button);editNameButton=findViewById(R.id.edit_name);}private void initData(){mAddressString =getIntent().getStringExtra("address");mNameString=getIntent().getStringExtra("name");button.setText("开/关");connectButton.setText("连接");disconnectButton.setText("未连接");editNameButton.setText("改名");}private void initEvent(){button.setOnClickListener(this);connectButton.setOnClickListener(this);disconnectButton.setOnClickListener(this);editNameButton.setOnClickListener(this);Intent intent=new Intent(this,BluetoothLeService.class);bindService(intent,mServiceConnection,BIND_AUTO_CREATE);}@Overridepublic void onClick(View view) {switch (view.getId()){case R.id.send_button:if (mLedStatus==0){sendAt("AT+IO1=H");mLedStatus=1;}else {sendAt("AT+IO1=L");mLedStatus=0;}break;case R.id.connect_button:mBluetoothLeService.connect(mAddressString);break;case R.id.disconnect_button:mBluetoothLeService.disconnect();break;case R.id.edit_name:dialog(mNameString);}}private void dialog(String name){final EditText et = new EditText(this);final AlertDialog.Builder dialog=new AlertDialog.Builder(this);dialog.setTitle("输入"+name+"新名称");dialog.setView(et);dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {dialogInterface.dismiss();sendAt("AT+NAME="+et.getText().toString());}});dialog.setNegativeButton("取消",null);dialog.create().show();}private void sendAt(String s){byte[] buf=s.getBytes();mBluetoothLeService.writeAT(buf);}}

如果你复制完了两个类,而且alt加回车加了所有的类以后,发现还有两个标红的,那么恭喜你,现在到了全篇文章最核心的部分

做一个ServiceConnection,用于绑定服务的第二个参数,主要就是对mBluetoothLeService的操作,根据蓝牙的地址连接到相关的设备,当我们绑定服务时就执行连接方法,这是整篇文章中最复杂的部分,可以按Ctrl键+F键观察mBluetoothLeService的位置

public class BleAtActivity extends Activity implements View.OnClickListener{private ServiceConnection mServiceConnection=new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName componentName, IBinder iBinder) {mBluetoothLeService=((BluetoothLeService.LocalBinder)iBinder).getService();if (!mBluetoothLeService.initialize())finish();mBluetoothLeService.connect(mAddressString);}@Overridepublic void onServiceDisconnected(ComponentName componentName) {mBluetoothLeService=null;}};
}

附录:
BluetoothLeService.java

import android.app.Service;
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.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;import java.util.List;
import java.util.UUID;/*** Service for managing connection and data communication with a GATT server hosted on a* given Bluetooth LE device.*/
public class BluetoothLeService extends Service {private final static String TAG = BluetoothLeService.class.getSimpleName();private BluetoothManager mBluetoothManager;private BluetoothAdapter mBluetoothAdapter;private String mBluetoothDeviceAddress;private BluetoothGatt mBluetoothGatt;//ble characteristicprivate BluetoothGattCharacteristic mNotifyCharacteristic;private BluetoothGattCharacteristic mWriteCharacteristic;private BluetoothGattCharacteristic mATCharacteristic;private int mConnectionState = STATE_DISCONNECTED;private static final int STATE_DISCONNECTED = 0;private static final int STATE_CONNECTING = 1;private static final int STATE_CONNECTED = 2;public final static String ACTION_GATT_CONNECTED ="com.example.bluetooth.le.ACTION_GATT_CONNECTED";public final static String ACTION_GATT_DISCONNECTED ="com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";public final static String ACTION_GATT_SERVICES_DISCOVERED ="com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";public final static String ACTION_DATA_AVAILABLE ="com.example.bluetooth.le.ACTION_DATA_AVAILABLE";public final static String EXTRA_DATA ="com.example.bluetooth.le.EXTRA_DATA";public final static String ACTION_WRITE_SUCCESSFUL ="com.example.bluetooth.le.WRITE_SUCCESSFUL";public final static String ACTION_GATT_SERVICES_NO_DISCOVERED ="com.example.bluetooth.le.GATT_SERVICES_NO_DISCOVERED";//public final static UUID UUID_BLE_SPP_NOTIFY = UUID.fromString(BleSppGattAttributes.BLE_SPP_Notify_Characteristic);public final static UUID UUID_BLE_SPP_NOTIFY_0 = UUID.fromString(BleSppGattAttributes.BLE_SPP_Notify_Characteristic_0);public final static UUID UUID_BLE_SPP_AT = UUID.fromString(BleSppGattAttributes.BLE_SPP_AT_Characteristic);// Implements callback methods for GATT events that the app cares about.  For example,// connection change and services discovered.private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {String intentAction;if (newState == BluetoothProfile.STATE_CONNECTED) {intentAction = ACTION_GATT_CONNECTED;mConnectionState = STATE_CONNECTED;broadcastUpdate(intentAction);Log.i(TAG, "Connected to GATT server.");// Attempts to discover services after successful connection.Log.i(TAG, "Attempting to start service discovery:" +mBluetoothGatt.discoverServices());} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {intentAction = ACTION_GATT_DISCONNECTED;mConnectionState = STATE_DISCONNECTED;Log.i(TAG, "Disconnected from GATT server.");broadcastUpdate(intentAction);}}@Overridepublic void onServicesDiscovered(BluetoothGatt gatt, int status) {if (status == BluetoothGatt.GATT_SUCCESS) {// 默认先使用 B-0006/TL8266 服务发现BluetoothGattService service = gatt.getService(UUID.fromString(BleSppGattAttributes.BLE_SPP_Service));// service.getInstanceId()if (service!=null){//默认找到B-0006/tl8266的服务,继续查找B-0006/tl8266的特征值mNotifyCharacteristic = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_Notify_Characteristic));mWriteCharacteristic  = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_Write_Characteristic));mATCharacteristic  = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_AT_Characteristic));}
//                else
//                {//                    //没有找到,查找是否是B-002/B-0004
//                    service = gatt.getService(UUID.fromString(BleSppGattAttributes.BLE_SPP_Service_0));
//                    if (service !=null)
//                    {//                        mNotifyCharacteristic = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_Notify_Characteristic_0));
//                        mWriteCharacteristic = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_Write_Characteristic_0));
//                    }
//                }//                BluetoothGattService service = gatt.getService(UUID.fromString(BleSppGattAttributes.BLE_SPP_Service_0));
//                mNotifyCharacteristic = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_Notify_Characteristic_0));
//                mWriteCharacteristic  = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_Write_Characteristic_0));if (mNotifyCharacteristic!=null){broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);//使能NotifysetCharacteristicNotification(mNotifyCharacteristic,true);setCharacteristicNotification(mATCharacteristic,true);}if (service==null){Log.v("log","service is null");broadcastUpdate(ACTION_GATT_SERVICES_NO_DISCOVERED);// mBluetoothGatt.discoverServices();}} else {Log.w(TAG, "onServicesDiscovered received: " + status);}}@Overridepublic void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic,int status) {if (status == BluetoothGatt.GATT_SUCCESS) {broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);}}@Overridepublic void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);}//Will call this when write successful@Overridepublic void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {if (status == BluetoothGatt.GATT_SUCCESS) {broadcastUpdate(ACTION_WRITE_SUCCESSFUL);Log.v("log","Write OK");}}};private void broadcastUpdate(final String action) {final Intent intent = new Intent(action);sendBroadcast(intent);}private void broadcastUpdate(final String action,final BluetoothGattCharacteristic characteristic) {final Intent intent = new Intent(action);// if (UUID_BLE_SPP_NOTIFY.equals(characteristic.getUuid()) || UUID_BLE_SPP_NOTIFY_0.equals(characteristic.getUuid())){// For all other profiles, writes the data formatted in HEX.final byte[] data = characteristic.getValue();if (data != null && data.length > 0){intent.putExtra(EXTRA_DATA,data);}}sendBroadcast(intent);}public class LocalBinder extends Binder {BluetoothLeService getService() {return BluetoothLeService.this;}}@Overridepublic IBinder onBind(Intent intent) {return mBinder;}@Overridepublic boolean onUnbind(Intent intent) {// After using a given device, you should make sure that BluetoothGatt.close() is called// such that resources are cleaned up properly.  In this particular example, close() is// invoked when the UI is disconnected from the Service.close();return super.onUnbind(intent);}private final IBinder mBinder = new LocalBinder();/*** Initializes a reference to the local Bluetooth adapter.** @return Return true if the initialization is successful.*/public boolean initialize() {// For API level 18 and above, get a reference to BluetoothAdapter through// BluetoothManager.if (mBluetoothManager == null) {mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);if (mBluetoothManager == null) {Log.e(TAG, "Unable to initialize BluetoothManager.");return false;}}mBluetoothAdapter = mBluetoothManager.getAdapter();if (mBluetoothAdapter == null) {Log.e(TAG, "Unable to obtain a BluetoothAdapter.");return false;}return true;}/*** Connects to the GATT server hosted on the Bluetooth LE device.** @param address The device address of the destination device.** @return Return true if the connection is initiated successfully. The connection result*         is reported asynchronously through the*         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}*         callback.*/public boolean connect(final String address) {if (mBluetoothAdapter == null || address == null) {Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");return false;}// Previously connected device.  Try to reconnect.if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)&& mBluetoothGatt != null) {Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");if (mBluetoothGatt.connect()) {mConnectionState = STATE_CONNECTING;return true;} else {return false;}}final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);if (device == null) {Log.w(TAG, "Device not found.  Unable to connect.");return false;}// We want to directly connect to the device, so we are setting the autoConnect// parameter to false.mBluetoothGatt = device.connectGatt(this, false, mGattCallback);Log.d(TAG, "Trying to create a new connection.");mBluetoothDeviceAddress = address;mConnectionState = STATE_CONNECTING;return true;}/*** Disconnects an existing connection or cancel a pending connection. The disconnection result* is reported asynchronously through the* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}* callback.*/public void disconnect() {if (mBluetoothAdapter == null || mBluetoothGatt == null) {Log.w(TAG, "BluetoothAdapter not initialized");return;}mBluetoothGatt.disconnect();}/*** After using a given BLE device, the app must call this method to ensure resources are* released properly.*/public void close() {if (mBluetoothGatt == null) {return;}mBluetoothGatt.close();mBluetoothGatt = null;}/*** Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported* asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}* callback.** @param characteristic The characteristic to read from.*/public void readCharacteristic(BluetoothGattCharacteristic characteristic) {if (mBluetoothAdapter == null || mBluetoothGatt == null) {Log.w(TAG, "BluetoothAdapter not initialized");return;}mBluetoothGatt.readCharacteristic(characteristic);}/*** Enables or disables notification on a give characteristic.** @param characteristic Characteristic to act on.* @param enabled If true, enable notification.  False otherwise.*/public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,boolean enabled) {if (mBluetoothAdapter == null || mBluetoothGatt == null) {Log.w(TAG, "BluetoothAdapter not initialized");return;}mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);// This is specific to BLE SPP Notify.if (UUID_BLE_SPP_NOTIFY.equals(characteristic.getUuid()) || UUID_BLE_SPP_NOTIFY_0.equals(characteristic.getUuid())) {BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(BleSppGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);mBluetoothGatt.writeDescriptor(descriptor);}}public void writeData(byte[] data) {if ( mWriteCharacteristic != null &&data != null) {mWriteCharacteristic.setValue(data);//mBluetoothLeService.writeCmBluetoothGatt.writeCharacteristic(mWriteCharacteristic);}}public void writeAT(byte[] data) {if ( mATCharacteristic != null &&data != null) {mATCharacteristic.setValue(data);mBluetoothGatt.writeCharacteristic(mATCharacteristic);}}/*** Retrieves a list of supported GATT services on the connected device. This should be* invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.** @return A {@code List} of supported services.*/public List<BluetoothGattService> getSupportedGattServices() {if (mBluetoothGatt == null) return null;return mBluetoothGatt.getServices();}
}

BleSppGattAttributes.java


import java.util.HashMap;public class BleSppGattAttributes {private static HashMap<String, String> attributes = new HashMap();public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";//B-0002/B-0004
//    Service UUID:fee0
//    Notify:fee1
//    Write:fee1public static String BLE_SPP_Service_0 = "0000fee0-0000-1000-8000-00805f9b34fb";public static String BLE_SPP_Notify_Characteristic_0 = "0000fee1-0000-1000-8000-00805f9b34fb";public static String  BLE_SPP_Write_Characteristic_0 = "0000fee1-0000-1000-8000-00805f9b34fb";//B-0006 / TL8266 Use
//    Service UUID:1910
//    Notify:2B10
//    Write:2B11public static String BLE_SPP_Service = "0000fee0-0000-1000-8000-00805f9b34fb";public static String BLE_SPP_Notify_Characteristic = "0000fee1-0000-1000-8000-00805f9b34fb";public static String BLE_SPP_Write_Characteristic = "0000fee2-0000-1000-8000-00805f9b34fb";public static String BLE_SPP_AT_Characteristic = "0000fee3-0000-1000-8000-00805f9b34fb";static {//B-0002/B-0004 SPP Serviceattributes.put(BLE_SPP_Service_0, "BLE SPP Service_0");attributes.put(BLE_SPP_Notify_Characteristic_0, "BLE SPP Notify Characteristic_0");attributes.put(BLE_SPP_Write_Characteristic_0, "BLE SPP Write Characteristic_0");//B-0006/TL-8266 SPP Serviceattributes.put(BLE_SPP_Service, "BLE SPP Service");attributes.put(BLE_SPP_Notify_Characteristic, "BLE SPP Notify Characteristic");attributes.put(BLE_SPP_Write_Characteristic, "BLE SPP Write Characteristic");attributes.put(BLE_SPP_AT_Characteristic, "BLE SPP Write Characteristic");}public static String lookup(String uuid, String defaultName) {String name = attributes.get(uuid);return name == null ? defaultName : name;}
}

源码地址

【TL8266】向蓝牙模块发送AT指令的APP相关推荐

  1. 嵌入式单片机基础篇(二十七)之Stm32F103单片机给蓝牙模块发送AT指令程序

    Stm32F103单片机给蓝牙模块发送AT指令程序 #include "stm32f10x.h" #include "string.h" #include &q ...

  2. 浅谈Arduino进入蓝牙模块的AT指令模式

    春天适合努力和拥抱,也适合创客和造物图片图片今天小编得空,继续跟大家分享蓝牙模块的AT指令的相关用法. AT指令 1.什么是AT指令 在使用蓝牙模块的时候,我们经常想修改蓝牙模块的名字.密码,甚至蓝牙 ...

  3. 【TL8266】APP接收蓝牙模块发送过来的消息

    前一篇文章讲述了如何向蓝牙模块发送数据,这一篇讲述如何接收数据,点击开关按钮发送AT指令,模块会返回OK 先做一个广播接收器,按Ctrl+F关注mBluetoothLeService的操作 publi ...

  4. 蓝牙模块HC-05 AT指令使用以及两个蓝牙模块的配对

    蓝牙模块用的就是某宝常见的蓝牙模块,首先要将蓝牙模块进入AT模式,按住蓝牙按键后再通电就会进入蓝牙的AT模式,进入AT模式后蓝牙led慢闪,然后就可以利用TTL或者J-Link与串口助手给模块发送AT ...

  5. 微信小程序连接蓝牙模块发送数据的详解以及封装版

    连接蓝牙 前言 详解 小程序链接蓝牙流程图 需要的数据 api openBluetoothAdapter:打开蓝牙适配器 getBluetoothAdapterState:查看蓝牙适配器状态 star ...

  6. Android开发-连接开发板蓝牙模块发送和接收数据

    帮同学写一个连接小车蓝牙模块遥控小车的APP,在网上搜阅了很多资料,大概了解了蓝牙的工作原理,再经历了种种BUG后终于是成功连上了小车蓝牙,并可以发送数据,小车可以接收到,测试的蓝牙是Arduino小 ...

  7. 蓝牙模块通信c语言,求一个蓝牙模块发送数据的例子

    #include #include #define uchar unsigned char #define uint unsigned int /******led定义*******/ sbit le ...

  8. android 蓝牙与单片机通信原理图,手机蓝牙与HC-06蓝牙模块控制单片机程序加APP...

    这是楼主的程序(人民服务): /*********************************************************** STC90C51RD+与HC-06蓝牙连线: 蓝 ...

  9. 10蓝牙模块 hm 电脑蓝牙 连接_树莓派与HM-10蓝牙模块搭建iBeacon | 学步园

    最近iBeacon很火,我也买了个树莓派搭建一个iBeacon玩玩. 首先,需要的设备有: 1. 树莓派及电源 2. 一个蓝牙模块(网上都是用蓝牙适配器,而我用的是HM-10的蓝牙模块). 3. 连接 ...

最新文章

  1. 图解 | 搞定分布式,程序员进阶之路
  2. 用计算机弹奏lemon乐谱,原神乐谱lemon怎么弹 lemon乐谱弹奏方法教学
  3. 湖南省第八届大学生程序设计大赛原题 D - 平方根大搜索 UVA 12505 - Searching in sqrt(n)...
  4. springCloud学习-高可用的分布式配置中心(Spring Cloud Config)
  5. php mysql source_详解MySQL数据库中有关source命令
  6. rocketmq官网和其它资料
  7. GPS基站架设完整操作流程
  8. Leetcode--122. 买卖股票的最佳时机Ⅱ
  9. 计算两个矩阵相乘(Java)
  10. hadoop服务快速部署
  11. 传统到敏捷的转型中,谁更适合做Scrum Master?
  12. Linux 系统使用WordPress开启“固定链接设置”之后部分页面打不开(404)的解决办法...
  13. shell进入特权模式_GRUB引导下进Linux单用户模式的三种方式,修改root密码
  14. xd使用技巧_真香!3个技巧,帮你获得面试机率提升300%
  15. 点评一下阿提亚和黎曼猜想
  16. 2048+html源码之家,前端纯原生代码实现2048
  17. 360浏览器打开Axure
  18. 常见计算机英语词汇翻译,常见计算机英语词汇翻译_0.doc
  19. 解决Win10无操作两分钟进入睡眠问题
  20. STM32单片机新建工程

热门文章

  1. Ubuntu 误修改sudoers 导致 无法使用sudo的解决办法
  2. python离散数据傅里叶变换公式_离散傅里叶变换笔记
  3. win10录屏快捷键是什么?录屏快捷键怎么设置
  4. MySQL错误号码1045
  5. 检测PPG信号的峰值
  6. MAYA学习——NURBS建模1
  7. 科普贴丨240Hz有必要吗?
  8. python自学之路一:python的简介
  9. windows 系统加固
  10. enspac启动失败代码2_解决eNSP路由器AR启动失败错误代码40,交换机正常的问题