我正在开发一款Android应用,用于连接支持蓝牙串口配置文件(SPP)的简单设备。我能够成功连接和交换数据,但每次连接时都会提示用户输入设备的PIN。
在蓝牙设置中,我可以看到该设备是“未连接配对”。
提示是一个问题,因为如果用户输入PIN的速度不够快,套接字连接会超时,用户必须重试。
以下代码的相关位......
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.scanlayout);
...
_Context = this;
_ActivityCreated = true;
_ReceivedText = (TextView)findViewById(R.id._Scan_Results);
_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
_BluetoothDevice = _BluetoothAdapter.getRemoteDevice(_DeviceAddress);
_BusySpinner = ProgressDialog.show(_Context, "", "Connecting to scanner...");
new ConnectToScannerTask().execute(_BluetoothDevice);
}
private final Handler scanReceivedHandler = new Handler()
{
@Override
public void handleMessage(Message message)
{
String receivedText = (String)message.obj;
_ReceivedText.setText(receivedText);
}
};
private class ConnectToScannerTask extends AsyncTask<BluetoothDevice, Void, InputStream>
{
@Override
protected InputStream doInBackground(BluetoothDevice... params)
{
BluetoothDevice device = params[0];
try
{
_Socket = device.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
_BluetoothAdapter.cancelDiscovery();
_Socket.connect();
return _Socket.getInputStream();
}
catch (IOException e)
{
Log.d("ScanActivity.ConnectToScannerTask.doInBackground", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(final InputStream result)
{
_BusySpinner.dismiss();
if (result == null)
{
_ReceivedText.setText("Failed to connect to scanner.");
return;
}
Thread thread = new Thread()
{
@Override
public void run()
{
byte[] buffer = new byte[1024];
try
{
while (_ActivityCreated)
{
Arrays.fill(buffer, (byte) 0);
int bytesRead = result.read(buffer);
if (bytesRead > 0)
{
Message message = scanReceivedHandler.obtainMessage(1, new String(buffer));
message.sendToTarget();
Log.e("ScanActivity", "Received: " + new String(buffer));
}
if (bytesRead < 0)
{
break;
}
}
Message message = scanReceivedHandler.obtainMessage(1, "End of Stream");
message.sendToTarget();
Log.e("ScanActivity", "End of Stream");
}
catch (Exception e)
{
Message message = scanReceivedHandler.obtainMessage(1, "Connection to scanner lost");
message.sendToTarget();
Log.e("ScanActivity", e.getMessage());
}
try
{
_Socket.close();
}
catch (IOException e)
{
Log.e("ScanActivity", e.getMessage());
}
}
};
thread.start();
}
}
只要用户快速输入PIN,连接就会成功,我就可以接收数据了。我的预感是我错过了设置步骤。我不熟悉BT的细节,所以我不确定这可能是设备强制输入PIN的问题吗?
答案 0 :(得分:1)
这可能是远程设备无法保持设备绑定的问题(意味着存储要在后续连接中使用的链接密钥),这将导致每次重新配对并要求输入PIN。 Android应该在成功配对后存储绑定信息。