gpt4 book ai didi

java - 连接到 Android 上已配对的设备时提示输入蓝牙 PIN

转载 作者:行者123 更新时间:2023-11-30 04:49:49 24 4
gpt4 key购买 nike

我正在开发一个 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 的问题?

最佳答案

这可能是远程设备没有保持设备绑定(bind)的问题(意味着存储链接 key 以用于后续连接),这将导致每次重新配对并需要输入 PIN。Android 通常应在成功配对后存储绑定(bind)信息。

关于java - 连接到 Android 上已配对的设备时提示输入蓝牙 PIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3839795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com