ToB企服应用市场:ToB评测及商务社交产业平台

标题: Android Studio制作手机App:通过手机蓝牙(Bluetooth)与STM32上的低功耗蓝 [打印本页]

作者: 九天猎人    时间: 2024-6-14 21:40
标题: Android Studio制作手机App:通过手机蓝牙(Bluetooth)与STM32上的低功耗蓝
背景:
本文的内容是针对单片机蓝牙模块(HC-42)开发的手机App。在这之前,我想先声明一点,手机与手机间的蓝牙连接方式”与“手机与HC间的蓝牙连接方式”是不一样的。缘故起因就是手机搭配的是“经典蓝牙”模块,HC等蓝牙属于“低功耗蓝牙”模块。(二者的区别想相识的话建议你去看看其他朋侪的文章),我在这里只想简朴说一下这二者在功能代码实现上可以说是完全不一样的。这就解释了有一些朋侪制作的软件明显可以与手机,平板等装备配对连接,却一直与HC蓝牙配对失败。
媒介:
本文的内容只讲怎样实现手机与HC蓝牙的配对,如果想相识一下手机与手机,手机与平板间的“经典蓝牙”通信方式,可以看我往期的博文,这篇博文讲的是怎样制作一个基于蓝牙通信的聊天软件(类似于微信功能),也是一个挺有意思的项目(Android Studio制作蓝牙聊天通讯软件)
本文内容简介:
制作一个手机APP,无线连接HC蓝牙模块,将手机端数据发送给HC,从而控制STM32,文末会有资源分享。
简朴通讯原理图:

怎样制作如许一个App?
起首看一下本次的效果图:

 一、软件UI界面部分的设计实现
可以看 软件UI界面设计的实现 这篇博文,先实现界面设计后,再完成接下来的功能代码实现。
二、功能代码的实现。
1、在AndroidManifest.xml中添加依赖:
  1. <uses-permission android:name="android.permission.BLUETOOTH"/>
  2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
  3. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  4. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  5. <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"
复制代码
 2、新建文件BlueToothController .java,完备代码及其解析如下:
  1. package BluetoothPackage;
  2. import android.app.Activity;
  3. import android.bluetooth.BluetoothAdapter;
  4. import android.bluetooth.BluetoothDevice;
  5. import android.bluetooth.BluetoothGatt;
  6. import android.bluetooth.BluetoothGattCallback;
  7. import android.bluetooth.le.BluetoothLeScanner;
  8. import android.bluetooth.le.ScanCallback;
  9. import android.content.Context;
  10. import android.content.Intent;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. /**
  14. * Created by WYB on 2023/4/28.
  15. */
  16. public class BluetoothController {
  17.     private BluetoothAdapter mAdapter;//本手机的蓝牙适配器
  18.     private BluetoothLeScanner mLeScanner;//本手机蓝牙适配器上的扫描硬件
  19.     private Activity mActivity;
  20.     public static final int REQUEST_CODE_ENABLE_BLUETOOTH = 0;
  21.     public BluetoothController(Activity activity){
  22.         mAdapter = BluetoothAdapter.getDefaultAdapter();//获取本机蓝牙适配器
  23.         mLeScanner = mAdapter.getBluetoothLeScanner();//获取本机蓝牙扫描器
  24.         mActivity = activity;
  25.     }
  26.     public BluetoothAdapter getAdapter() {
  27.         return mAdapter;
  28.     }
  29.     public BluetoothLeScanner getmLeScanner(){
  30.         return mLeScanner;
  31.     }
  32.     /*
  33.         打开蓝牙设备
  34.     */
  35.     public void  turnOnBlueTooth(){
  36.         Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  37.         mActivity.startActivityForResult(intent,REQUEST_CODE_ENABLE_BLUETOOTH);
  38.     }
  39.     /*
  40.         关闭蓝牙设备
  41.     */
  42.     public void  turnOffBlueTooth(){
  43.         mAdapter.disable();
  44.     }
  45.     /**
  46.      * 打开蓝牙可见性,让别的设备发现我
  47.      */
  48.     public void enableVisibily(Context context){
  49.         Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  50.         intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
  51.         context.startActivity(intent);
  52.     }
  53.     /*
  54.         查找未绑定的蓝牙设备
  55.     */
  56.     public void findDevice(){
  57.         assert (mAdapter!=null);
  58.         mAdapter.startDiscovery();
  59.     }
  60.     /*
  61.         查看已绑定的蓝牙设备
  62.     */
  63.     public List<BluetoothDevice> getBondedDeviceList(){
  64.         return new ArrayList<>(mAdapter.getBondedDevices());
  65.     }
  66.     /*
  67.         开启扫描
  68.     */
  69.     public void scanBlueTooth(ScanCallback scanCallback){
  70.         mLeScanner.startScan(scanCallback);
  71.     }
  72.     /*
  73.         关闭扫描
  74.     */
  75.     public void stopBlueTooth(ScanCallback scanCallback){
  76.         mLeScanner.stopScan(scanCallback);
  77.     }
  78.     /*
  79.         连接设备
  80.     */
  81.     public BluetoothGatt connectBlueTooth(BluetoothDevice bluetoothDevice, boolean autoConnect, BluetoothGattCallback gattCallback){
  82.         return bluetoothDevice.connectGatt(this.mActivity,autoConnect,gattCallback);
  83.     }
  84. }
