Android BLE和HC-05(使用C代码)的数据发送和接收?
创始人
2024-08-13 09:01:35
0

要在Android上使用BLE协议发送和接收数据,可以使用Android的Bluetooth Low Energy(BLE)API进行操作。下面是一个示例代码,展示了如何在Android上使用BLE进行数据发送和接收。

首先,在AndroidManifest.xml文件中添加以下权限:



然后,在你的Activity中添加以下代码:

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private static final int REQUEST_ENABLE_BT = 1;
    private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 2;

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothGatt mBluetoothGatt;
    private BluetoothGattCharacteristic mCharacteristic;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    // 发送数据
                    sendData("Hello, HC-05!");
                    break;
                case 2:
                    // 接收数据
                    byte[] data = (byte[]) msg.obj;
                    Log.d(TAG, "Received data: " + new String(data));
                    break;
            }
            return true;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 检查设备是否支持BLE
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Log.e(TAG, "BLE not supported");
            finish();
        }

        // 初始化BluetoothAdapter
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // 检查设备是否支持蓝牙
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Bluetooth not supported");
            finish();
        }

        // 检查是否授予位置权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
        } else {
            // 开始扫描设备
            startScan();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 断开连接并释放资源
        if (mBluetoothGatt != null) {
            mBluetoothGatt.disconnect();
            mBluetoothGatt.close();
            mBluetoothGatt = null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 开始扫描设备
                startScan();
            } else {
                Log.e(TAG, "Location permission not granted");
                finish();
            }
        }
    }

    private void startScan() {
        // 检查蓝牙是否已启用
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            return;
        }

        // 开始扫描设备
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
            // 根据设备名字来选择连接的设备
            if (device.getName().equals("HC-05")) {
                // 停止扫描
                mBluetoothAdapter

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
安装了Anaconda之后找不... 在安装Anaconda后,如果找不到Jupyter Notebook,可以尝试以下解决方法:检查环境...