android.bluetooth.BluetoothSocket 无法连接
我已经尝试了其他评论中的所有建议但无济于事,我希望有人可以帮助我。我已经为这个问题苦苦挣扎了三天了。我非常确定我的 UUID 是正确的,并且我知道蓝牙访问已在清单中启用。
我正在尝试将我的 Android 应用程序连接到在 Fedora 中运行的 python 服务器。它间歇性地起作用,现在根本不起作用。我收到的 android 异常通常是这样的。这些异常是在 btSocket.connect(); 时抛出的。在下面附加的代码中执行。
12-09 05:08:42.331: ERROR/BluetoothService(676): java.io.IOException: Service discovery failed
或者
12-09 05:27:00.757: ERROR/BluetoothService(729): java.io.IOException: Service discovery failed
这是我的 Android 蓝牙类,应该可以处理所有事情。当主应用程序类收到套接字已连接的消息时启动该线程。我的蓝牙课程基于 http://www.anddev.org/viewtopic.php ?p=35487#35487。
package spin.halo;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.bluetooth.*;
import android.os.Handler;
import android.util.Log;
public class BluetoothService extends Thread{
private static final String TAG = "BluetoothService";
private static final boolean D = true;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private InputStream inStream = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String address;
private Handler appHandler;
public BluetoothService(Handler h) {
if (D)
Log.e(TAG, "+++ ON CREATE +++");
appHandler = h;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "NO BT ADAPTER!");
return;
}
if (!mBluetoothAdapter.isEnabled()) {
Log.e(TAG, "Bluetooth is not enabled!");
return;
}
if (D)
Log.e(TAG, "+++ DONE IN ON CREATE, GOT LOCAL BT ADAPTER +++");
}
public void connectToServer() {
connectToServer("60:33:4B:25:0D:37");
}
public void connectToServer(String serverMacAddress) {
address = serverMacAddress;
//
if (D) {
Log.e(TAG, "+ ABOUT TO ATTEMPT CLIENT CONNECT +");
}
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.v(TAG, "REMOTE DEVICE: " + device.toString());
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
Log.v(TAG, "SOCKET: " + btSocket.toString());
} catch (Exception e) {
Log.e(TAG, "ON RESUME: Socket creation failed.", e);
}
/* Discovery may be going on, e.g., if you're running a
'scan for devices' search from your handset's Bluetooth
settings, so we call cancelDiscovery(). It doesn't hurt
to call it, but it might hurt not to... discovery is a
heavyweight process; you don't want it in progress when
a connection attempt is made.*/
mBluetoothAdapter.cancelDiscovery();
// Blocking connect, for a simple client nothing else can
// happen until a successful connection is made, so we
// don't care if it blocks.
try {
btSocket.connect();
Log.e(TAG, "ON RESUME: BT connection established, data transfer link open.");
appHandler.sendMessage(appHandler.obtainMessage(ValidationApp.BT_CONNECTION_MADE, ""));
} catch (IOException e) {
try {
Log.e(TAG, "ON RESUME: Could not connect", e);
btSocket.close();
} catch (IOException e2) {
Log.e(TAG, "ON RESUME: Unable to close socket during connection failure", e2);
}
}
// Create output stream
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}
// Create input stream
try {
inStream = btSocket.getInputStream();
} catch (IOException e) {
Log.e(TAG, "Input stream creation failed.", e);
}
}
public void write(String message) {
if(message.length() > 0) {
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
}
}
public void run() {
LineNumberReader mLineReader = new LineNumberReader(new InputStreamReader(inStream));
while(true) {
try {
String message = mLineReader.readLine();
if(D) {Log.v(TAG, "Bluetooth says: " + message);}
Log.v(TAG, appHandler.obtainMessage(ValidationApp.BT_MESSAGE, message).toString());
appHandler.sendMessage(appHandler.obtainMessage(ValidationApp.BT_MESSAGE, message));
} catch (IOException e) {
Log.e(TAG, "startListen: ", e);
}
}
}
}
我的 python 代码的关键部分如下。我对这段代码很有信心。
# pybluez library
import bluetooth
server_socket = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
client_sockets = []
server_socket.bind(("",bluetooth.PORT_ANY))
port = server_socket.getsockname()[1]
uuid = "00001101-0000-1000-8000-00805F9B34FB"
print "Listening for devices..."
# advertise service
server_socket.listen(1)
bluetooth.advertise_service( server_socket, "Validation Host",
service_id = uuid,
service_classes = [ uuid, bluetooth.SERIAL_PORT_CLASS ],
profiles = [ bluetooth.SERIAL_PORT_PROFILE ],
)
# accept incoming connections
client_sock, client_info = server_socket.accept()
client_sockets.append(client_sock)
print "Accepted Connection from ", client_info
感谢您的浏览。
I've tried all the suggestions in other comments without avail and I hope someone can help me. I've been struggling with this problem for three days now. I'm quite sure my UUIDs are correct and I know that the bluetooth access is enabled in the manifest.
I'm trying to connect my android application to a python server running in Fedora. It has worked intermittently and not at all right now. The android exceptions I'm receiving generally are along the lines of.. These are thrown when btSocket.connect(); is executed in the code attached below.
12-09 05:08:42.331: ERROR/BluetoothService(676): java.io.IOException: Service discovery failed
or
12-09 05:27:00.757: ERROR/BluetoothService(729): java.io.IOException: Service discovery failed
This is my android bluetooth class that is supposed to take care of everything. The thread is started when the main application class receives a message that the socket has been connected to. My bluetooth class is based on http://www.anddev.org/viewtopic.php?p=35487#35487.
package spin.halo;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.bluetooth.*;
import android.os.Handler;
import android.util.Log;
public class BluetoothService extends Thread{
private static final String TAG = "BluetoothService";
private static final boolean D = true;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private InputStream inStream = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String address;
private Handler appHandler;
public BluetoothService(Handler h) {
if (D)
Log.e(TAG, "+++ ON CREATE +++");
appHandler = h;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "NO BT ADAPTER!");
return;
}
if (!mBluetoothAdapter.isEnabled()) {
Log.e(TAG, "Bluetooth is not enabled!");
return;
}
if (D)
Log.e(TAG, "+++ DONE IN ON CREATE, GOT LOCAL BT ADAPTER +++");
}
public void connectToServer() {
connectToServer("60:33:4B:25:0D:37");
}
public void connectToServer(String serverMacAddress) {
address = serverMacAddress;
//
if (D) {
Log.e(TAG, "+ ABOUT TO ATTEMPT CLIENT CONNECT +");
}
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.v(TAG, "REMOTE DEVICE: " + device.toString());
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
Log.v(TAG, "SOCKET: " + btSocket.toString());
} catch (Exception e) {
Log.e(TAG, "ON RESUME: Socket creation failed.", e);
}
/* Discovery may be going on, e.g., if you're running a
'scan for devices' search from your handset's Bluetooth
settings, so we call cancelDiscovery(). It doesn't hurt
to call it, but it might hurt not to... discovery is a
heavyweight process; you don't want it in progress when
a connection attempt is made.*/
mBluetoothAdapter.cancelDiscovery();
// Blocking connect, for a simple client nothing else can
// happen until a successful connection is made, so we
// don't care if it blocks.
try {
btSocket.connect();
Log.e(TAG, "ON RESUME: BT connection established, data transfer link open.");
appHandler.sendMessage(appHandler.obtainMessage(ValidationApp.BT_CONNECTION_MADE, ""));
} catch (IOException e) {
try {
Log.e(TAG, "ON RESUME: Could not connect", e);
btSocket.close();
} catch (IOException e2) {
Log.e(TAG, "ON RESUME: Unable to close socket during connection failure", e2);
}
}
// Create output stream
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}
// Create input stream
try {
inStream = btSocket.getInputStream();
} catch (IOException e) {
Log.e(TAG, "Input stream creation failed.", e);
}
}
public void write(String message) {
if(message.length() > 0) {
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
}
}
public void run() {
LineNumberReader mLineReader = new LineNumberReader(new InputStreamReader(inStream));
while(true) {
try {
String message = mLineReader.readLine();
if(D) {Log.v(TAG, "Bluetooth says: " + message);}
Log.v(TAG, appHandler.obtainMessage(ValidationApp.BT_MESSAGE, message).toString());
appHandler.sendMessage(appHandler.obtainMessage(ValidationApp.BT_MESSAGE, message));
} catch (IOException e) {
Log.e(TAG, "startListen: ", e);
}
}
}
}
The key portions of my python code are below. I am quite confident about this code.
# pybluez library
import bluetooth
server_socket = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
client_sockets = []
server_socket.bind(("",bluetooth.PORT_ANY))
port = server_socket.getsockname()[1]
uuid = "00001101-0000-1000-8000-00805F9B34FB"
print "Listening for devices..."
# advertise service
server_socket.listen(1)
bluetooth.advertise_service( server_socket, "Validation Host",
service_id = uuid,
service_classes = [ uuid, bluetooth.SERIAL_PORT_CLASS ],
profiles = [ bluetooth.SERIAL_PORT_PROFILE ],
)
# accept incoming connections
client_sock, client_info = server_socket.accept()
client_sockets.append(client_sock)
print "Accepted Connection from ", client_info
Thanks for taking a look.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码看起来总体不错,我假设您只是从一些示例中复制并粘贴它。
部分 Android 手机(例如 HTCdesire)存在 bug,导致 device.createRfcommSocketToServiceRecord 方法失败。我建议采用以下方法:
1)尝试使用提供的 pythong 脚本在两台 Linux 计算机之间聊天
http://www.radekdostal.com(你知道在哪里)
这样您就可以验证您的 Linux 设置是否正常工作。
2) 尝试启动从计算机到 Android 的连接(使用 android-bluetooth-chat-client-python) 请注意,默认的 BluetoothChat 演示只能在第一次尝试时接受连接。
3) 尝试从 Android 手机连接到 Linux 计算机,但使用以下代码手动指定 RFCOMM 通道号
您需要使用以下代码找出您的 RFCOMM 通道号
Your code looks generally good, I assume you just copy and paste it from some examples.
There is a bug in some Android phones such as HTC desire, which cause method device.createRfcommSocketToServiceRecord to fail. I would suggest following approach:
1) Trying to chat between two linux computer using pythong scripts provided at
http://www.radekdostal.com (you know where)
by that you verify that your Linux setup is working properly.
2) Trying to initiate connection from computer to Android (use android-bluetooth-chat-client-python) Be aware that default BluetoothChat demo is able to accept connection only on the first try.
3) Try connecting from Android phone to linux computer, but manually specify RFCOMM channel number using following code
You will need to find out what is your RFCOMM channel number using