gpt4 book ai didi

java - Android 中与蓝牙设备的第二次连接失败

转载 作者:太空狗 更新时间:2023-10-29 15:04:59 25 4
gpt4 key购买 nike

我正在尝试在 Android 4.4 中建立蓝牙连接,但 BluetoothSocket 的连接方法似乎运行异常。我的应用程序可以假定设备已经绑定(bind),因此我可以通过 MAC 地址进行连接。问题是它在设备第一次绑定(bind)时立即完美连接,但如果我重新启动它,连接不会建立并且会发生超时。我在一个 while 循环中执行此操作直到它连接,但是对于真正的解决方案来说它花费的时间太长或者它根本不起作用。这是我的代码示例:

public class BluetoothManager{

private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket socket;
private OutputStream output;
private InputStream input;

public BluetoothManager() {
/***************/
/* Constructor */
/***************/

// lock = new Object();

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}

public boolean turnOnBluetooth() {
/**************************************/
/* Turn on Bluetooth an notify result */
/**************************************/

// check if bluetooth is supported
if (bluetoothAdapter == null) {
return (false);
} else {
// enable Bluetooth if not enabled yet
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
}
while (!bluetoothAdapter.isEnabled()) {
Log.i("Debug", "Waiting for bluetooth to turn on");
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
return (true);
}
}

public boolean turnOffBluetooth() {
/***************************************/
/* Turn off Bluetooth an notify result */
/***************************************/

// check if bluetooth is supported
if (bluetoothAdapter == null) {
return (false);
} else {
// disable Bluetooth if not enabled yet
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
}
while (bluetoothAdapter.isEnabled()) {
Log.i("Debug
Thread.sleep(500);
} catch (Exception e) {
}
}
return (true);
}
}

public boolean configureBluetooth(String MACaddress) {
/***********************************************************************/
/* Configures to the specified bluetooth device and returns the result */
/***********************************************************************/

Log.i("Debug", "Connecting to Bluetooth Device");
bluetoothDevice = bluetoothAdapter.getRemoteDevice(MACaddress);

return (true);
}

@SuppressLint("NewApi")
public void createSocket() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
final UUID serialUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");

socket = null;
output = null;
input = null;


Method m = bluetoothDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class });
socket = (BluetoothSocket)m.invoke(bluetoothDevice, 1);
}


@SuppressLint("NewApi")
public void connect() throws IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
/************************************/
/* Connects to the bluetooth device */
/************************************/

Log.i("Debug", "en connect");
while (!socket.isConnected()) { // we try until the connection is established
try {
socket.connect();
output = socket.getOutputStream();
input = socket.getInputStream();
} catch (IOException e) {
Log.i("Depuración", "Connection not established. Another run : "+e);
try {
Thread.sleep(1000);
} catch (Exception e1) {
}
}
}
}

public void terminateConnection() throws IOException {
Log.i("Debug", "terminating connection");
if(output!=null){
Log.i("Debug", "output!=null - stop streaming");
stopStreaming();
}

try {
Thread.sleep(100);
} catch (Exception e) {
}
if(input!=null){
Log.i("Debug", "input!=null");
input.close();
input=null;
}
if(output!=null){
Log.i("Depuración", "output!=null");
output.close();
output = null;
}
if(socket!=null){
Log.i("Debug", "socket!=null");
socket.close();
socket=null;
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
turnOffBluetooth();
try {
Thread.sleep(100);
} catch (Exception e) {
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
System.gc();
}

如果我从我的 MainActivity 调用此方法,它会起作用,但仅限于设备第一次绑定(bind)时。如果我再次启动该应用程序,我会在尝试连接到设备时遇到异常:

socket.connect();

我怀疑这与我终止连接的方式有关,但我无法弄清楚。以下是方法的顺序调用:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

bluetoothManager = new BluetoothManager();
try {
bluetoothManager.terminateConnection();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
bluetoothManager.turnOffBluetooth();
bluetoothManager.turnOnBluetooth();

boolean configured = false;
while (!configured) {
Log.i("Debug", "Configuration Attemp");
configured = bluetoothManager.configureBluetooth(MACaddress);
}

Log.i("Debug", "Bluetooth Configured");

try {
bluetoothManager.createSocket();
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

Log.i("Depuración", "Socket created");

try {
bluetoothManager.connect();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Log.i("Debug", "Connected!!!!");

protected void onPause() {
Log.i("Debug", "On pause");

// TODO Auto-generated method stub
try {
bluetoothManager.terminateConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bluetoothManager = null;
System.gc();
super.onPause();
};

我已经尝试解决这个问题好几天了,但我仍然找不到原因。

最佳答案

好吧,我不是这方面的专业人士,但看起来您应该在应用程序关闭时调用 bluetoothManager.terminateConnection();,比如说 onDestroy,但是不是 onCreate;如果以前的连接没有正确终止,我也有连接问题。只需尝试将此方法添加到您的主要 Activity 中:

  @Override
public void onDestroy(){
if (bluetoothManager != null){
bluetoothManager.terminateConnection();
}
super.onDestroy();
}

希望对您有所帮助。

关于java - Android 中与蓝牙设备的第二次连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22910682/

25 4 0
文章推荐: android - Spring Rest Template Put方法无效,为什么?
文章推荐: html - page-break/webkit-region-break 不再在 chrome 中工作了?
文章推荐: c - 在哪里可以找到用 OpenCL 或 CUDA 编写的对象检测(汽车、人)的工作代码示例?
文章推荐: html - Ionic 框架中
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com