【发布时间】:2010-03-13 07:42:56
【问题描述】:
我在让我的设备在 Android 中配对时遇到问题。如果我进入设置并手动配对它们,我可以使用以下代码让它们连接:
服务器
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.connect);
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(discoverableIntent, REQUEST_ENABLE_BT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == REQUEST_ENABLE_BT)
{
if(resultCode == RESULT_CANCELED)
{
new AlertDialog.Builder(this)
.setTitle(R.string.error)
.setMessage(R.string.bluetooth_unavailable)
.setPositiveButton(android.R.string.ok, AndroidUtils.DismissListener)
.create()
.show();
}
else
{
mServerSocket = mAdapter.listenUsingRfcommWithServiceRecord("Moo Productions Bluetooth Server", mUUID);
mState = State.ACCEPTING;
BluetoothSocket socket = mServerSocket.accept();
mServerSocket.close();
connected(socket);
}
}
}
客户
Set<BluetoothDevice> pairedDevices = mAdapter.getBondedDevices();
BluetoothSocket socket = null;
// Search the list of paired devices for the right one
for(BluetoothDevice device : pairedDevices)
{
try
{
mState = State.SEARCHING;
socket = device.createRfcommSocketToServiceRecord(mUUID);
mState = State.CONNECTING;
socket.connect();
connected(socket);
break;
}
catch (IOException e)
{
socket = null;
continue;
}
}
但如果设备尚未配对,它会在没有连接到有效套接字的情况下退出 foreach。在那种情况下,我开始发现。
// If that didn't work, discover
if(socket == null)
{
mState = State.SEARCHING;
mReceiver = new SocketReceiver();
mContext.registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
mAdapter.startDiscovery();
}
// ... Later ...
private class SocketReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction()))
{
try
{
// Get the device and try to open a socket
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(mUUID);
mState = State.CONNECTING;
socket.connect();
// This is our boy, so stop looking
mAdapter.cancelDiscovery();
mContext.unregisterReceiver(mReceiver);
connected(socket);
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
但它永远找不到其他设备。我从来没有得到一个配对对话框,当我单步执行时,我看到它发现了正确的设备,但它无法连接到这个异常java.io.IOException: Service discovery failed。关于我缺少什么的任何想法?
【问题讨论】:
-
嗨 CaseyB 你好吗?我也遇到了同样的问题..意味着当我从一个设备连接到另一个设备时,它会再次连接,如果我从第二个设备到第一个设备日志猫显示消息“服务发现失败”,那么为什么它没有从我尝试过的其他设备有不同的 UUId,请帮助我。
-
我一直无法弄清楚这一点。我转移到另一个项目。对不起。