复制代码
3、MainActivity .java,完备代码及其解析如下:
  1. package com.example.wyb.bluetoothchatui;
  2. import android.Manifest;
  3. import android.bluetooth.BluetoothAdapter;
  4. import android.bluetooth.BluetoothDevice;
  5. import android.bluetooth.BluetoothManager;
  6. import android.bluetooth.le.ScanCallback;
  7. import android.bluetooth.le.ScanResult;
  8. import android.content.Context;
  9. import android.content.Intent;
  10. import android.content.pm.PackageManager;
  11. import android.os.Build;
  12. import android.os.Handler;
  13. import android.support.v4.app.ActivityCompat;
  14. import android.support.v4.content.ContextCompat;
  15. import android.support.v7.app.AppCompatActivity;
  16. import android.os.Bundle;
  17. import android.util.Log;
  18. import android.view.View;
  19. import android.widget.AdapterView;
  20. import android.widget.Button;
  21. import android.widget.ListView;
  22. import android.widget.Toast;
  23. import java.util.ArrayList;
  24. import java.util.List;
  25. import BluetoothPackage.BluetoothController;
  26. import MyClass.DeviceAdapter;
  27. import MyClass.DeviceClass;
  28. public class MainActivity extends AppCompatActivity {
  29.     private DeviceAdapter mAdapter1,mAdapter2;
  30.     private List<DeviceClass> mbondDeviceList = new ArrayList<>();//搜索到的所有已绑定设备保存为列表(仅保留名称与地址)
  31.     private List<DeviceClass> mfindDeviceList = new ArrayList<>();//搜索到的所有未绑定设备保存为列表(仅保留名称与地址)
  32.     private List<BluetoothDevice> bondDevices = new ArrayList<>();//搜索到的所有的已绑定设备
  33.     private List<BluetoothDevice> findDevices = new ArrayList<>();//搜索到的所有的未绑定设备
  34.     private BluetoothController mbluetoothController;
  35.     private Toast mToast;
  36.     private mScanCallBack myScanCallBack;
  37.     private static final int PERMISSION_REQUEST_COARSE_LOCATION=1;
  38.     private Button findBtn;
  39.     private Handler mHandler = new Handler();
  40.     @Override
  41.     protected void onCreate(Bundle savedInstanceState) {
  42.         super.onCreate(savedInstanceState);
  43.         setContentView(R.layout.activity_main);
  44.         mbluetoothController = new BluetoothController(this);
  45.         Init_listView();//初始化设备列表
  46.         findBtn = (Button) findViewById(R.id.button1);
  47.         Init_Bluetooth();//开启蓝牙相关权限
  48.     }
  49.     //扫描蓝牙功能的实现
  50.     private class mScanCallBack extends ScanCallback{
  51.         @Override
  52.         public void onScanResult(int callbackType, ScanResult result){
  53.             super.onScanResult(callbackType,result);
  54.             if(!findDevices.contains(result.getDevice()))
  55.             {
  56.                 mfindDeviceList.add(new DeviceClass(result.getDevice().getName(),result.getDevice().getAddress()));
  57.                 findDevices.add(result.getDevice());
  58.                 mAdapter2.notifyDataSetChanged();
  59.             }
  60.         }
  61.         @Override
  62.         public void onBatchScanResults(List<ScanResult> results){
  63.             super.onBatchScanResults(results);
  64.         }
  65.         @Override
  66.         public void onScanFailed(int errorCode){
  67.             super.onScanFailed(errorCode);
  68.         }
  69.     }
  70.     //初始化蓝牙权限
  71.     private void Init_Bluetooth(){
  72.         myScanCallBack = new mScanCallBack();
  73.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  74.             if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  75.                 requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
  76.             }
  77.         }
  78.         mbluetoothController.turnOnBlueTooth();
  79.     }
  80.     //初始化列表,适配器的加载
  81.     public void Init_listView(){
  82.         mAdapter1 = new DeviceAdapter(MainActivity.this, R.layout.device_item, mbondDeviceList);
  83.         ListView listView1 = (ListView)findViewById(R.id.listview1);
  84.         listView1.setAdapter(mAdapter1);
  85.         mAdapter1.notifyDataSetChanged();
  86.         mAdapter2 = new DeviceAdapter(MainActivity.this, R.layout.device_item, mfindDeviceList);
  87.         ListView listView2 = (ListView)findViewById(R.id.listview2);
  88.         listView2.setAdapter(mAdapter2);
  89.         mAdapter2.notifyDataSetChanged();
  90.         listView2.setOnItemClickListener(toBondDevices);//点击设备,进行绑定
  91.     }
  92.     //点击开始查找蓝牙设备
  93.     public View findDevice(View view){
  94.         //先执行其他代码,8s后执行run()里面的代码
  95.         mHandler.postDelayed(new Runnable() {
  96.             @Override
  97.             public void run() {
  98.                 change_Button_Text("搜索设备","ENABLE");
  99.                 mbluetoothController.stopBlueTooth(myScanCallBack);
  100.             }
  101.         }, 8000);
  102.         change_Button_Text("搜索中...","DISABLE");
  103.         mbluetoothController.scanBlueTooth(myScanCallBack);Log.e("提示","---------->findDevice");
  104.         return view;
  105.     }
  106.     //点击按键搜索后按键的变化
  107.     private void change_Button_Text(String text,String state){
  108.         if("ENABLE".equals(state)){
  109.             findBtn.setEnabled(true);
  110.             findBtn.getBackground().setAlpha(255); //0~255 之间任意调整
  111.             findBtn.setTextColor(ContextCompat.getColor(this, R.color.black));
  112.         }
  113.         else {
  114.             findBtn.setEnabled(false);
  115.             findBtn.getBackground().setAlpha(150); //0~255 之间任意调整
  116.             findBtn.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
  117.         }
  118.         findBtn.setText(text);
  119.     }
  120.     //点击设备后执行的函数,跳转到第二个操作界面,并将选中的蓝牙设备信息传递过去
  121.     private AdapterView.OnItemClickListener toBondDevices =new AdapterView.OnItemClickListener(){
  122.         @Override
  123.         public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
  124.             mbluetoothController.stopBlueTooth(myScanCallBack);
  125.             BluetoothDevice device = findDevices.get(i);
  126.             Intent intent = new Intent(MainActivity.this,Main2Activity.class);
  127.             intent.putExtra("device",device);
  128.             startActivity(intent);
  129.         }
  130.     };
  131.     //设置toast的标准格式
  132.     private void showToast(String text){
  133.         if(mToast == null){
  134.             mToast = Toast.makeText(this, text,Toast.LENGTH_SHORT);
  135.             mToast.show();
  136.         }
  137.         else {
  138.             mToast.setText(text);
  139.             mToast.show();
  140.         }
  141.     }
  142. }
