シングルチップBluetoothモジュールを使用することによって制御されるAndroidデバイスは、非常に簡単にスマートホームのシナリオを実装行うことです、そして私は、Android HC-05 Bluetoothモジュール通信プロセスの完全な説明と関連するコードを開発しています。
適切なアクセス権を取得
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- 6.0以上需要加的额外权限 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />
登録Bluetooth無線
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
登録放送受信機
// 注册广播接收者
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent intent) {
// 获取到广播的action
String action = intent.getAction();
// 判断广播是搜索到设备还是搜索完成
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
// 找到设备后获取其设备
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 判断这个设备是否是之前已经绑定过了,如果是则不需要添加,在程序初始化的时候已经添加了
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
// 设备没有绑定过,则将其保持到arrayList集合中
bluetoothDevices.add(device.getName() + ":"
+ device.getAddress() + "\n");
// 更新字符串数组适配器,将内容显示在listView中
arrayAdapter.notifyDataSetChanged();
}
} else if (action
.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
setTitle("搜索完成");
}
}
};
Bluetoothデバイスを検索します
mBluetoothAdapter.startDiscovery();
データを送信します
private void sendCode(byte[] code)
{
try {
// 判断客户端接口是否为空
if (clientSocket == null) {
// 获取到客户端接口
clientSocket = selectDevice
.createRfcommSocketToServiceRecord(MY_UUID);
// 向服务端发送连接
clientSocket.connect();
// 获取到输出流,向外写数据
os = clientSocket.getOutputStream();
if (commected) {
commected = false;
// 实例接收客户端传过来的数据线程
thread = new ConnectedThread(clientSocket);
// 线程开始
thread.start();
}
}
// 判断是否拿到输出流
if (os != null) {
os.write(code);
}
Toast.makeText(BuletoothClientActivity.this, "发送信息成功,请查收", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
// 如果发生异常则告诉用户发送失败
Toast.makeText(BuletoothClientActivity.this, "发送信息失败", Toast.LENGTH_SHORT).show();
}
}
受信データのスレッド
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d("logcat", "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.d("logcat", "temp sockets not created" + e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
if (Thread.interrupted()) {
Log.d("logcat", "return");
return;
}
Log.d("logcat", "BEGIN mConnectedThread");
byte[] buffer = new byte[128];
int bytes;
while (true) {
synchronized (this) {
try {
while (mmInStream.available() == 0) {
}
try {
Thread.sleep(100); //当有数据流入时,线程休眠一段时间
} catch (InterruptedException e) {
e.printStackTrace();
}
bytes = mmInStream.read(buffer);
Log.d("logcat", "count " + bytes);
Message msg = new Message();
msg.obj = new String(buffer, 0, bytes, "utf-8");
Log.d("logcat", "data " + msg.obj);
handler.sendMessage(msg);
} catch (IOException e) {
Log.e("logcat", "disconnected", e);
break;
}
}
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e("logcat", "断开连接", e);
}
}
}
}
通信テスト
アンドリューステストは、送信し
たクライアントからのフィードバックOK、データによるサービス終了を
クライアントが正常にメッセージを受信します
APPは、クライアントとしてのAndroid携帯電話にインストールされます
:HC-05 Bluetoothモジュールの接続は以下のとおりである
シリアル通信HC-05をテストするためにシリアルデバッグツールを使用して
アドレスGitHubのに必要がある完全なDEMOのコメント欄を