1、引言
最近在学习如何在安卓手机上对蓝牙进行操控,作为初学者发现大多数博客对安卓开发的初学者极为不友好,特别是安卓和java都不熟悉的童鞋,因此现对我近期所学习内容做一个总结,希望对大家有帮助。
2、布局文件
控件的种类,数量及用途如下表所示,AS中控件的使用方法可参考B站up主(longway777)讲得很到位。
| 控件种类 | 控件数量 | 作用 |
|---|---|---|
| Button | 2 | 蓝牙的打开与关闭 |
| Guideline | 2 | 固定控件 |
| textView | 1 | 显示蓝牙的状态 |
具体布局如下图所示,
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="@string/button1"
android:textSize="24sp"
app:layout_constraintEnd_toStartOf="@+id/guideline2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="@string/button2"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toTopOf="@+id/guideline" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content

这篇博客详细介绍了如何在安卓应用中实现蓝牙的开启与关闭功能。首先,讲解了布局文件的创建,包括按钮和文本视图的设置。接着,讨论了在AndroidManifest.xml中添加蓝牙权限的必要性,并解析了BluetoothAdapter类的关键方法。博主提供了两种实现蓝牙控制的代码示例,一种是通过按钮监听方法,另一种是设置点击事件。最后,展示了应用运行的效果并给出了源码片段。
最低0.47元/天 解锁文章
3013





