@Mackovich 非常感谢您以及其他试图提供帮助的人。为了其他有同样问题的人。这是我搜索了很长时间后的解决方案。
P.S 我想提一件事,我读到了“服务”,它是正确的方式。但我以其他简单的方式做到了。
我有两个活动 (1) 蓝牙搜索活动和 (2) 方向活动。
我的问题是我试图在活动 (1) 中执行所有蓝牙 stuuf,只是将命令从活动 (2) 发送到 (1),这会将其发送到遥控车。这是问题,因为正如@Mackovich 所说,该活动可能被破坏。
我解决了什么问题?
在活动 (1) 中,我使用 ListView 来显示蓝牙设备广播并获取这些设备信息。然后使用 Intent 将这些信息传递给活动 (2)。已设置连接并尝试发送活动 (1)。
注意:要建立蓝牙连接,您需要两个重要信息:
1. UUID(我们听说过)。
2。目标蓝牙设备的 MAC 地址。 (我们从活动(1)中得到它)。
所以,首先我们需要蓝牙适配器、阵列适配器(用于隐藏找到的设备的信息)和广播接收器。
//Declare Bluetooth Stuff
BluetoothAdapter mBluetoothAdapter; // Make instance of the Bluetooth
ArrayAdapter mArrayAdapter; // Array where the devices will be stored
private static final int ENABLE_BT_REQUEST_CODE = 1;
private static final int DISCOVERABLE_BT_REQUEST_CODE = 2;
private static final int DISCOVERABLE_DURATION = 300;
public static String EXTRA_ADDRESS = "Device_MAC_Address";
//In order for the bluetooth to discover the devices that broadcasting and obtain their info.
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Whenever a remote Bluetooth device is found
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice mBluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(mBluetoothDevice.getName() + "\n" + mBluetoothDevice.getAddress());
} else {
Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
}
};
然后,在用户选择列出的设备之一后。我们将获取设备的MAC地址并发送给activity(2)进行连接和发送。
//Obtain the value of the item clicked as String value
String itemValue = (String) DevicesList.getItemAtPosition(position);
//Extract the MAC Address from the String value above
String MAC = itemValue.substring(itemValue.length() - 17);
// Make an intent to start next activity.
Intent i = new Intent(BluetoothActivity.this, NavigationActivity.class);
//Change the activity.
i.putExtra(EXTRA_ADDRESS, MAC); //this will be received at NavigationActivity(class) Activity
startActivity(i);
}
});
现在,我们解决了活动之间传递数据的问题。因为不需要敌人传递数据。
这是针对原始帖子中的问题(1)。
关于问题(2)。
问题是您是否使用了 Google 提供的代码。有些事情你需要调整。在ConnectThread 类中的run 方法中,您需要定义您创建的ConnectedThread 类的对象。通过这种方式你将传递BluetoothSocket用于连接发送数据的变量抛出它。
这也解决了问题 (3)。是的,你需要这两个类。
正如我在原帖中所说,我是初学者。所以,我认为向初学者解释的最好方法是像一个人一样思考。在这种情况下,我实际上是初学者。
我希望这会对其他人有所帮助。如果有人发现这有任何问题,请注意。请告诉我纠正它。
谢谢。