安卓app开发实战蓝牙聊天

安卓App开发实战: 蓝牙聊天应用

蓝牙聊天应用可以让用户通过蓝牙进行实时的双向通信。本文将详细介绍如何开发一个安卓蓝牙聊天应用,主要分为以下几个部分:

1. 蓝牙基础概念

2. 蓝牙权限及配置

3. 搜索并连接蓝牙设备

4. 实现双向通信

5. 对话界面设计

一、蓝牙基础概念

蓝牙是一种短距离无线通信技术,典型的应用场景包括文件传输、语音传输等。在安卓开发中,蓝牙分为经典蓝牙(Bluetooth Classic)和低功耗蓝牙(Bluetooth Low Energy, BLE)两种。本文将以经典蓝牙为例,实现一款简单的蓝牙聊天应用。

二、蓝牙权限及配置

1. 在AndroidManifest.xml中添加蓝牙相关权限:

```xml

```

2. 在build.gradle文件的dependencies中添加依赖:

```groovy

implementation 'com.android.support:appcompat-v7:28.0.0'

```

三、搜索并连接蓝牙设备

1. 获取BluetoothAdapter实例:

```java

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

```

2. 开启蓝牙:

```java

if (!bluetoothAdapter.isEnabled()) {

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

}

```

3. 搜索蓝牙设备:

```java

private void discoverDevices() {

if (bluetoothAdapter.isDiscovering()) {

// 取消搜索设备

bluetoothAdapter.cancelDiscovery();

}

bluetoothAdapter.startDiscovery();

}

```

4. 监听搜索到的设备:

```java

BroadcastReceiver mReceiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

if (BluetoothDevice.ACTION_FOUND.equals(action)) {

// 从Intent中获取搜索到的蓝牙设备

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

}

}

};

// 注册设备搜索广播接收器

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

registerReceiver(mReceiver, filter);

```

四、实现双向通信

1. 通过UUID建立连接:

```java

private class ConnectThread extends Thread {

private final BluetoothSocket mmSocket;

private final BluetoothDevice mmDevice;

public ConnectThread(BluetoothDevice device) {

BluetoothSocket tmp = null;

mmDevice = device;

try {

// 使用InsecureRfcommSocket获取一个蓝牙通信的socket

tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);

} catch (IOException e) {

Log.e(TAG, "ConnectThread:创建socket失败", e);

}

mmSocket = tmp;

}

public void run() {

// 尝试连接蓝牙设备

try {

mmSocket.connect();

} catch (IOException connectException) {

// 无法连接,关闭socket并退出

try {

mmSocket.close();

} catch (IOException closeException) {

Log.e(TAG, "ConnectThread:无法关闭socket", closeException);

}

return;

}

// socket连接成功,取消搜索设备

bluetoothAdapter.cancelDiscovery();

// 管理连接后的Socket

manageConnectedSocket(mmSocket);

}

// 取消连接

public void cancel() {

try {

mmSocket.close();

} catch (IOException e) {

Log.e(TAG, "ConnectThread.cancel:关闭socket失败", e);

}

}

}

```

2. 双向通信的读写操作:

```java

private class ConnectedThread extends Thread {

private final BluetoothSocket mmSocket;

private final InputStream mmInStream;

private final OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket) {

mmSocket = socket;

InputStream tmpIn = null;

OutputStream tmpOut = null;

// 获取输入输出流

try {

tmpIn = socket.getInputStream();

tmpOut = socket.getOutputStream();

} catch (IOException e) {

Log.e(TAG, "ConnectedThread:获取socket流失败", e);

}

mmInStream = tmpIn;

mmOutStream = tmpOut;

}

public void run() {

byte[] buffer = new byte[1024];

int bytes;

// 持续监听输入流,等待数据接收

while (true) {

try {

// 从输入流读取数据

bytes = mmInStream.read(buffer);

// 将数据转换为String,并显示在会话窗口

String readMessage = new String(buffer, 0, bytes);

Message msg=Message.obtain();

msg.obj=readMessage;

mReceiveHandler.sendMessage(msg);

} catch (IOException e) {

Log.e(TAG, "ConnectedThread:读取数据失败", e);

break;

}

}

}

// 写入数据到输出流,发送给蓝牙设备

public void write(byte[] bytes) {

try {

mmOutStream.write(bytes);

} catch (IOException e) {

Log.e(TAG, "ConnectedThread:写入数据失败", e);

}

}

// 取消当前线程

public void cancel() {

try {

mmSocket.close();

} catch (IOException e) {

Log.e(TAG, "ConnectedThread.cancel:关闭socket失败", e);

}

}

}

```

五、对话界面设计

在布局文件中添加一个RecyclerView,并添加输入框和发送按钮。将接收到的聊天信息显示在RecyclerView上。发送聊天信息时,将聊天内容写入ConnectedThread的输出流,实现与对方蓝牙设备的互动。

结语

通过以上步骤,您可以完成一个简单的安卓蓝牙聊天应用的开发。这仅仅是一个基础的示例,实际应用中还需要进一步完善。例如优化UI, 提高搜索设备速度等。希望这篇教程对您入门安卓

川公网安备 51019002001728号