[英]Android Bluetooth accept() / connect() with already paired devices
我無法通過藍牙連接兩台Android設備,只有在之前配對時才會發生。 我正在運行一個作為服務器,另一個作為客戶端。
以下是服務器端的一系列事項:
在客戶端:
當客戶端和服務器之前從未配對時,上述過程對我來說非常好。 但是,Android在設備列表中注冊后,它們將不可避免地在connect()/ accept()階段超時。
我一直在尋找解決方案幾天,並嘗試了很多東西,包括這一個: 連接到已經配對的藍牙設備
反射方法對我也不起作用。 似乎connect()會立即返回,但是當我嘗試getOutputStream()時,我得到一個異常。 在accept()方面,它甚至沒有注冊有人試圖連接。 我認真地需要一些幫助或指針來讓設備在之前配對后建立連接。
以下是有關設備的一些信息:
提前謝謝你。 我在Android和藍牙方面大約有兩周的時間,所以如果您發現任何缺失的步驟或最佳做法,請同時指出它們。
在我嘗試連接到綁定設備的客戶端中,我只是在BluetoothAdapter.getBondedDevices()
找到的BluetoothAdapter.getBondedDevices()
上調用它。 這不起作用。
為了正確建立藍牙連接,我必須做一些類似於下面的偽代碼:
BluetoothDevice bonded = a device from BluetoothAdapter.getBondedDevices();
BluetoothDevice actual = BluetoothAdapter.getRemoteDevice(bonded.getAddress());
BluetoothSocket socket = actual.createRfcommSocketToServiceRecord(SOME_UUID);
socket.connect();
我完全按照藍牙聊天示例: 藍牙聊天服務得到了這個答案。 為什么它不能從getBondedDevices()
在設備上工作超出我的范圍。 也許對Android有更多了解的人可以回答這個問題。
看看這個例子: http : //developer.android.com/resources/samples/BluetoothChat/index.html 。
這可以解釋藍牙設備如何連接和轉換信息。
private static BluetoothSocket mSocket;
BluetoothDevice selectDevice = null;
void connectDevice(){
if(mSocket == null) {
//Log.d(TAG, "Socket is null");
UUID SPP_UUID = UUID
.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
Set<BluetoothDevice> bondedDevices = BluetoothAdapter
.getDefaultAdapter().getBondedDevices();
//Log.d(TAG, "Size: " + bondedDevices.size());
/**
* Select your divice form paired devices
*/
for (BluetoothDevice bluetoothDevice : bondedDevices) {
selectDevice = bluetoothDevice;
//Log.d(TAG, bluetoothDevice.getName()+" "+bluetoothDevice.getAddress());
}
if(selectDevice.getBondState() == selectDevice.BOND_BONDED) {
//Log.d(TAG, selectDevice.getName());
try {
mSocket = selectDevice.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e1) {
// TODO Auto-generated catch block
//Log.d(TAG, "socket not created");
e1.printStackTrace();
}
try {
mSocket.connect();
} catch (IOException e) {
try {
mSocket.close();
//Log.d(TAG, "Cannot connect");
} catch (IOException e1) {
//Log.d(TAG, "Socket not closed");
e1.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.