想要对应用程序进行编程以连接到蓝牙设备

Want to program app to connect to bluetooth device

希望有人能指引我正确的方向。

我正在尝试编写一个简单的应用程序,通过蓝牙连接到一个火警设备。总体目标是当设备触发火警时,应用程序通过简单的二进制 Alarm/No 报警功能显示火警状态。

我遇到的问题是编程蓝牙功能。我有 Java 的经验,但没有蓝牙功能。我想编写一个搜索和连接蓝牙设备的按钮。

这是我在 MainActivity.kt

中开始的部分代码
package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val daqButton = findViewById<Button>(R.id.daqButton)

        daqButton.setOnClickListener {

        }
    }
}

这是我在 AndroidManifest.xml

中开始的代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <!-- If your app targets Android 9 or lower, you can declare
         ACCESS_COARSE_LOCATION instead. -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

非常感谢能帮助我完成此任务的任何提示或技巧!提前致谢:)

嗯,最简单的实现方法是使用像这样的 third-party 库 Bluetooth Library

  • 将库依赖项包含到您的 app module gradle 文件中。
  • 按照 GitHub 上的库存储库中的说明在您的应用中设置库。
  • 如果您需要从应用程序连接到设备,您必须通过提供 ListView 和插入发现的蓝牙设备的逻辑来自行实现扫描功能。 请参阅 Github 存储库文档,您会发现一些可用于实现搜索、发现和连接功能的回调。
  • 如果您更喜欢简单的方法,只需从设备的蓝牙管理器外部连接到蓝牙设备,那么您可以按如下方式与设备通信。
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main)

    bluetooth = new Bluetooth(this);
    bluetooth.send("Your message");

}

  • 如果您想从其他蓝牙设备收到一些响应,您必须收听 DeviceCallback() 您将在 Github 存储库中找到它的描述

备注

您必须在

的清单文件中添加一些权限
  • 蓝牙
  • BLUETOOTH_ADMIN
  • ACCESS_COARSE_LOCATION

为了让您的应用程序能够使用蓝牙