三、筛选蓝牙信息并连接(安卓蓝牙ble教程)

11 篇文章 0 订阅
10 篇文章 0 订阅

1、MainActivity.java

注:如果复制代码进项目时显示红色,请按ALT+ENTER键导包(import class)

 

package club.stm32;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    /**
     * 需要根据条件修改的参数
     */
    private String MacHeader = "A6:C0:80";  //蓝牙的Mac地址前六位,需要根据自己的蓝牙进行修改


    private BluetoothAdapter bluetoothAdapter;
    private Button btnCheckPermission;
    private TextView tvmsg;
    private Button btnSearchBLE;
    private BluetoothDevice mdevice;
    private BluetoothGatt bluetoothGatt;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getPermission();  //获取权限
        bluetoothInit();    //蓝牙初始化
        widgetInit();       //控件初始化
        widgetListener();   //控件监听

    }

    //获取权限
    private void getPermission() {

        //如果sdk版本大于23
        if (Build.VERSION.SDK_INT >=23){

            //如果没有权限
            if ((ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED))
            {
                //动态申请权限
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 10);

            }
        }
    }

    //控件初始化
    private void widgetInit() {

        //请自行提升到全局,原型是:Button startscan = findViewById(R.id.startscan);
        btnCheckPermission = findViewById(R.id.btnCheckPermission);

        //请自行提升到全局,原型是:TextView tvmsg = findViewById(R.id.tvmsg);
        tvmsg = findViewById(R.id.tvmsg);

        //请自行提升到全局,原型是:Button btnSearchBLE = findViewById(R.id.btnSearchBLE);
        btnSearchBLE = findViewById(R.id.btnSearchBLE);
    }

    //控件监听
    private void widgetListener() {

        //测试权限按钮监听
        btnCheckPermission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
                if (permissionCheck == PackageManager.PERMISSION_GRANTED) {//如果有权限
                    Toast.makeText(MainActivity.this, "hava this permission", Toast.LENGTH_SHORT).show();//toast信息
                    Log.d("权限:","有定位权限");//在logcat上打印信息
                    tvmsg.setText("有定位权限");
                }else {
                    getPermission();//获取权限
                    Toast.makeText(MainActivity.this, "no this permission", Toast.LENGTH_SHORT).show();//toast信息
                    Log.d("权限:","无定位权限");//在logcat上打印信息
                    tvmsg.setText("无定位权限");
                }
            }
        });

        //搜索蓝牙按钮监听
        btnSearchBLE.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开始搜索蓝牙
                bluetoothAdapter.startLeScan(mBLEScanCallback);
            }
        });

    }

    //mBLEScanCallback回调函数
    private BluetoothAdapter.LeScanCallback mBLEScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {

            //打印蓝牙mac地址
            Log.d("BleMAC", device.getAddress());
            if(device.toString().indexOf(MacHeader) == 0){
                Log.d("符合的蓝牙地址", device.getAddress());
                bluetoothAdapter.stopLeScan(mBLEScanCallback);
                //停止搜索蓝牙,降低功耗
                bluetoothAdapter.stopLeScan(mBLEScanCallback);
                //获取远程设备(连接蓝牙)原型是BluetoothDevice mdevice = bluetoothAdapter.getRemoteDevice(des);请自行提升全局
                mdevice = bluetoothAdapter.getRemoteDevice(device.toString());
                //连接bluetoothGatt 到这一步时,蓝牙已经连接上了
                //原型是BluetoothGatt bluetoothGatt = device.connectGatt(MainActivity.this, false, bluetoothGattCallback); 请自行提升全局
                //bluetoothGattCallback是蓝牙gatt回调函数,接下来会跳到bluetoothGattCallback函数
                bluetoothGatt = mdevice.connectGatt(MainActivity.this, false, bluetoothGattCallback);
                Log.d("已连接到蓝牙", device.getAddress());
            }
        }
    };

    //蓝牙回调函数
    private final BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {

    };



    private void bluetoothInit() {

        //如果不支持蓝牙
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))
        {
            //提示不支持蓝牙
            Toast.makeText(this, "程序不支持该设备", Toast.LENGTH_SHORT).show();
            //退出程序
            finish();
        }
        //创建蓝牙适配器原型是BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //如果蓝牙适配器为空
        if (bluetoothAdapter == null)
        {
            //显示设备无蓝牙
            Toast.makeText(this, "设备无蓝牙", Toast.LENGTH_SHORT).show();
            //退出
            finish();
        }
        //如果蓝牙未开启
        if (!bluetoothAdapter.isEnabled())
        {
            //不提示,直接开启蓝牙
            bluetoothAdapter.enable();
            //提示开启蓝牙中
            Toast.makeText(this, "开启蓝牙中,如果未开启,请检查应用权限", Toast.LENGTH_SHORT).show();
        }
    }
}

2、布局文件activity_main.xml

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:text="Hello World!"
        android:id="@+id/tvmsg"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="测试权限"
            android:id="@+id/btnCheckPermission"
            />

        <Button
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="搜索蓝牙"
            android:id="@+id/btnSearchBLE"
            />


    </LinearLayout>



</LinearLayout>

效果图:

 

 

 

 

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Qt for Android中连接BLE蓝牙设备,你需要使用Qt的蓝牙库和相关类。根据你提供的引用内容,我可以看到你已经参考了一些文章和博客,并找到了一个功能相近的项目。 首先,你需要包含以下头文件: #include <QtBluetooth/qbluetoothlocaldevice.h> // 本地设备信息 #include <QBluetoothDeviceDiscoveryAgent> // 设备搜寻 #include <QBluetoothDeviceInfo> // 设备信息 #include <QLowEnergyController> // 设备连接 #include <QLowEnergyService> // 数据接收、发送 \[3\] 然后,你可以使用QLowEnergyController类来连接BLE设备。你可以使用QBluetoothDeviceDiscoveryAgent类来搜索附近的设备,并获取设备信息。一旦你找到了目标设备,你可以使用QLowEnergyController类来连接设备。 在连接设备之前,你可以使用QListWidget控件来显示设备列表,并使用双击或按钮来触发连接设备的操作。你可以使用connect函数来连接信号和槽函数,以便在用户双击设备列表项或点击按钮时触发连接操作。 connect(ui->Device_List, SIGNAL(itemActivated(QListWidgetItem*)),this, SLOT(connect_Device())); //连接设备 connect(ui->Link_Device,&QPushButton::clicked,\[=\]{ connect_Device(); }); //连接设备 connect(ui->disLink_Device,&QPushButton::clicked,\[=\]{ m_pcontrol->disconnectFromDevice(); ui->Server_List->clear(); }); //断开设备连接 \[2\] 需要注意的是,Qt官方的蓝牙套接字只适用于SPP传输的蓝牙,而BLE蓝牙需要使用QLowEnergyController和QLowEnergyService类来实现连接和数据传输。这可能会比蓝牙套接字复杂很多倍。 希望这些信息对你有帮助,祝你成功完成你的毕设! #### 引用[.reference_title] - *1* [Qt for Android 使用BLE串口蓝牙发送数据](https://blog.csdn.net/qq_35342292/article/details/104170372)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [QT for Android BLE Bluetooch QT BLE](https://blog.csdn.net/qq_27620407/article/details/129122512)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值