/* * Copyright 2021 HIMSA II K/S - www.himsa.com. * Represented by EHIMA - www.ehima.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.bluetooth; import static android.bluetooth.BluetoothUtils.getSyncTimeout; import android.annotation.CallbackExecutor; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.RequiresPermission; import android.annotation.SdkConstant; import android.annotation.SuppressLint; import android.annotation.SystemApi; import android.bluetooth.annotations.RequiresBluetoothConnectPermission; import android.content.AttributionSource; import android.content.Context; import android.os.IBinder; import android.os.RemoteException; import android.util.CloseGuard; import android.util.Log; import com.android.modules.utils.SynchronousResultReceiver; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.Executor; import java.util.concurrent.TimeoutException; /** * This class provides a public APIs to control the Bluetooth Hearing Access Profile client service. * *
BluetoothHapClient is a proxy object for controlling the Bluetooth HAP
* Service client via IPC. Use {@link BluetoothAdapter#getProfileProxy} to get the
* BluetoothHapClient proxy object.
* @hide
*/
@SystemApi
public final class BluetoothHapClient implements BluetoothProfile, AutoCloseable {
private static final String TAG = "BluetoothHapClient";
private static final boolean DBG = false;
private static final boolean VDBG = false;
private final Map This intent will have 3 extras:
* {@link #EXTRA_STATE} or {@link #EXTRA_PREVIOUS_STATE} can be any of
* {@link #STATE_DISCONNECTED}, {@link #STATE_CONNECTING},
* {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTING}.
* @hide
*/
@SystemApi
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED,
})
@SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_HAP_CONNECTION_STATE_CHANGED =
"android.bluetooth.action.HAP_CONNECTION_STATE_CHANGED";
/**
* Intent used to broadcast the device availability change and the availability of its
* presets. Please note that in the binaural case, there will be two different LE devices for
* the left and right side and each device will have their own availability event.
*
* This intent will have 2 extras:
* The same {@link Callback} object used when calling
* {@link #registerCallback(Executor, Callback)} must be used.
*
* Callbacks are automatically unregistered when application process goes away
*
* @param callback user implementation of the {@link Callback}
* @throws NullPointerException when callback is null or IllegalArgumentException when no
* callback is registered
* @hide
*/
@SystemApi
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED,
})
public void unregisterCallback(@NonNull Callback callback) {
Objects.requireNonNull(callback, "callback cannot be null");
if (DBG) log("unregisterCallback");
synchronized (mCallbackExecutorMap) {
if (mCallbackExecutorMap.remove(callback) == null) {
throw new IllegalArgumentException("This callback has not been registered");
}
}
// If the callback map is empty, we unregister the service-to-app callback
if (mCallbackExecutorMap.isEmpty()) {
try {
final IBluetoothHapClient service = getService();
if (service != null) {
final SynchronousResultReceiver The device should already be paired.
* Connection policy can be one of {@link #CONNECTION_POLICY_ALLOWED},
* {@link #CONNECTION_POLICY_FORBIDDEN}, {@link #CONNECTION_POLICY_UNKNOWN}
*
* @param device Paired bluetooth device
* @param connectionPolicy is the connection policy to set to for this profile
* @return true if connectionPolicy is set, false on error
* @hide
*/
@SystemApi
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED,
})
public boolean setConnectionPolicy(@NonNull BluetoothDevice device,
@ConnectionPolicy int connectionPolicy) {
if (DBG) log("setConnectionPolicy(" + device + ", " + connectionPolicy + ")");
Objects.requireNonNull(device, "BluetoothDevice cannot be null");
final IBluetoothHapClient service = getService();
final boolean defaultValue = false;
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (mAdapter.isEnabled() && isValidDevice(device)
&& (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
|| connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
try {
final SynchronousResultReceiver The connection policy can be any of:
* {@link #CONNECTION_POLICY_ALLOWED}, {@link #CONNECTION_POLICY_FORBIDDEN},
* {@link #CONNECTION_POLICY_UNKNOWN}
*
* @param device Bluetooth device
* @return connection policy of the device or {@link #CONNECTION_POLICY_FORBIDDEN} if device is
* null
* @hide
*/
@SystemApi
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED,
})
public @ConnectionPolicy int getConnectionPolicy(@Nullable BluetoothDevice device) {
if (VDBG) log("getConnectionPolicy(" + device + ")");
final IBluetoothHapClient service = getService();
final int defaultValue = BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (mAdapter.isEnabled() && isValidDevice(device)) {
try {
final SynchronousResultReceiver Users are expected to get group identifier for each of the connected
* device to discover the device grouping. This allows them to make an informed
* decision which devices can be controlled by single group API call and which
* require individual device calls.
*
* Note that some binaural HA devices may not support group operations,
* therefore are not considered a valid HAP group. In such case -1 is returned
* even if such device is a valid Le Audio Coordinated Set member.
*
* @param device
* @return valid group identifier or -1
* @hide
*/
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED,
})
public int getHapGroup(@NonNull BluetoothDevice device) {
final IBluetoothHapClient service = getService();
final int defaultValue = BluetoothCsipSetCoordinator.GROUP_ID_INVALID;
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled() && isValidDevice(device)) {
try {
final SynchronousResultReceiver This group call may replace multiple device calls if those are part of the
* valid HAS group. Note that binaural HA devices may or may not support group.
*
* On success, {@link Callback#onPresetSelected(BluetoothDevice, int, int)} will be called
* for each device within the group with reason code
* {@link BluetoothStatusCodes#REASON_LOCAL_APP_REQUEST}
* On failure, {@link Callback#onPresetSelectionForGroupFailed(int, int)} will be
* called for the group.
*
* @param groupId is the device group identifier for which want to set the active preset
* @param presetIndex is an index of one of the available presets
* @hide
*/
@SystemApi
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED
})
public void selectPresetForGroup(int groupId, int presetIndex) {
final IBluetoothHapClient service = getService();
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()) {
try {
service.selectPresetForGroup(groupId, presetIndex, mAttributionSource);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
/**
* Sets the next preset as a currently active preset for a HA device
*
* Note that the meaning of 'next' is HA device implementation specific and
* does not necessarily mean a higher preset index.
*
* @param device is the device for which we want to set the active preset
* @hide
*/
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED
})
public void switchToNextPreset(@NonNull BluetoothDevice device) {
final IBluetoothHapClient service = getService();
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled() && isValidDevice(device)) {
try {
service.switchToNextPreset(device, mAttributionSource);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
/**
* Sets the next preset as a currently active preset for a HA device group
*
* Note that the meaning of 'next' is HA device implementation specific and
* does not necessarily mean a higher preset index.
* This group call may replace multiple device calls if those are part of the
* valid HAS group. Note that binaural HA devices may or may not support group.
*
* @param groupId is the device group identifier for which want to set the active preset
* @hide
*/
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED
})
public void switchToNextPresetForGroup(int groupId) {
final IBluetoothHapClient service = getService();
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()) {
try {
service.switchToNextPresetForGroup(groupId, mAttributionSource);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
/**
* Sets the previous preset as a currently active preset for a HA device.
*
* Note that the meaning of 'previous' is HA device implementation specific and
* does not necessarily mean a lower preset index.
*
* @param device is the device for which we want to set the active preset
* @hide
*/
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED
})
public void switchToPreviousPreset(@NonNull BluetoothDevice device) {
final IBluetoothHapClient service = getService();
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled() && isValidDevice(device)) {
try {
service.switchToPreviousPreset(device, mAttributionSource);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
/**
* Sets the previous preset as a currently active preset for a HA device group
*
* Note the meaning of 'previous' is HA device implementation specific and
* does not necessarily mean a lower preset index.
* This group call may replace multiple device calls if those are part of the
* valid HAS group. Note that binaural HA devices may or may not support group.
*
* @param groupId is the device group identifier for which want to set the active preset
* @hide
*/
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED
})
public void switchToPreviousPresetForGroup(int groupId) {
final IBluetoothHapClient service = getService();
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()) {
try {
service.switchToPreviousPresetForGroup(groupId, mAttributionSource);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
/**
* Requests the preset info
*
* @param device is the device for which we want to get the preset name
* @param presetIndex is an index of one of the available presets
* @return preset info
* @hide
*/
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED
})
public @Nullable BluetoothHapPresetInfo getPresetInfo(@NonNull BluetoothDevice device,
int presetIndex) {
final IBluetoothHapClient service = getService();
final BluetoothHapPresetInfo defaultValue = null;
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled() && isValidDevice(device)) {
try {
final SynchronousResultReceiver Note that the name length is restricted to 40 characters.
*
* On success, {@link Callback#onPresetInfoChanged(BluetoothDevice, List, int)}
* with a new name will be called and reason code
* {@link BluetoothStatusCodes#REASON_LOCAL_APP_REQUEST}
* On failure, {@link Callback#onSetPresetNameFailed(BluetoothDevice, int)} will be called.
*
* @param device is the device for which we want to get the preset name
* @param presetIndex is an index of one of the available presets
* @param name is a new name for a preset, maximum length is 40 characters
* @hide
*/
@SystemApi
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED
})
public void setPresetName(@NonNull BluetoothDevice device, int presetIndex,
@NonNull String name) {
final IBluetoothHapClient service = getService();
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled() && isValidDevice(device)) {
try {
service.setPresetName(device, presetIndex, name, mAttributionSource);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
/**
* Sets the name for a hearing aid preset.
*
* Note that the name length is restricted to 40 characters.
*
* On success, {@link Callback#onPresetInfoChanged(BluetoothDevice, List, int)}
* with a new name will be called for each device within the group with reason code
* {@link BluetoothStatusCodes#REASON_LOCAL_APP_REQUEST}
* On failure, {@link Callback#onSetPresetNameForGroupFailed(int, int)} will be invoked
*
* @param groupId is the device group identifier
* @param presetIndex is an index of one of the available presets
* @param name is a new name for a preset, maximum length is 40 characters
* @hide
*/
@SystemApi
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED
})
public void setPresetNameForGroup(int groupId, int presetIndex, @NonNull String name) {
final IBluetoothHapClient service = getService();
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()) {
try {
service.setPresetNameForGroup(groupId, presetIndex, name, mAttributionSource);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
private boolean isEnabled() {
if (mAdapter.getState() == BluetoothAdapter.STATE_ON) return true;
return false;
}
private boolean isValidDevice(BluetoothDevice device) {
if (device == null) return false;
if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true;
return false;
}
private static void log(String msg) {
Log.d(TAG, msg);
}
}
*
*
*
*
* @hide
*/
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED,
})
@SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_HAP_DEVICE_AVAILABLE =
"android.bluetooth.action.HAP_DEVICE_AVAILABLE";
/**
* Contains a list of all available presets
* @hide
*/
public static final String EXTRA_HAP_FEATURES = "android.bluetooth.extra.HAP_FEATURES";
/**
* Represets an invalid index value. This is usually value returned in a currently
* active preset request for a device which is not connected. This value shouldn't be used
* in the API calls.
* @hide
*/
public static final int PRESET_INDEX_UNAVAILABLE = IBluetoothHapClient.PRESET_INDEX_UNAVAILABLE;
/**
* Feature value.
* @hide
*/
public static final int FEATURE_TYPE_MONAURAL =
1 << IBluetoothHapClient.FEATURE_BIT_NUM_TYPE_MONAURAL;
/**
* Feature value.
* @hide
*/
public static final int FEATURE_TYPE_BANDED =
1 << IBluetoothHapClient.FEATURE_BIT_NUM_TYPE_BANDED;
/**
* Feature value.
* @hide
*/
public static final int FEATURE_SYNCHRONIZATED_PRESETS =
1 << IBluetoothHapClient.FEATURE_BIT_NUM_SYNCHRONIZATED_PRESETS;
/**
* Feature value.
* @hide
*/
public static final int FEATURE_INDEPENDENT_PRESETS =
1 << IBluetoothHapClient.FEATURE_BIT_NUM_INDEPENDENT_PRESETS;
/**
* Feature value.
* @hide
*/
public static final int FEATURE_DYNAMIC_PRESETS =
1 << IBluetoothHapClient.FEATURE_BIT_NUM_DYNAMIC_PRESETS;
/**
* Feature value.
* @hide
*/
public static final int FEATURE_WRITABLE_PRESETS =
1 << IBluetoothHapClient.FEATURE_BIT_NUM_WRITABLE_PRESETS;
/**
* @hide
*/
@Retention(RetentionPolicy.SOURCE)
@IntDef(
flag = true,
value = {
FEATURE_TYPE_MONAURAL,
FEATURE_TYPE_BANDED,
FEATURE_SYNCHRONIZATED_PRESETS,
FEATURE_DYNAMIC_PRESETS,
FEATURE_WRITABLE_PRESETS,
})
@interface Feature {}
private final BluetoothAdapter mAdapter;
private final AttributionSource mAttributionSource;
private final BluetoothProfileConnector recv = SynchronousResultReceiver.get();
service.getConnectedDevices(mAttributionSource, recv);
return Attributable.setAttributionSource(
recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue),
mAttributionSource);
} catch (TimeoutException e) {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
return defaultValue;
}
/**
* {@inheritDoc}
* @hide
*/
@SystemApi
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED,
})
@Override
public @NonNull List
recv = SynchronousResultReceiver.get();
service.getDevicesMatchingConnectionStates(states, mAttributionSource, recv);
return Attributable.setAttributionSource(
recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue),
mAttributionSource);
} catch (TimeoutException e) {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
return defaultValue;
}
/**
* {@inheritDoc}
* @hide
*/
@SystemApi
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED,
})
@Override
public @BluetoothProfile.BtProfileState int getConnectionState(
@NonNull BluetoothDevice device) {
if (VDBG) Log.d(TAG, "getConnectionState(" + device + ")");
final IBluetoothHapClient service = getService();
final int defaultValue = BluetoothProfile.STATE_DISCONNECTED;
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled() && isValidDevice(device)) {
try {
final SynchronousResultReceiver
> recv =
SynchronousResultReceiver.get();
service.getAllPresetInfo(device, mAttributionSource, recv);
return recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue);
} catch (TimeoutException e) {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
return defaultValue;
}
/**
* Requests HAP features
*
* @param device is the device for which we want to get features for
* @return features value with feature bits set
* @hide
*/
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_PRIVILEGED
})
public @Feature int getFeatures(@NonNull BluetoothDevice device) {
final IBluetoothHapClient service = getService();
final int defaultValue = 0x00;
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled() && isValidDevice(device)) {
try {
final SynchronousResultReceiver