📅  最后修改于: 2023-12-03 14:59:16.731000             🧑  作者: Mango
Android 蓝牙技术可用于在 Android 手机和其他设备之间进行数据传输和通信。这个教程通过一个简单的示例来介绍如何在 Android 应用程序中使用蓝牙。
这个示例将展示如何扫描蓝牙设备并与之建立连接,使用已配对的设备发送和接收数据。
在 AndroidManifest.xml 文件中添加以下权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
你还需要在代码中对权限进行检查和请求:
private void checkPermissions() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH)
!= PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN}, 1);
}
}
在代码中,你需要初始化 BluetoothAdapter,这是整个蓝牙 API 中最重要的类:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
扫描蓝牙设备需要开始搜索,代码如下:
mBluetoothAdapter.startDiscovery();
通过注册 BroadcastReceiver 来接收设备的扫描结果:
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
连接蓝牙设备需要一些步骤,主要有搜索设备、配对设备、连接设备等。下面是一个示例代码:
// Get the device MAC address, which is the last 17 chars in the View
String address = device.getAddress();
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mBluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
bluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
发送和接收数据也是相对简单的:
// Get the input and output streams, using temp objects because
// member streams are final
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = mBluetoothSocket.getInputStream();
tmpOut = mBluetoothSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "getStream() failed", e);
}
mInputStream = tmpIn;
mOutputStream = tmpOut;
// Read from the InputStream
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mInputStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
// Write to the OutputStream
byte[] bytes = message.getBytes();
try {
mOutputStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write() failed", e);
}
这篇教程仅仅是蓝牙技术的入门教学,希望能对想要学习和应用蓝牙技术的程序员有所帮助。