复制代码
4、MainActivity2 .java,完备代码及其解析如下:
  1. package com.example.wyb.bluetoothchatui;
  2. import android.bluetooth.BluetoothDevice;
  3. import android.bluetooth.BluetoothGatt;
  4. import android.bluetooth.BluetoothGattCallback;
  5. import android.bluetooth.BluetoothGattCharacteristic;
  6. import android.bluetooth.BluetoothGattService;
  7. import android.content.Intent;
  8. import android.support.v7.app.AppCompatActivity;
  9. import android.os.Bundle;
  10. import android.util.Log;
  11. import android.view.View;
  12. import android.widget.EditText;
  13. import android.widget.ListView;
  14. import android.widget.TextView;
  15. import android.widget.Toast;
  16. import java.util.List;
  17. import BluetoothPackage.BluetoothController;
  18. public class Main2Activity extends AppCompatActivity {
  19.     private BluetoothDevice Device;
  20.     private TextView textView;
  21.     private EditText editText;
  22.     private mGattCallback myGattCallBack;
  23.     private BluetoothGatt mybluetoothGatt;
  24.     private BluetoothController mbluetoothController;
  25.     private String SERVICE_EIGENVALUE_SED = "0000ffe1-0000-1000-8000-00805f9b34fb";
  26.     private android.os.Handler mytimeHandler = new android.os.Handler();
  27.     private BluetoothGattCharacteristic mneedGattCharacteristic;
  28.     private TextView deviceState;
  29.     private TextView appname;
  30.     @Override
  31.     protected void onDestroy() {
  32.         //返回第一个界面时取消蓝牙配对
  33.         mybluetoothGatt.disconnect();
  34.         super.onDestroy();
  35.     }
  36.     @Override
  37.     protected void onCreate(Bundle savedInstanceState) {
  38.         super.onCreate(savedInstanceState);
  39.         setContentView(R.layout.activity_main2);
  40.         Intent intent = getIntent();
  41.         Device = intent.getParcelableExtra("device");
  42.         textView = (TextView) findViewById(R.id.textView1);
  43.         editText = (EditText) findViewById(R.id.input_text);
  44.         deviceState = (TextView) findViewById(R.id.device_state);
  45.         appname = (TextView) findViewById(R.id.AppName);
  46.         appname.setText("");
  47.         deviceState.setText("Device:"+Device.getName()+"(未连接)");
  48.         mbluetoothController = new BluetoothController(this);
  49.         myGattCallBack = new mGattCallback();
  50.         mybluetoothGatt = mbluetoothController.connectBlueTooth(Device,false,myGattCallBack);
  51.     }
  52.     //蓝牙绑定功能的实现
  53.     private class mGattCallback extends BluetoothGattCallback {
  54.         @Override
  55.         public void onConnectionStateChange(BluetoothGatt gatt,int status,int newState){
  56.             Log.e("提示","蓝牙连接成功");
  57.             super.onConnectionStateChange(gatt,status,newState);
  58.             mytimeHandler.postDelayed(new Runnable(){
  59.                 @Override
  60.                 public void run(){
  61.                     mybluetoothGatt.discoverServices();
  62.                     deviceState.setText("Device:"+Device.getName()+"(已连接)");
  63.                 }
  64.             },1000);
  65.         }
  66.         @Override
  67.         public void onServicesDiscovered(BluetoothGatt gatt,int status){
  68.             List<BluetoothGattService> services = mybluetoothGatt.getServices();
  69.             for(int i=0;i<services.size();i++){
  70.                 Log.e("提示","第"+i+"个"+services.get(i));
  71.                 List<BluetoothGattCharacteristic> characteristics = services.get(i).getCharacteristics();
  72.                 for (int j=0;j<characteristics.size();j++){
  73.                     Log.e("提示","第"+i+"个服务,第"+j+"个特征值"+characteristics.get(j));
  74.                     if(characteristics.get(j).getUuid().toString().equals(SERVICE_EIGENVALUE_SED)){
  75.                         Log.e("提示","我找到我需要的特征了");
  76.                         mneedGattCharacteristic = characteristics.get(j);
  77.                         mybluetoothGatt.setCharacteristicNotification(mneedGattCharacteristic,true);
  78.                     }
  79.                 }
  80.             }
  81.             super.onServicesDiscovered(gatt,status);
  82.             Log.e("提示","onServicesDiscovered");
  83.         }
  84.         @Override
  85.         public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,int status){
  86.             super.onCharacteristicRead(gatt,characteristic,status);
  87.             Log.e("提示","onCharacteristicRead");
  88.         }
  89.         @Override
  90.         public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic){
  91.             super.onCharacteristicChanged(gatt,characteristic);
  92.             Log.e("提示","onCharacteristicChanged");
  93.         }
  94.     }
  95.     //发送信息的实现
  96.     public void sendData(BluetoothGatt bluetoothGatt,BluetoothGattCharacteristic bluetoothGattCharacteristic,String text){
  97.         bluetoothGattCharacteristic.setValue(text);
  98.         bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
  99.     }
  100.     //处理要发送的信息,并更新界面内容
  101.     public View sendMessage(View view){
  102.         sendData(mybluetoothGatt,mneedGattCharacteristic,editText.getText().toString());
  103.         textView.setText(textView.getText().toString()+editText.getText().toString());
  104.         editText.getText().clear();
  105.         return view;
  106.     }
  107. }
复制代码
三、本项目的最终分享
链接:https://pan.baidu.com/s/1rX6GbTvHRU3Mb18tgwEjHg  提取码:td1d
四、后文
那么到此你就已经完成了本项目的制作,此软件制作实在没有想象中的那么难,至于STM32上的步伐编写教程可以看往期博文: Bluetooth(HC)与STM32的连接通讯(在手机端通过蓝牙控制STM32板子小灯)



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4