我有一个连接到类似于以下设备的功能(在这种情况下为蓝牙信用卡机):
private void pinPar(final String name, final String address) {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
pinpadSelected = new PinpadObject(name, address, false);
BluetoothConnectionProvider bluetoothConnectionProvider = new BluetoothConnectionProvider(MainActivity.this, pinpadSelected);
bluetoothConnectionProvider.setDialogMessage("Connecting to pinpad");
bluetoothConnectionProvider.setWorkInBackground(false);
bluetoothConnectionProvider.setConnectionCallback(new StoneCallbackInterface() {
@Override
public void onSuccess() {
Toast.makeText(getApplicationContext(), "Pinpad connected", Toast.LENGTH_SHORT).show();
out.println("Connected to " + name + " at " + address);
}
@Override
public void onError() {
Toast.makeText(getApplicationContext(), "Connection failed", Toast.LENGTH_SHORT).show();
out.println("Failed connecting to "+ name + " at " + address);
}
}
);
bluetoothConnectionProvider.execute();
}
});
}
我一直在寻找一个类似的函数,pinUnpar
该函数将简单地关闭该连接,但是bluetoothConnectionProvider
没有任何方法close()
或类似的东西。我怎样才能做到这一点?
好的,我已经有一段时间没有在android上处理过蓝牙了,但是可以了。使用蓝牙连接设备的方式有很多种,但是我特别喜欢一种简单的方式,因为它不需要扫描要连接的设备,也不需要配对。如下:
首先,您需要一个客户端和服务器都知道的通用UUID,因为在这种情况下您的服务器是蓝牙信用卡机器,因此您需要找出用于连接的UUID是什么(不要太难,如果未在机器手册中写明,则可以使用笔记本电脑自己检测出来)。
客户代码:-
BluetoothAdapter adapter;
adapter= BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device;
device= adapter.getRemoteDevice(serverAddress); //address here would be the address value
//passed to your function
BluetoothSocket socket= device.createInsecureRfcommSocketToServiceRecord(uuid);
//here uuid is the UUID the device uses as mentioned perviously
socket.connect();
OutputStream ouput=socket.getOutputStream();
InputStream input=socket.getInputStream();
这样,您就可以与计算机建立连接,您可以在其中写入任何内容,也可以读取其中的任何内容。我假设您不是在对信用卡机进行编程,所以我省略了相应的服务器代码。
由于此代码使用简单的流和套接字,因此很容易关闭,也很容易打开。
编辑:-
这仅对BT连接使用android API,请注意,此代码使用不安全的rfcomm,这意味着它容易受到MITMA和其他此类攻击的攻击。如果您不希望这样做,可以改为
device.createInsecureRfcommSocketToServiceRecord(uuid)
和
device.createRfcommSocketToServiceRecord(uuid);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句