目标:当我知道它已连接时,打开当前连接的A2DP设备的蓝牙插座。
为了连接套接字,我需要该设备的MAC地址。
正如我目前所了解的那样,有两种听众可以获得蓝牙状态:
1- BluetoothAdapter.getProfileProxy(),如此处所述How to get bluetooth connected devices using BluetoothHeadset API
2- BluetoothDevice.ACTION_ACL_CONNECTED上的广播接收器,如此处所述How to programmatically tell if a Bluetooth device is connected? (Android 2.2)
因此我需要在连接A2DP设备时使用它们来触发...然后获取此设备的MAC地址(然后打开btSocket): 在BroadcastReceiver" BluetoothDevice.ACTION_ACL_CONNECTED"内启动btAdapter.getProfileProxy,但延迟时间为3秒,以便连接。
这是唯一(复杂)的方法吗?
onCreate{
context.registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
context.registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "Action received\n");
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
{
Log.d(TAG, "ACTION_ACL_CONNECTED received\n");
timerHandler.postDelayed(timerRunnableBtConnection, 3000);
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action))
{
Log.d(TAG, "ACTION_ACL_DISCONNECTED received\n");
btAdapter.closeProfileProxy(BluetoothProfile.A2DP, btA2dp);
}
}
private Runnable timerRunnableBtConnection = new Runnable() {
@Override
public void run() {
btAdapter.getProfileProxy(intelloApplication.getAppContext(), mProfileListener, BluetoothProfile.A2DP);
}
};
};
// Define Service Listener of BluetoothProfile
// then create the btSocket on it
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
Log.d(TAG, "Bluetooth connected\n");
btA2dp = (BluetoothA2dp) proxy;
List<BluetoothDevice> devices = btA2dp.getConnectedDevices();
Log.d(TAG, "List of " + devices.size() + " device\n");
for ( final BluetoothDevice dev : devices ) {
String address = dev.getAddress();
Log.d(TAG, "Name: " + dev.getName() + " and address: " + address + "\n");
btDevice = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(btDevice);
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
useBluetooth = true;
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
useBluetooth = false;
Log.d(TAG, "....Close connection.");
} catch (IOException e2) {
Log.d(TAG, "Unable to close socket during connection failure");
Log.d(TAG, e2.getMessage());
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
}
}
}
public void onServiceDisconnected(int profile) {
if (profile == BluetoothProfile.A2DP) {
Log.d(TAG, "Bluetooth disconnected\n");
}
}
};