/media/java/android/media/AudioManager.java

https://github.com/android/platform_frameworks_base · Java · 7904 lines · 3915 code · 520 blank · 3469 comment · 561 complexity · 822f14c9fa79f458b97cd7bd18a97a9f MD5 · raw file

  1. /*
  2. * Copyright (C) 2007 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package android.media;
  17. import android.annotation.CallbackExecutor;
  18. import android.annotation.IntDef;
  19. import android.annotation.IntRange;
  20. import android.annotation.NonNull;
  21. import android.annotation.Nullable;
  22. import android.annotation.RequiresPermission;
  23. import android.annotation.SdkConstant;
  24. import android.annotation.SdkConstant.SdkConstantType;
  25. import android.annotation.SuppressLint;
  26. import android.annotation.SystemApi;
  27. import android.annotation.SystemService;
  28. import android.annotation.TestApi;
  29. import android.app.NotificationManager;
  30. import android.app.PendingIntent;
  31. import android.bluetooth.BluetoothCodecConfig;
  32. import android.bluetooth.BluetoothDevice;
  33. import android.bluetooth.BluetoothProfile;
  34. import android.compat.annotation.UnsupportedAppUsage;
  35. import android.content.ComponentName;
  36. import android.content.Context;
  37. import android.content.Intent;
  38. import android.media.AudioAttributes.AttributeSystemUsage;
  39. import android.media.audiopolicy.AudioPolicy;
  40. import android.media.audiopolicy.AudioPolicy.AudioPolicyFocusListener;
  41. import android.media.audiopolicy.AudioProductStrategy;
  42. import android.media.audiopolicy.AudioVolumeGroup;
  43. import android.media.audiopolicy.AudioVolumeGroupChangeHandler;
  44. import android.media.projection.MediaProjection;
  45. import android.media.session.MediaController;
  46. import android.media.session.MediaSession;
  47. import android.media.session.MediaSessionLegacyHelper;
  48. import android.media.session.MediaSessionManager;
  49. import android.net.Uri;
  50. import android.os.Binder;
  51. import android.os.Build;
  52. import android.os.Handler;
  53. import android.os.IBinder;
  54. import android.os.Looper;
  55. import android.os.Message;
  56. import android.os.Process;
  57. import android.os.RemoteException;
  58. import android.os.ServiceManager;
  59. import android.os.SystemClock;
  60. import android.os.UserHandle;
  61. import android.provider.Settings;
  62. import android.text.TextUtils;
  63. import android.util.ArrayMap;
  64. import android.util.Log;
  65. import android.util.Pair;
  66. import android.view.KeyEvent;
  67. import com.android.internal.annotations.GuardedBy;
  68. import com.android.internal.util.Preconditions;
  69. import java.io.IOException;
  70. import java.lang.annotation.Retention;
  71. import java.lang.annotation.RetentionPolicy;
  72. import java.lang.ref.WeakReference;
  73. import java.util.ArrayList;
  74. import java.util.Arrays;
  75. import java.util.HashMap;
  76. import java.util.HashSet;
  77. import java.util.Iterator;
  78. import java.util.List;
  79. import java.util.Map;
  80. import java.util.Objects;
  81. import java.util.TreeMap;
  82. import java.util.concurrent.ConcurrentHashMap;
  83. import java.util.concurrent.Executor;
  84. /**
  85. * AudioManager provides access to volume and ringer mode control.
  86. */
  87. @SystemService(Context.AUDIO_SERVICE)
  88. public class AudioManager {
  89. private Context mOriginalContext;
  90. private Context mApplicationContext;
  91. private long mVolumeKeyUpTime;
  92. private boolean mUseFixedVolumeInitialized;
  93. private boolean mUseFixedVolume;
  94. private static final String TAG = "AudioManager";
  95. private static final boolean DEBUG = false;
  96. private static final AudioPortEventHandler sAudioPortEventHandler = new AudioPortEventHandler();
  97. private static final AudioVolumeGroupChangeHandler sAudioAudioVolumeGroupChangedHandler =
  98. new AudioVolumeGroupChangeHandler();
  99. private static WeakReference<Context> sContext;
  100. /**
  101. * Broadcast intent, a hint for applications that audio is about to become
  102. * 'noisy' due to a change in audio outputs. For example, this intent may
  103. * be sent when a wired headset is unplugged, or when an A2DP audio
  104. * sink is disconnected, and the audio system is about to automatically
  105. * switch audio route to the speaker. Applications that are controlling
  106. * audio streams may consider pausing, reducing volume or some other action
  107. * on receipt of this intent so as not to surprise the user with audio
  108. * from the speaker.
  109. */
  110. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  111. public static final String ACTION_AUDIO_BECOMING_NOISY = "android.media.AUDIO_BECOMING_NOISY";
  112. /**
  113. * Sticky broadcast intent action indicating that the ringer mode has
  114. * changed. Includes the new ringer mode.
  115. *
  116. * @see #EXTRA_RINGER_MODE
  117. */
  118. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  119. public static final String RINGER_MODE_CHANGED_ACTION = "android.media.RINGER_MODE_CHANGED";
  120. /**
  121. * @hide
  122. * Sticky broadcast intent action indicating that the internal ringer mode has
  123. * changed. Includes the new ringer mode.
  124. *
  125. * @see #EXTRA_RINGER_MODE
  126. */
  127. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  128. public static final String INTERNAL_RINGER_MODE_CHANGED_ACTION =
  129. "android.media.INTERNAL_RINGER_MODE_CHANGED_ACTION";
  130. /**
  131. * The new ringer mode.
  132. *
  133. * @see #RINGER_MODE_CHANGED_ACTION
  134. * @see #RINGER_MODE_NORMAL
  135. * @see #RINGER_MODE_SILENT
  136. * @see #RINGER_MODE_VIBRATE
  137. */
  138. public static final String EXTRA_RINGER_MODE = "android.media.EXTRA_RINGER_MODE";
  139. /**
  140. * Broadcast intent action indicating that the vibrate setting has
  141. * changed. Includes the vibrate type and its new setting.
  142. *
  143. * @see #EXTRA_VIBRATE_TYPE
  144. * @see #EXTRA_VIBRATE_SETTING
  145. * @deprecated Applications should maintain their own vibrate policy based on
  146. * current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
  147. */
  148. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  149. public static final String VIBRATE_SETTING_CHANGED_ACTION =
  150. "android.media.VIBRATE_SETTING_CHANGED";
  151. /**
  152. * @hide Broadcast intent when the volume for a particular stream type changes.
  153. * Includes the stream, the new volume and previous volumes.
  154. * Notes:
  155. * - for internal platform use only, do not make public,
  156. * - never used for "remote" volume changes
  157. *
  158. * @see #EXTRA_VOLUME_STREAM_TYPE
  159. * @see #EXTRA_VOLUME_STREAM_VALUE
  160. * @see #EXTRA_PREV_VOLUME_STREAM_VALUE
  161. */
  162. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  163. @UnsupportedAppUsage
  164. public static final String VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION";
  165. /**
  166. * @hide Broadcast intent when the devices for a particular stream type changes.
  167. * Includes the stream, the new devices and previous devices.
  168. * Notes:
  169. * - for internal platform use only, do not make public,
  170. * - never used for "remote" volume changes
  171. *
  172. * @see #EXTRA_VOLUME_STREAM_TYPE
  173. * @see #EXTRA_VOLUME_STREAM_DEVICES
  174. * @see #EXTRA_PREV_VOLUME_STREAM_DEVICES
  175. * @see #getDevicesForStream
  176. */
  177. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  178. public static final String STREAM_DEVICES_CHANGED_ACTION =
  179. "android.media.STREAM_DEVICES_CHANGED_ACTION";
  180. /**
  181. * @hide Broadcast intent when a stream mute state changes.
  182. * Includes the stream that changed and the new mute state
  183. *
  184. * @see #EXTRA_VOLUME_STREAM_TYPE
  185. * @see #EXTRA_STREAM_VOLUME_MUTED
  186. */
  187. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  188. public static final String STREAM_MUTE_CHANGED_ACTION =
  189. "android.media.STREAM_MUTE_CHANGED_ACTION";
  190. /**
  191. * @hide Broadcast intent when the master mute state changes.
  192. * Includes the the new volume
  193. *
  194. * @see #EXTRA_MASTER_VOLUME_MUTED
  195. */
  196. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  197. public static final String MASTER_MUTE_CHANGED_ACTION =
  198. "android.media.MASTER_MUTE_CHANGED_ACTION";
  199. /**
  200. * The new vibrate setting for a particular type.
  201. *
  202. * @see #VIBRATE_SETTING_CHANGED_ACTION
  203. * @see #EXTRA_VIBRATE_TYPE
  204. * @see #VIBRATE_SETTING_ON
  205. * @see #VIBRATE_SETTING_OFF
  206. * @see #VIBRATE_SETTING_ONLY_SILENT
  207. * @deprecated Applications should maintain their own vibrate policy based on
  208. * current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
  209. */
  210. public static final String EXTRA_VIBRATE_SETTING = "android.media.EXTRA_VIBRATE_SETTING";
  211. /**
  212. * The vibrate type whose setting has changed.
  213. *
  214. * @see #VIBRATE_SETTING_CHANGED_ACTION
  215. * @see #VIBRATE_TYPE_NOTIFICATION
  216. * @see #VIBRATE_TYPE_RINGER
  217. * @deprecated Applications should maintain their own vibrate policy based on
  218. * current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
  219. */
  220. public static final String EXTRA_VIBRATE_TYPE = "android.media.EXTRA_VIBRATE_TYPE";
  221. /**
  222. * @hide The stream type for the volume changed intent.
  223. */
  224. @UnsupportedAppUsage
  225. public static final String EXTRA_VOLUME_STREAM_TYPE = "android.media.EXTRA_VOLUME_STREAM_TYPE";
  226. /**
  227. * @hide
  228. * The stream type alias for the volume changed intent.
  229. * For instance the intent may indicate a change of the {@link #STREAM_NOTIFICATION} stream
  230. * type (as indicated by the {@link #EXTRA_VOLUME_STREAM_TYPE} extra), but this is also
  231. * reflected by a change of the volume of its alias, {@link #STREAM_RING} on some devices,
  232. * {@link #STREAM_MUSIC} on others (e.g. a television).
  233. */
  234. public static final String EXTRA_VOLUME_STREAM_TYPE_ALIAS =
  235. "android.media.EXTRA_VOLUME_STREAM_TYPE_ALIAS";
  236. /**
  237. * @hide The volume associated with the stream for the volume changed intent.
  238. */
  239. @UnsupportedAppUsage
  240. public static final String EXTRA_VOLUME_STREAM_VALUE =
  241. "android.media.EXTRA_VOLUME_STREAM_VALUE";
  242. /**
  243. * @hide The previous volume associated with the stream for the volume changed intent.
  244. */
  245. public static final String EXTRA_PREV_VOLUME_STREAM_VALUE =
  246. "android.media.EXTRA_PREV_VOLUME_STREAM_VALUE";
  247. /**
  248. * @hide The devices associated with the stream for the stream devices changed intent.
  249. */
  250. public static final String EXTRA_VOLUME_STREAM_DEVICES =
  251. "android.media.EXTRA_VOLUME_STREAM_DEVICES";
  252. /**
  253. * @hide The previous devices associated with the stream for the stream devices changed intent.
  254. */
  255. public static final String EXTRA_PREV_VOLUME_STREAM_DEVICES =
  256. "android.media.EXTRA_PREV_VOLUME_STREAM_DEVICES";
  257. /**
  258. * @hide The new master volume mute state for the master mute changed intent.
  259. * Value is boolean
  260. */
  261. public static final String EXTRA_MASTER_VOLUME_MUTED =
  262. "android.media.EXTRA_MASTER_VOLUME_MUTED";
  263. /**
  264. * @hide The new stream volume mute state for the stream mute changed intent.
  265. * Value is boolean
  266. */
  267. public static final String EXTRA_STREAM_VOLUME_MUTED =
  268. "android.media.EXTRA_STREAM_VOLUME_MUTED";
  269. /**
  270. * Broadcast Action: Wired Headset plugged in or unplugged.
  271. *
  272. * You <em>cannot</em> receive this through components declared
  273. * in manifests, only by explicitly registering for it with
  274. * {@link Context#registerReceiver(BroadcastReceiver, IntentFilter)
  275. * Context.registerReceiver()}.
  276. *
  277. * <p>The intent will have the following extra values:
  278. * <ul>
  279. * <li><em>state</em> - 0 for unplugged, 1 for plugged. </li>
  280. * <li><em>name</em> - Headset type, human readable string </li>
  281. * <li><em>microphone</em> - 1 if headset has a microphone, 0 otherwise </li>
  282. * </ul>
  283. * </ul>
  284. */
  285. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  286. public static final String ACTION_HEADSET_PLUG =
  287. "android.intent.action.HEADSET_PLUG";
  288. /**
  289. * Broadcast Action: A sticky broadcast indicating an HDMI cable was plugged or unplugged.
  290. *
  291. * The intent will have the following extra values: {@link #EXTRA_AUDIO_PLUG_STATE},
  292. * {@link #EXTRA_MAX_CHANNEL_COUNT}, {@link #EXTRA_ENCODINGS}.
  293. * <p>It can only be received by explicitly registering for it with
  294. * {@link Context#registerReceiver(BroadcastReceiver, IntentFilter)}.
  295. */
  296. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  297. public static final String ACTION_HDMI_AUDIO_PLUG =
  298. "android.media.action.HDMI_AUDIO_PLUG";
  299. /**
  300. * Extra used in {@link #ACTION_HDMI_AUDIO_PLUG} to communicate whether HDMI is plugged in
  301. * or unplugged.
  302. * An integer value of 1 indicates a plugged-in state, 0 is unplugged.
  303. */
  304. public static final String EXTRA_AUDIO_PLUG_STATE = "android.media.extra.AUDIO_PLUG_STATE";
  305. /**
  306. * Extra used in {@link #ACTION_HDMI_AUDIO_PLUG} to define the maximum number of channels
  307. * supported by the HDMI device.
  308. * The corresponding integer value is only available when the device is plugged in (as expressed
  309. * by {@link #EXTRA_AUDIO_PLUG_STATE}).
  310. */
  311. public static final String EXTRA_MAX_CHANNEL_COUNT = "android.media.extra.MAX_CHANNEL_COUNT";
  312. /**
  313. * Extra used in {@link #ACTION_HDMI_AUDIO_PLUG} to define the audio encodings supported by
  314. * the connected HDMI device.
  315. * The corresponding array of encoding values is only available when the device is plugged in
  316. * (as expressed by {@link #EXTRA_AUDIO_PLUG_STATE}). Encoding values are defined in
  317. * {@link AudioFormat} (for instance see {@link AudioFormat#ENCODING_PCM_16BIT}). Use
  318. * {@link android.content.Intent#getIntArrayExtra(String)} to retrieve the encoding values.
  319. */
  320. public static final String EXTRA_ENCODINGS = "android.media.extra.ENCODINGS";
  321. /** Used to identify the volume of audio streams for phone calls */
  322. public static final int STREAM_VOICE_CALL = AudioSystem.STREAM_VOICE_CALL;
  323. /** Used to identify the volume of audio streams for system sounds */
  324. public static final int STREAM_SYSTEM = AudioSystem.STREAM_SYSTEM;
  325. /** Used to identify the volume of audio streams for the phone ring */
  326. public static final int STREAM_RING = AudioSystem.STREAM_RING;
  327. /** Used to identify the volume of audio streams for music playback */
  328. public static final int STREAM_MUSIC = AudioSystem.STREAM_MUSIC;
  329. /** Used to identify the volume of audio streams for alarms */
  330. public static final int STREAM_ALARM = AudioSystem.STREAM_ALARM;
  331. /** Used to identify the volume of audio streams for notifications */
  332. public static final int STREAM_NOTIFICATION = AudioSystem.STREAM_NOTIFICATION;
  333. /** @hide Used to identify the volume of audio streams for phone calls when connected
  334. * to bluetooth */
  335. @UnsupportedAppUsage
  336. public static final int STREAM_BLUETOOTH_SCO = AudioSystem.STREAM_BLUETOOTH_SCO;
  337. /** @hide Used to identify the volume of audio streams for enforced system sounds
  338. * in certain countries (e.g camera in Japan) */
  339. @UnsupportedAppUsage
  340. public static final int STREAM_SYSTEM_ENFORCED = AudioSystem.STREAM_SYSTEM_ENFORCED;
  341. /** Used to identify the volume of audio streams for DTMF Tones */
  342. public static final int STREAM_DTMF = AudioSystem.STREAM_DTMF;
  343. /** @hide Used to identify the volume of audio streams exclusively transmitted through the
  344. * speaker (TTS) of the device */
  345. @UnsupportedAppUsage
  346. public static final int STREAM_TTS = AudioSystem.STREAM_TTS;
  347. /** Used to identify the volume of audio streams for accessibility prompts */
  348. public static final int STREAM_ACCESSIBILITY = AudioSystem.STREAM_ACCESSIBILITY;
  349. /** @hide Used to identify the volume of audio streams for virtual assistant */
  350. @SystemApi
  351. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  352. public static final int STREAM_ASSISTANT = AudioSystem.STREAM_ASSISTANT;
  353. /** Number of audio streams */
  354. /**
  355. * @deprecated Do not iterate on volume stream type values.
  356. */
  357. @Deprecated public static final int NUM_STREAMS = AudioSystem.NUM_STREAMS;
  358. /**
  359. * Increase the ringer volume.
  360. *
  361. * @see #adjustVolume(int, int)
  362. * @see #adjustStreamVolume(int, int, int)
  363. */
  364. public static final int ADJUST_RAISE = 1;
  365. /**
  366. * Decrease the ringer volume.
  367. *
  368. * @see #adjustVolume(int, int)
  369. * @see #adjustStreamVolume(int, int, int)
  370. */
  371. public static final int ADJUST_LOWER = -1;
  372. /**
  373. * Maintain the previous ringer volume. This may be useful when needing to
  374. * show the volume toast without actually modifying the volume.
  375. *
  376. * @see #adjustVolume(int, int)
  377. * @see #adjustStreamVolume(int, int, int)
  378. */
  379. public static final int ADJUST_SAME = 0;
  380. /**
  381. * Mute the volume. Has no effect if the stream is already muted.
  382. *
  383. * @see #adjustVolume(int, int)
  384. * @see #adjustStreamVolume(int, int, int)
  385. */
  386. public static final int ADJUST_MUTE = -100;
  387. /**
  388. * Unmute the volume. Has no effect if the stream is not muted.
  389. *
  390. * @see #adjustVolume(int, int)
  391. * @see #adjustStreamVolume(int, int, int)
  392. */
  393. public static final int ADJUST_UNMUTE = 100;
  394. /**
  395. * Toggle the mute state. If muted the stream will be unmuted. If not muted
  396. * the stream will be muted.
  397. *
  398. * @see #adjustVolume(int, int)
  399. * @see #adjustStreamVolume(int, int, int)
  400. */
  401. public static final int ADJUST_TOGGLE_MUTE = 101;
  402. /** @hide */
  403. @IntDef(flag = false, prefix = "ADJUST", value = {
  404. ADJUST_RAISE,
  405. ADJUST_LOWER,
  406. ADJUST_SAME,
  407. ADJUST_MUTE,
  408. ADJUST_UNMUTE,
  409. ADJUST_TOGGLE_MUTE }
  410. )
  411. @Retention(RetentionPolicy.SOURCE)
  412. public @interface VolumeAdjustment {}
  413. /** @hide */
  414. public static final String adjustToString(int adj) {
  415. switch (adj) {
  416. case ADJUST_RAISE: return "ADJUST_RAISE";
  417. case ADJUST_LOWER: return "ADJUST_LOWER";
  418. case ADJUST_SAME: return "ADJUST_SAME";
  419. case ADJUST_MUTE: return "ADJUST_MUTE";
  420. case ADJUST_UNMUTE: return "ADJUST_UNMUTE";
  421. case ADJUST_TOGGLE_MUTE: return "ADJUST_TOGGLE_MUTE";
  422. default: return new StringBuilder("unknown adjust mode ").append(adj).toString();
  423. }
  424. }
  425. // Flags should be powers of 2!
  426. /**
  427. * Show a toast containing the current volume.
  428. *
  429. * @see #adjustStreamVolume(int, int, int)
  430. * @see #adjustVolume(int, int)
  431. * @see #setStreamVolume(int, int, int)
  432. * @see #setRingerMode(int)
  433. */
  434. public static final int FLAG_SHOW_UI = 1 << 0;
  435. /**
  436. * Whether to include ringer modes as possible options when changing volume.
  437. * For example, if true and volume level is 0 and the volume is adjusted
  438. * with {@link #ADJUST_LOWER}, then the ringer mode may switch the silent or
  439. * vibrate mode.
  440. * <p>
  441. * By default this is on for the ring stream. If this flag is included,
  442. * this behavior will be present regardless of the stream type being
  443. * affected by the ringer mode.
  444. *
  445. * @see #adjustVolume(int, int)
  446. * @see #adjustStreamVolume(int, int, int)
  447. */
  448. public static final int FLAG_ALLOW_RINGER_MODES = 1 << 1;
  449. /**
  450. * Whether to play a sound when changing the volume.
  451. * <p>
  452. * If this is given to {@link #adjustVolume(int, int)} or
  453. * {@link #adjustSuggestedStreamVolume(int, int, int)}, it may be ignored
  454. * in some cases (for example, the decided stream type is not
  455. * {@link AudioManager#STREAM_RING}, or the volume is being adjusted
  456. * downward).
  457. *
  458. * @see #adjustStreamVolume(int, int, int)
  459. * @see #adjustVolume(int, int)
  460. * @see #setStreamVolume(int, int, int)
  461. */
  462. public static final int FLAG_PLAY_SOUND = 1 << 2;
  463. /**
  464. * Removes any sounds/vibrate that may be in the queue, or are playing (related to
  465. * changing volume).
  466. */
  467. public static final int FLAG_REMOVE_SOUND_AND_VIBRATE = 1 << 3;
  468. /**
  469. * Whether to vibrate if going into the vibrate ringer mode.
  470. */
  471. public static final int FLAG_VIBRATE = 1 << 4;
  472. /**
  473. * Indicates to VolumePanel that the volume slider should be disabled as user
  474. * cannot change the stream volume
  475. * @hide
  476. */
  477. public static final int FLAG_FIXED_VOLUME = 1 << 5;
  478. /**
  479. * Indicates the volume set/adjust call is for Bluetooth absolute volume
  480. * @hide
  481. */
  482. public static final int FLAG_BLUETOOTH_ABS_VOLUME = 1 << 6;
  483. /**
  484. * Adjusting the volume was prevented due to silent mode, display a hint in the UI.
  485. * @hide
  486. */
  487. public static final int FLAG_SHOW_SILENT_HINT = 1 << 7;
  488. /**
  489. * Indicates the volume call is for Hdmi Cec system audio volume
  490. * @hide
  491. */
  492. public static final int FLAG_HDMI_SYSTEM_AUDIO_VOLUME = 1 << 8;
  493. /**
  494. * Indicates that this should only be handled if media is actively playing.
  495. * @hide
  496. */
  497. public static final int FLAG_ACTIVE_MEDIA_ONLY = 1 << 9;
  498. /**
  499. * Like FLAG_SHOW_UI, but only dialog warnings and confirmations, no sliders.
  500. * @hide
  501. */
  502. public static final int FLAG_SHOW_UI_WARNINGS = 1 << 10;
  503. /**
  504. * Adjusting the volume down from vibrated was prevented, display a hint in the UI.
  505. * @hide
  506. */
  507. public static final int FLAG_SHOW_VIBRATE_HINT = 1 << 11;
  508. /**
  509. * Adjusting the volume due to a hardware key press.
  510. * This flag can be used in the places in order to denote (or check) that a volume adjustment
  511. * request is from a hardware key press. (e.g. {@link MediaController}).
  512. * @hide
  513. */
  514. @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
  515. public static final int FLAG_FROM_KEY = 1 << 12;
  516. /** @hide */
  517. @IntDef(prefix = {"ENCODED_SURROUND_OUTPUT_"}, value = {
  518. ENCODED_SURROUND_OUTPUT_UNKNOWN,
  519. ENCODED_SURROUND_OUTPUT_AUTO,
  520. ENCODED_SURROUND_OUTPUT_NEVER,
  521. ENCODED_SURROUND_OUTPUT_ALWAYS,
  522. ENCODED_SURROUND_OUTPUT_MANUAL
  523. })
  524. @Retention(RetentionPolicy.SOURCE)
  525. public @interface EncodedSurroundOutputMode {}
  526. /**
  527. * The mode for surround sound formats is unknown.
  528. */
  529. public static final int ENCODED_SURROUND_OUTPUT_UNKNOWN = -1;
  530. /**
  531. * The surround sound formats are available for use if they are detected. This is the default
  532. * mode.
  533. */
  534. public static final int ENCODED_SURROUND_OUTPUT_AUTO = 0;
  535. /**
  536. * The surround sound formats are NEVER available, even if they are detected by the hardware.
  537. * Those formats will not be reported.
  538. */
  539. public static final int ENCODED_SURROUND_OUTPUT_NEVER = 1;
  540. /**
  541. * The surround sound formats are ALWAYS available, even if they are not detected by the
  542. * hardware. Those formats will be reported as part of the HDMI output capability.
  543. * Applications are then free to use either PCM or encoded output.
  544. */
  545. public static final int ENCODED_SURROUND_OUTPUT_ALWAYS = 2;
  546. /**
  547. * Surround sound formats are available according to the choice of user, even if they are not
  548. * detected by the hardware. Those formats will be reported as part of the HDMI output
  549. * capability. Applications are then free to use either PCM or encoded output.
  550. */
  551. public static final int ENCODED_SURROUND_OUTPUT_MANUAL = 3;
  552. /** @hide */
  553. @IntDef(flag = true, prefix = "FLAG", value = {
  554. FLAG_SHOW_UI,
  555. FLAG_ALLOW_RINGER_MODES,
  556. FLAG_PLAY_SOUND,
  557. FLAG_REMOVE_SOUND_AND_VIBRATE,
  558. FLAG_VIBRATE,
  559. FLAG_FIXED_VOLUME,
  560. FLAG_BLUETOOTH_ABS_VOLUME,
  561. FLAG_SHOW_SILENT_HINT,
  562. FLAG_HDMI_SYSTEM_AUDIO_VOLUME,
  563. FLAG_ACTIVE_MEDIA_ONLY,
  564. FLAG_SHOW_UI_WARNINGS,
  565. FLAG_SHOW_VIBRATE_HINT,
  566. FLAG_FROM_KEY,
  567. })
  568. @Retention(RetentionPolicy.SOURCE)
  569. public @interface Flags {}
  570. // The iterator of TreeMap#entrySet() returns the entries in ascending key order.
  571. private static final TreeMap<Integer, String> FLAG_NAMES = new TreeMap<>();
  572. static {
  573. FLAG_NAMES.put(FLAG_SHOW_UI, "FLAG_SHOW_UI");
  574. FLAG_NAMES.put(FLAG_ALLOW_RINGER_MODES, "FLAG_ALLOW_RINGER_MODES");
  575. FLAG_NAMES.put(FLAG_PLAY_SOUND, "FLAG_PLAY_SOUND");
  576. FLAG_NAMES.put(FLAG_REMOVE_SOUND_AND_VIBRATE, "FLAG_REMOVE_SOUND_AND_VIBRATE");
  577. FLAG_NAMES.put(FLAG_VIBRATE, "FLAG_VIBRATE");
  578. FLAG_NAMES.put(FLAG_FIXED_VOLUME, "FLAG_FIXED_VOLUME");
  579. FLAG_NAMES.put(FLAG_BLUETOOTH_ABS_VOLUME, "FLAG_BLUETOOTH_ABS_VOLUME");
  580. FLAG_NAMES.put(FLAG_SHOW_SILENT_HINT, "FLAG_SHOW_SILENT_HINT");
  581. FLAG_NAMES.put(FLAG_HDMI_SYSTEM_AUDIO_VOLUME, "FLAG_HDMI_SYSTEM_AUDIO_VOLUME");
  582. FLAG_NAMES.put(FLAG_ACTIVE_MEDIA_ONLY, "FLAG_ACTIVE_MEDIA_ONLY");
  583. FLAG_NAMES.put(FLAG_SHOW_UI_WARNINGS, "FLAG_SHOW_UI_WARNINGS");
  584. FLAG_NAMES.put(FLAG_SHOW_VIBRATE_HINT, "FLAG_SHOW_VIBRATE_HINT");
  585. FLAG_NAMES.put(FLAG_FROM_KEY, "FLAG_FROM_KEY");
  586. }
  587. /** @hide */
  588. public static String flagsToString(int flags) {
  589. final StringBuilder sb = new StringBuilder();
  590. for (Map.Entry<Integer, String> entry : FLAG_NAMES.entrySet()) {
  591. final int flag = entry.getKey();
  592. if ((flags & flag) != 0) {
  593. if (sb.length() > 0) {
  594. sb.append(',');
  595. }
  596. sb.append(entry.getValue());
  597. flags &= ~flag;
  598. }
  599. }
  600. if (flags != 0) {
  601. if (sb.length() > 0) {
  602. sb.append(',');
  603. }
  604. sb.append(flags);
  605. }
  606. return sb.toString();
  607. }
  608. /**
  609. * Ringer mode that will be silent and will not vibrate. (This overrides the
  610. * vibrate setting.)
  611. *
  612. * @see #setRingerMode(int)
  613. * @see #getRingerMode()
  614. */
  615. public static final int RINGER_MODE_SILENT = 0;
  616. /**
  617. * Ringer mode that will be silent and will vibrate. (This will cause the
  618. * phone ringer to always vibrate, but the notification vibrate to only
  619. * vibrate if set.)
  620. *
  621. * @see #setRingerMode(int)
  622. * @see #getRingerMode()
  623. */
  624. public static final int RINGER_MODE_VIBRATE = 1;
  625. /**
  626. * Ringer mode that may be audible and may vibrate. It will be audible if
  627. * the volume before changing out of this mode was audible. It will vibrate
  628. * if the vibrate setting is on.
  629. *
  630. * @see #setRingerMode(int)
  631. * @see #getRingerMode()
  632. */
  633. public static final int RINGER_MODE_NORMAL = 2;
  634. /**
  635. * Maximum valid ringer mode value. Values must start from 0 and be contiguous.
  636. * @hide
  637. */
  638. public static final int RINGER_MODE_MAX = RINGER_MODE_NORMAL;
  639. /**
  640. * Vibrate type that corresponds to the ringer.
  641. *
  642. * @see #setVibrateSetting(int, int)
  643. * @see #getVibrateSetting(int)
  644. * @see #shouldVibrate(int)
  645. * @deprecated Applications should maintain their own vibrate policy based on
  646. * current ringer mode that can be queried via {@link #getRingerMode()}.
  647. */
  648. public static final int VIBRATE_TYPE_RINGER = 0;
  649. /**
  650. * Vibrate type that corresponds to notifications.
  651. *
  652. * @see #setVibrateSetting(int, int)
  653. * @see #getVibrateSetting(int)
  654. * @see #shouldVibrate(int)
  655. * @deprecated Applications should maintain their own vibrate policy based on
  656. * current ringer mode that can be queried via {@link #getRingerMode()}.
  657. */
  658. public static final int VIBRATE_TYPE_NOTIFICATION = 1;
  659. /**
  660. * Vibrate setting that suggests to never vibrate.
  661. *
  662. * @see #setVibrateSetting(int, int)
  663. * @see #getVibrateSetting(int)
  664. * @deprecated Applications should maintain their own vibrate policy based on
  665. * current ringer mode that can be queried via {@link #getRingerMode()}.
  666. */
  667. public static final int VIBRATE_SETTING_OFF = 0;
  668. /**
  669. * Vibrate setting that suggests to vibrate when possible.
  670. *
  671. * @see #setVibrateSetting(int, int)
  672. * @see #getVibrateSetting(int)
  673. * @deprecated Applications should maintain their own vibrate policy based on
  674. * current ringer mode that can be queried via {@link #getRingerMode()}.
  675. */
  676. public static final int VIBRATE_SETTING_ON = 1;
  677. /**
  678. * Vibrate setting that suggests to only vibrate when in the vibrate ringer
  679. * mode.
  680. *
  681. * @see #setVibrateSetting(int, int)
  682. * @see #getVibrateSetting(int)
  683. * @deprecated Applications should maintain their own vibrate policy based on
  684. * current ringer mode that can be queried via {@link #getRingerMode()}.
  685. */
  686. public static final int VIBRATE_SETTING_ONLY_SILENT = 2;
  687. /**
  688. * Suggests using the default stream type. This may not be used in all
  689. * places a stream type is needed.
  690. */
  691. public static final int USE_DEFAULT_STREAM_TYPE = Integer.MIN_VALUE;
  692. private static IAudioService sService;
  693. /**
  694. * @hide
  695. * For test purposes only, will throw NPE with some methods that require a Context.
  696. */
  697. @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  698. public AudioManager() {
  699. }
  700. /**
  701. * @hide
  702. */
  703. @UnsupportedAppUsage
  704. public AudioManager(Context context) {
  705. setContext(context);
  706. }
  707. private Context getContext() {
  708. if (mApplicationContext == null) {
  709. setContext(mOriginalContext);
  710. }
  711. if (mApplicationContext != null) {
  712. return mApplicationContext;
  713. }
  714. return mOriginalContext;
  715. }
  716. private void setContext(Context context) {
  717. mApplicationContext = context.getApplicationContext();
  718. if (mApplicationContext != null) {
  719. mOriginalContext = null;
  720. } else {
  721. mOriginalContext = context;
  722. }
  723. sContext = new WeakReference<>(context);
  724. }
  725. @UnsupportedAppUsage
  726. private static IAudioService getService()
  727. {
  728. if (sService != null) {
  729. return sService;
  730. }
  731. IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
  732. sService = IAudioService.Stub.asInterface(b);
  733. return sService;
  734. }
  735. /**
  736. * Sends a simulated key event for a media button.
  737. * To simulate a key press, you must first send a KeyEvent built with a
  738. * {@link KeyEvent#ACTION_DOWN} action, then another event with the {@link KeyEvent#ACTION_UP}
  739. * action.
  740. * <p>The key event will be sent to the current media key event consumer which registered with
  741. * {@link AudioManager#registerMediaButtonEventReceiver(PendingIntent)}.
  742. * @param keyEvent a {@link KeyEvent} instance whose key code is one of
  743. * {@link KeyEvent#KEYCODE_MUTE},
  744. * {@link KeyEvent#KEYCODE_HEADSETHOOK},
  745. * {@link KeyEvent#KEYCODE_MEDIA_PLAY},
  746. * {@link KeyEvent#KEYCODE_MEDIA_PAUSE},
  747. * {@link KeyEvent#KEYCODE_MEDIA_PLAY_PAUSE},
  748. * {@link KeyEvent#KEYCODE_MEDIA_STOP},
  749. * {@link KeyEvent#KEYCODE_MEDIA_NEXT},
  750. * {@link KeyEvent#KEYCODE_MEDIA_PREVIOUS},
  751. * {@link KeyEvent#KEYCODE_MEDIA_REWIND},
  752. * {@link KeyEvent#KEYCODE_MEDIA_RECORD},
  753. * {@link KeyEvent#KEYCODE_MEDIA_FAST_FORWARD},
  754. * {@link KeyEvent#KEYCODE_MEDIA_CLOSE},
  755. * {@link KeyEvent#KEYCODE_MEDIA_EJECT},
  756. * or {@link KeyEvent#KEYCODE_MEDIA_AUDIO_TRACK}.
  757. */
  758. public void dispatchMediaKeyEvent(KeyEvent keyEvent) {
  759. MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(getContext());
  760. helper.sendMediaButtonEvent(keyEvent, false);
  761. }
  762. /**
  763. * @hide
  764. */
  765. public void preDispatchKeyEvent(KeyEvent event, int stream) {
  766. /*
  767. * If the user hits another key within the play sound delay, then
  768. * cancel the sound
  769. */
  770. int keyCode = event.getKeyCode();
  771. if (keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_VOLUME_UP
  772. && keyCode != KeyEvent.KEYCODE_VOLUME_MUTE
  773. && mVolumeKeyUpTime + AudioSystem.PLAY_SOUND_DELAY > SystemClock.uptimeMillis()) {
  774. /*
  775. * The user has hit another key during the delay (e.g., 300ms)
  776. * since the last volume key up, so cancel any sounds.
  777. */
  778. adjustSuggestedStreamVolume(ADJUST_SAME,
  779. stream, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
  780. }
  781. }
  782. /**
  783. * Indicates if the device implements a fixed volume policy.
  784. * <p>Some devices may not have volume control and may operate at a fixed volume,
  785. * and may not enable muting or changing the volume of audio streams.
  786. * This method will return true on such devices.
  787. * <p>The following APIs have no effect when volume is fixed:
  788. * <ul>
  789. * <li> {@link #adjustVolume(int, int)}
  790. * <li> {@link #adjustSuggestedStreamVolume(int, int, int)}
  791. * <li> {@link #adjustStreamVolume(int, int, int)}
  792. * <li> {@link #setStreamVolume(int, int, int)}
  793. * <li> {@link #setRingerMode(int)}
  794. * <li> {@link #setStreamSolo(int, boolean)}
  795. * <li> {@link #setStreamMute(int, boolean)}
  796. * </ul>
  797. */
  798. public boolean isVolumeFixed() {
  799. synchronized (this) {
  800. try {
  801. if (!mUseFixedVolumeInitialized) {
  802. mUseFixedVolume = getContext().getResources().getBoolean(
  803. com.android.internal.R.bool.config_useFixedVolume);
  804. }
  805. } catch (Exception e) {
  806. } finally {
  807. // only ever try once, so always consider initialized even if query failed
  808. mUseFixedVolumeInitialized = true;
  809. }
  810. }
  811. return mUseFixedVolume;
  812. }
  813. /**
  814. * Adjusts the volume of a particular stream by one step in a direction.
  815. * <p>
  816. * This method should only be used by applications that replace the platform-wide
  817. * management of audio settings or the main telephony application.
  818. * <p>This method has no effect if the device implements a fixed volume policy
  819. * as indicated by {@link #isVolumeFixed()}.
  820. * <p>From N onward, ringer mode adjustments that would toggle Do Not Disturb are not allowed
  821. * unless the app has been granted Do Not Disturb Access.
  822. * See {@link NotificationManager#isNotificationPolicyAccessGranted()}.
  823. *
  824. * @param streamType The stream type to adjust. One of {@link #STREAM_VOICE_CALL},
  825. * {@link #STREAM_SYSTEM}, {@link #STREAM_RING}, {@link #STREAM_MUSIC},
  826. * {@link #STREAM_ALARM} or {@link #STREAM_ACCESSIBILITY}.
  827. * @param direction The direction to adjust the volume. One of
  828. * {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
  829. * {@link #ADJUST_SAME}.
  830. * @param flags One or more flags.
  831. * @see #adjustVolume(int, int)
  832. * @see #setStreamVolume(int, int, int)
  833. * @throws SecurityException if the adjustment triggers a Do Not Disturb change
  834. * and the caller is not granted notification policy access.
  835. */
  836. public void adjustStreamVolume(int streamType, int direction, int flags) {
  837. final IAudioService service = getService();
  838. try {
  839. service.adjustStreamVolume(streamType, direction, flags,
  840. getContext().getOpPackageName());
  841. } catch (RemoteException e) {
  842. throw e.rethrowFromSystemServer();
  843. }
  844. }
  845. /**
  846. * Adjusts the volume of the most relevant stream. For example, if a call is
  847. * active, it will have the highest priority regardless of if the in-call
  848. * screen is showing. Another example, if music is playing in the background
  849. * and a call is not active, the music stream will be adjusted.
  850. * <p>
  851. * This method should only be used by applications that replace the
  852. * platform-wide management of audio settings or the main telephony
  853. * application.
  854. * <p>
  855. * This method has no effect if the device implements a fixed volume policy
  856. * as indicated by {@link #isVolumeFixed()}.
  857. *
  858. * @param direction The direction to adjust the volume. One of
  859. * {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE},
  860. * {@link #ADJUST_SAME}, {@link #ADJUST_MUTE},
  861. * {@link #ADJUST_UNMUTE}, or {@link #ADJUST_TOGGLE_MUTE}.
  862. * @param flags One or more flags.
  863. * @see #adjustSuggestedStreamVolume(int, int, int)
  864. * @see #adjustStreamVolume(int, int, int)
  865. * @see #setStreamVolume(int, int, int)
  866. * @see #isVolumeFixed()
  867. */
  868. public void adjustVolume(int direction, int flags) {
  869. MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(getContext());
  870. helper.sendAdjustVolumeBy(USE_DEFAULT_STREAM_TYPE, direction, flags);
  871. }
  872. /**
  873. * Adjusts the volume of the most relevant stream, or the given fallback
  874. * stream.
  875. * <p>
  876. * This method should only be used by applications that replace the
  877. * platform-wide management of audio settings or the main telephony
  878. * application.
  879. * <p>
  880. * This method has no effect if the device implements a fixed volume policy
  881. * as indicated by {@link #isVolumeFixed()}.
  882. *
  883. * @param direction The direction to adjust the volume. One of
  884. * {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE},
  885. * {@link #ADJUST_SAME}, {@link #ADJUST_MUTE},
  886. * {@link #ADJUST_UNMUTE}, or {@link #ADJUST_TOGGLE_MUTE}.
  887. * @param suggestedStreamType The stream type that will be used if there
  888. * isn't a relevant stream. {@link #USE_DEFAULT_STREAM_TYPE} is
  889. * valid here.
  890. * @param flags One or more flags.
  891. * @see #adjustVolume(int, int)
  892. * @see #adjustStreamVolume(int, int, int)
  893. * @see #setStreamVolume(int, int, int)
  894. * @see #isVolumeFixed()
  895. */
  896. public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
  897. MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(getContext());
  898. helper.sendAdjustVolumeBy(suggestedStreamType, direction, flags);
  899. }
  900. /** @hide */
  901. @UnsupportedAppUsage
  902. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  903. public void setMasterMute(boolean mute, int flags) {
  904. final IAudioService service = getService();
  905. try {
  906. service.setMasterMute(mute, flags, getContext().getOpPackageName(),
  907. UserHandle.getCallingUserId());
  908. } catch (RemoteException e) {
  909. throw e.rethrowFromSystemServer();
  910. }
  911. }
  912. /**
  913. * Returns the current ringtone mode.
  914. *
  915. * @return The current ringtone mode, one of {@link #RINGER_MODE_NORMAL},
  916. * {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
  917. * @see #setRingerMode(int)
  918. */
  919. public int getRingerMode() {
  920. final IAudioService service = getService();
  921. try {
  922. return service.getRingerModeExternal();
  923. } catch (RemoteException e) {
  924. throw e.rethrowFromSystemServer();
  925. }
  926. }
  927. /**
  928. * Checks valid ringer mode values.
  929. *
  930. * @return true if the ringer mode indicated is valid, false otherwise.
  931. *
  932. * @see #setRingerMode(int)
  933. * @hide
  934. */
  935. @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  936. public static boolean isValidRingerMode(int ringerMode) {
  937. if (ringerMode < 0 || ringerMode > RINGER_MODE_MAX) {
  938. return false;
  939. }
  940. final IAudioService service = getService();
  941. try {
  942. return service.isValidRingerMode(ringerMode);
  943. } catch (RemoteException e) {
  944. throw e.rethrowFromSystemServer();
  945. }
  946. }
  947. /**
  948. * Returns the maximum volume index for a particular stream.
  949. *
  950. * @param streamType The stream type whose maximum volume index is returned.
  951. * @return The maximum valid volume index for the stream.
  952. * @see #getStreamVolume(int)
  953. */
  954. public int getStreamMaxVolume(int streamType) {
  955. final IAudioService service = getService();
  956. try {
  957. return service.getStreamMaxVolume(streamType);
  958. } catch (RemoteException e) {
  959. throw e.rethrowFromSystemServer();
  960. }
  961. }
  962. /**
  963. * Returns the minimum volume index for a particular stream.
  964. * @param streamType The stream type whose minimum volume index is returned. Must be one of
  965. * {@link #STREAM_VOICE_CALL}, {@link #STREAM_SYSTEM},
  966. * {@link #STREAM_RING}, {@link #STREAM_MUSIC}, {@link #STREAM_ALARM},
  967. * {@link #STREAM_NOTIFICATION}, {@link #STREAM_DTMF} or {@link #STREAM_ACCESSIBILITY}.
  968. * @return The minimum valid volume index for the stream.
  969. * @see #getStreamVolume(int)
  970. */
  971. public int getStreamMinVolume(int streamType) {
  972. if (!isPublicStreamType(streamType)) {
  973. throw new IllegalArgumentException("Invalid stream type " + streamType);
  974. }
  975. return getStreamMinVolumeInt(streamType);
  976. }
  977. /**
  978. * @hide
  979. * Same as {@link #getStreamMinVolume(int)} but without the check on the public stream type.
  980. * @param streamType The stream type whose minimum volume index is returned.
  981. * @return The minimum valid volume index for the stream.
  982. * @see #getStreamVolume(int)
  983. */
  984. public int getStreamMinVolumeInt(int streamType) {
  985. final IAudioService service = getService();
  986. try {
  987. return service.getStreamMinVolume(streamType);
  988. } catch (RemoteException e) {
  989. throw e.rethrowFromSystemServer();
  990. }
  991. }
  992. /**
  993. * Returns the current volume index for a particular stream.
  994. *
  995. * @param streamType The stream type whose volume index is returned.
  996. * @return The current volume index for the stream.
  997. * @see #getStreamMaxVolume(int)
  998. * @see #setStreamVolume(int, int, int)
  999. */
  1000. public int getStreamVolume(int streamType) {
  1001. final IAudioService service = getService();
  1002. try {
  1003. return service.getStreamVolume(streamType);
  1004. } catch (RemoteException e) {
  1005. throw e.rethrowFromSystemServer();
  1006. }
  1007. }
  1008. // keep in sync with frameworks/av/services/audiopolicy/common/include/Volume.h
  1009. private static final float VOLUME_MIN_DB = -758.0f;
  1010. /** @hide */
  1011. @IntDef(flag = false, prefix = "STREAM", value = {
  1012. STREAM_VOICE_CALL,
  1013. STREAM_SYSTEM,
  1014. STREAM_RING,
  1015. STREAM_MUSIC,
  1016. STREAM_ALARM,
  1017. STREAM_NOTIFICATION,
  1018. STREAM_DTMF,
  1019. STREAM_ACCESSIBILITY }
  1020. )
  1021. @Retention(RetentionPolicy.SOURCE)
  1022. public @interface PublicStreamTypes {}
  1023. /**
  1024. * Returns the volume in dB (decibel) for the given stream type at the given volume index, on
  1025. * the given type of audio output device.
  1026. * @param streamType stream type for which the volume is queried.
  1027. * @param index the volume index for which the volume is queried. The index value must be
  1028. * between the minimum and maximum index values for the given stream type (see
  1029. * {@link #getStreamMinVolume(int)} and {@link #getStreamMaxVolume(int)}).
  1030. * @param deviceType the type of audio output device for which volume is queried.
  1031. * @return a volume expressed in dB.
  1032. * A negative value indicates the audio signal is attenuated. A typical maximum value
  1033. * at the maximum volume index is 0 dB (no attenuation nor amplification). Muting is
  1034. * reflected by a value of {@link Float#NEGATIVE_INFINITY}.
  1035. */
  1036. public float getStreamVolumeDb(@PublicStreamTypes int streamType, int index,
  1037. @AudioDeviceInfo.AudioDeviceTypeOut int deviceType) {
  1038. if (!isPublicStreamType(streamType)) {
  1039. throw new IllegalArgumentException("Invalid stream type " + streamType);
  1040. }
  1041. if (index > getStreamMaxVolume(streamType) || index < getStreamMinVolume(streamType)) {
  1042. throw new IllegalArgumentException("Invalid stream volume index " + index);
  1043. }
  1044. if (!AudioDeviceInfo.isValidAudioDeviceTypeOut(deviceType)) {
  1045. throw new IllegalArgumentException("Invalid audio output device type " + deviceType);
  1046. }
  1047. final float gain = AudioSystem.getStreamVolumeDB(streamType, index,
  1048. AudioDeviceInfo.convertDeviceTypeToInternalDevice(deviceType));
  1049. if (gain <= VOLUME_MIN_DB) {
  1050. return Float.NEGATIVE_INFINITY;
  1051. } else {
  1052. return gain;
  1053. }
  1054. }
  1055. private static boolean isPublicStreamType(int streamType) {
  1056. switch (streamType) {
  1057. case STREAM_VOICE_CALL:
  1058. case STREAM_SYSTEM:
  1059. case STREAM_RING:
  1060. case STREAM_MUSIC:
  1061. case STREAM_ALARM:
  1062. case STREAM_NOTIFICATION:
  1063. case STREAM_DTMF:
  1064. case STREAM_ACCESSIBILITY:
  1065. return true;
  1066. default:
  1067. return false;
  1068. }
  1069. }
  1070. /**
  1071. * Get last audible volume before stream was muted.
  1072. *
  1073. * @hide
  1074. */
  1075. @UnsupportedAppUsage
  1076. public int getLastAudibleStreamVolume(int streamType) {
  1077. final IAudioService service = getService();
  1078. try {
  1079. return service.getLastAudibleStreamVolume(streamType);
  1080. } catch (RemoteException e) {
  1081. throw e.rethrowFromSystemServer();
  1082. }
  1083. }
  1084. /**
  1085. * Get the stream type whose volume is driving the UI sounds volume.
  1086. * UI sounds are screen lock/unlock, camera shutter, key clicks...
  1087. * It is assumed that this stream type is also tied to ringer mode changes.
  1088. * @hide
  1089. */
  1090. public int getUiSoundsStreamType() {
  1091. final IAudioService service = getService();
  1092. try {
  1093. return service.getUiSoundsStreamType();
  1094. } catch (RemoteException e) {
  1095. throw e.rethrowFromSystemServer();
  1096. }
  1097. }
  1098. /**
  1099. * Sets the ringer mode.
  1100. * <p>
  1101. * Silent mode will mute the volume and will not vibrate. Vibrate mode will
  1102. * mute the volume and vibrate. Normal mode will be audible and may vibrate
  1103. * according to user settings.
  1104. * <p>This method has no effect if the device implements a fixed volume policy
  1105. * as indicated by {@link #isVolumeFixed()}.
  1106. * * <p>From N onward, ringer mode adjustments that would toggle Do Not Disturb are not allowed
  1107. * unless the app has been granted Do Not Disturb Access.
  1108. * See {@link NotificationManager#isNotificationPolicyAccessGranted()}.
  1109. * @param ringerMode The ringer mode, one of {@link #RINGER_MODE_NORMAL},
  1110. * {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
  1111. * @see #getRingerMode()
  1112. * @see #isVolumeFixed()
  1113. */
  1114. public void setRingerMode(int ringerMode) {
  1115. if (!isValidRingerMode(ringerMode)) {
  1116. return;
  1117. }
  1118. final IAudioService service = getService();
  1119. try {
  1120. service.setRingerModeExternal(ringerMode, getContext().getOpPackageName());
  1121. } catch (RemoteException e) {
  1122. throw e.rethrowFromSystemServer();
  1123. }
  1124. }
  1125. /**
  1126. * Sets the volume index for a particular stream.
  1127. * <p>This method has no effect if the device implements a fixed volume policy
  1128. * as indicated by {@link #isVolumeFixed()}.
  1129. * <p>From N onward, volume adjustments that would toggle Do Not Disturb are not allowed unless
  1130. * the app has been granted Do Not Disturb Access.
  1131. * See {@link NotificationManager#isNotificationPolicyAccessGranted()}.
  1132. * @param streamType The stream whose volume index should be set.
  1133. * @param index The volume index to set. See
  1134. * {@link #getStreamMaxVolume(int)} for the largest valid value.
  1135. * @param flags One or more flags.
  1136. * @see #getStreamMaxVolume(int)
  1137. * @see #getStreamVolume(int)
  1138. * @see #isVolumeFixed()
  1139. * @throws SecurityException if the volume change triggers a Do Not Disturb change
  1140. * and the caller is not granted notification policy access.
  1141. */
  1142. public void setStreamVolume(int streamType, int index, int flags) {
  1143. final IAudioService service = getService();
  1144. try {
  1145. service.setStreamVolume(streamType, index, flags, getContext().getOpPackageName());
  1146. } catch (RemoteException e) {
  1147. throw e.rethrowFromSystemServer();
  1148. }
  1149. }
  1150. /**
  1151. * Sets the volume index for a particular {@link AudioAttributes}.
  1152. * @param attr The {@link AudioAttributes} whose volume index should be set.
  1153. * @param index The volume index to set. See
  1154. * {@link #getMaxVolumeIndexForAttributes(AudioAttributes)} for the largest valid value
  1155. * {@link #getMinVolumeIndexForAttributes(AudioAttributes)} for the lowest valid value.
  1156. * @param flags One or more flags.
  1157. * @see #getMaxVolumeIndexForAttributes(AudioAttributes)
  1158. * @see #getMinVolumeIndexForAttributes(AudioAttributes)
  1159. * @see #isVolumeFixed()
  1160. * @hide
  1161. */
  1162. @SystemApi
  1163. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1164. public void setVolumeIndexForAttributes(@NonNull AudioAttributes attr, int index, int flags) {
  1165. Preconditions.checkNotNull(attr, "attr must not be null");
  1166. final IAudioService service = getService();
  1167. try {
  1168. service.setVolumeIndexForAttributes(attr, index, flags,
  1169. getContext().getOpPackageName());
  1170. } catch (RemoteException e) {
  1171. throw e.rethrowFromSystemServer();
  1172. }
  1173. }
  1174. /**
  1175. * Returns the current volume index for a particular {@link AudioAttributes}.
  1176. *
  1177. * @param attr The {@link AudioAttributes} whose volume index is returned.
  1178. * @return The current volume index for the stream.
  1179. * @see #getMaxVolumeIndexForAttributes(AudioAttributes)
  1180. * @see #getMinVolumeIndexForAttributes(AudioAttributes)
  1181. * @see #setVolumeForAttributes(AudioAttributes, int, int)
  1182. * @hide
  1183. */
  1184. @SystemApi
  1185. @IntRange(from = 0)
  1186. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1187. public int getVolumeIndexForAttributes(@NonNull AudioAttributes attr) {
  1188. Preconditions.checkNotNull(attr, "attr must not be null");
  1189. final IAudioService service = getService();
  1190. try {
  1191. return service.getVolumeIndexForAttributes(attr);
  1192. } catch (RemoteException e) {
  1193. throw e.rethrowFromSystemServer();
  1194. }
  1195. }
  1196. /**
  1197. * Returns the maximum volume index for a particular {@link AudioAttributes}.
  1198. *
  1199. * @param attr The {@link AudioAttributes} whose maximum volume index is returned.
  1200. * @return The maximum valid volume index for the {@link AudioAttributes}.
  1201. * @see #getVolumeIndexForAttributes(AudioAttributes)
  1202. * @hide
  1203. */
  1204. @SystemApi
  1205. @IntRange(from = 0)
  1206. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1207. public int getMaxVolumeIndexForAttributes(@NonNull AudioAttributes attr) {
  1208. Preconditions.checkNotNull(attr, "attr must not be null");
  1209. final IAudioService service = getService();
  1210. try {
  1211. return service.getMaxVolumeIndexForAttributes(attr);
  1212. } catch (RemoteException e) {
  1213. throw e.rethrowFromSystemServer();
  1214. }
  1215. }
  1216. /**
  1217. * Returns the minimum volume index for a particular {@link AudioAttributes}.
  1218. *
  1219. * @param attr The {@link AudioAttributes} whose minimum volume index is returned.
  1220. * @return The minimum valid volume index for the {@link AudioAttributes}.
  1221. * @see #getVolumeIndexForAttributes(AudioAttributes)
  1222. * @hide
  1223. */
  1224. @SystemApi
  1225. @IntRange(from = 0)
  1226. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1227. public int getMinVolumeIndexForAttributes(@NonNull AudioAttributes attr) {
  1228. Preconditions.checkNotNull(attr, "attr must not be null");
  1229. final IAudioService service = getService();
  1230. try {
  1231. return service.getMinVolumeIndexForAttributes(attr);
  1232. } catch (RemoteException e) {
  1233. throw e.rethrowFromSystemServer();
  1234. }
  1235. }
  1236. /**
  1237. * Set the system usages to be supported on this device.
  1238. * @param systemUsages array of system usages to support {@link AttributeSystemUsage}
  1239. * @hide
  1240. */
  1241. @SystemApi
  1242. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1243. public void setSupportedSystemUsages(@NonNull @AttributeSystemUsage int[] systemUsages) {
  1244. Objects.requireNonNull(systemUsages, "systemUsages must not be null");
  1245. final IAudioService service = getService();
  1246. try {
  1247. service.setSupportedSystemUsages(systemUsages);
  1248. } catch (RemoteException e) {
  1249. throw e.rethrowFromSystemServer();
  1250. }
  1251. }
  1252. /**
  1253. * Get the system usages supported on this device.
  1254. * @return array of supported system usages {@link AttributeSystemUsage}
  1255. * @hide
  1256. */
  1257. @SystemApi
  1258. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1259. public @NonNull @AttributeSystemUsage int[] getSupportedSystemUsages() {
  1260. final IAudioService service = getService();
  1261. try {
  1262. return service.getSupportedSystemUsages();
  1263. } catch (RemoteException e) {
  1264. throw e.rethrowFromSystemServer();
  1265. }
  1266. }
  1267. /**
  1268. * Solo or unsolo a particular stream.
  1269. * <p>
  1270. * Do not use. This method has been deprecated and is now a no-op.
  1271. * {@link #requestAudioFocus} should be used for exclusive audio playback.
  1272. *
  1273. * @param streamType The stream to be soloed/unsoloed.
  1274. * @param state The required solo state: true for solo ON, false for solo
  1275. * OFF
  1276. * @see #isVolumeFixed()
  1277. * @deprecated Do not use. If you need exclusive audio playback use
  1278. * {@link #requestAudioFocus}.
  1279. */
  1280. @Deprecated
  1281. public void setStreamSolo(int streamType, boolean state) {
  1282. Log.w(TAG, "setStreamSolo has been deprecated. Do not use.");
  1283. }
  1284. /**
  1285. * Mute or unmute an audio stream.
  1286. * <p>
  1287. * This method should only be used by applications that replace the
  1288. * platform-wide management of audio settings or the main telephony
  1289. * application.
  1290. * <p>
  1291. * This method has no effect if the device implements a fixed volume policy
  1292. * as indicated by {@link #isVolumeFixed()}.
  1293. * <p>
  1294. * This method was deprecated in API level 22. Prior to API level 22 this
  1295. * method had significantly different behavior and should be used carefully.
  1296. * The following applies only to pre-22 platforms:
  1297. * <ul>
  1298. * <li>The mute command is protected against client process death: if a
  1299. * process with an active mute request on a stream dies, this stream will be
  1300. * unmuted automatically.</li>
  1301. * <li>The mute requests for a given stream are cumulative: the AudioManager
  1302. * can receive several mute requests from one or more clients and the stream
  1303. * will be unmuted only when the same number of unmute requests are
  1304. * received.</li>
  1305. * <li>For a better user experience, applications MUST unmute a muted stream
  1306. * in onPause() and mute is again in onResume() if appropriate.</li>
  1307. * </ul>
  1308. *
  1309. * @param streamType The stream to be muted/unmuted.
  1310. * @param state The required mute state: true for mute ON, false for mute
  1311. * OFF
  1312. * @see #isVolumeFixed()
  1313. * @deprecated Use {@link #adjustStreamVolume(int, int, int)} with
  1314. * {@link #ADJUST_MUTE} or {@link #ADJUST_UNMUTE} instead.
  1315. */
  1316. @Deprecated
  1317. public void setStreamMute(int streamType, boolean state) {
  1318. Log.w(TAG, "setStreamMute is deprecated. adjustStreamVolume should be used instead.");
  1319. int direction = state ? ADJUST_MUTE : ADJUST_UNMUTE;
  1320. if (streamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
  1321. adjustSuggestedStreamVolume(direction, streamType, 0);
  1322. } else {
  1323. adjustStreamVolume(streamType, direction, 0);
  1324. }
  1325. }
  1326. /**
  1327. * Returns the current mute state for a particular stream.
  1328. *
  1329. * @param streamType The stream to get mute state for.
  1330. * @return The mute state for the given stream.
  1331. * @see #adjustStreamVolume(int, int, int)
  1332. */
  1333. public boolean isStreamMute(int streamType) {
  1334. final IAudioService service = getService();
  1335. try {
  1336. return service.isStreamMute(streamType);
  1337. } catch (RemoteException e) {
  1338. throw e.rethrowFromSystemServer();
  1339. }
  1340. }
  1341. /**
  1342. * get master mute state.
  1343. *
  1344. * @hide
  1345. */
  1346. @UnsupportedAppUsage
  1347. public boolean isMasterMute() {
  1348. final IAudioService service = getService();
  1349. try {
  1350. return service.isMasterMute();
  1351. } catch (RemoteException e) {
  1352. throw e.rethrowFromSystemServer();
  1353. }
  1354. }
  1355. /**
  1356. * forces the stream controlled by hard volume keys
  1357. * specifying streamType == -1 releases control to the
  1358. * logic.
  1359. *
  1360. * @hide
  1361. */
  1362. @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
  1363. @UnsupportedAppUsage
  1364. public void forceVolumeControlStream(int streamType) {
  1365. final IAudioService service = getService();
  1366. try {
  1367. service.forceVolumeControlStream(streamType, mICallBack);
  1368. } catch (RemoteException e) {
  1369. throw e.rethrowFromSystemServer();
  1370. }
  1371. }
  1372. /**
  1373. * Returns whether a particular type should vibrate according to user
  1374. * settings and the current ringer mode.
  1375. * <p>
  1376. * This shouldn't be needed by most clients that use notifications to
  1377. * vibrate. The notification manager will not vibrate if the policy doesn't
  1378. * allow it, so the client should always set a vibrate pattern and let the
  1379. * notification manager control whether or not to actually vibrate.
  1380. *
  1381. * @param vibrateType The type of vibrate. One of
  1382. * {@link #VIBRATE_TYPE_NOTIFICATION} or
  1383. * {@link #VIBRATE_TYPE_RINGER}.
  1384. * @return Whether the type should vibrate at the instant this method is
  1385. * called.
  1386. * @see #setVibrateSetting(int, int)
  1387. * @see #getVibrateSetting(int)
  1388. * @deprecated Applications should maintain their own vibrate policy based on
  1389. * current ringer mode that can be queried via {@link #getRingerMode()}.
  1390. */
  1391. public boolean shouldVibrate(int vibrateType) {
  1392. final IAudioService service = getService();
  1393. try {
  1394. return service.shouldVibrate(vibrateType);
  1395. } catch (RemoteException e) {
  1396. throw e.rethrowFromSystemServer();
  1397. }
  1398. }
  1399. /**
  1400. * Returns whether the user's vibrate setting for a vibrate type.
  1401. * <p>
  1402. * This shouldn't be needed by most clients that want to vibrate, instead
  1403. * see {@link #shouldVibrate(int)}.
  1404. *
  1405. * @param vibrateType The type of vibrate. One of
  1406. * {@link #VIBRATE_TYPE_NOTIFICATION} or
  1407. * {@link #VIBRATE_TYPE_RINGER}.
  1408. * @return The vibrate setting, one of {@link #VIBRATE_SETTING_ON},
  1409. * {@link #VIBRATE_SETTING_OFF}, or
  1410. * {@link #VIBRATE_SETTING_ONLY_SILENT}.
  1411. * @see #setVibrateSetting(int, int)
  1412. * @see #shouldVibrate(int)
  1413. * @deprecated Applications should maintain their own vibrate policy based on
  1414. * current ringer mode that can be queried via {@link #getRingerMode()}.
  1415. */
  1416. public int getVibrateSetting(int vibrateType) {
  1417. final IAudioService service = getService();
  1418. try {
  1419. return service.getVibrateSetting(vibrateType);
  1420. } catch (RemoteException e) {
  1421. throw e.rethrowFromSystemServer();
  1422. }
  1423. }
  1424. /**
  1425. * Sets the setting for when the vibrate type should vibrate.
  1426. * <p>
  1427. * This method should only be used by applications that replace the platform-wide
  1428. * management of audio settings or the main telephony application.
  1429. *
  1430. * @param vibrateType The type of vibrate. One of
  1431. * {@link #VIBRATE_TYPE_NOTIFICATION} or
  1432. * {@link #VIBRATE_TYPE_RINGER}.
  1433. * @param vibrateSetting The vibrate setting, one of
  1434. * {@link #VIBRATE_SETTING_ON},
  1435. * {@link #VIBRATE_SETTING_OFF}, or
  1436. * {@link #VIBRATE_SETTING_ONLY_SILENT}.
  1437. * @see #getVibrateSetting(int)
  1438. * @see #shouldVibrate(int)
  1439. * @deprecated Applications should maintain their own vibrate policy based on
  1440. * current ringer mode that can be queried via {@link #getRingerMode()}.
  1441. */
  1442. public void setVibrateSetting(int vibrateType, int vibrateSetting) {
  1443. final IAudioService service = getService();
  1444. try {
  1445. service.setVibrateSetting(vibrateType, vibrateSetting);
  1446. } catch (RemoteException e) {
  1447. throw e.rethrowFromSystemServer();
  1448. }
  1449. }
  1450. /**
  1451. * Sets the speakerphone on or off.
  1452. * <p>
  1453. * This method should only be used by applications that replace the platform-wide
  1454. * management of audio settings or the main telephony application.
  1455. *
  1456. * @param on set <var>true</var> to turn on speakerphone;
  1457. * <var>false</var> to turn it off
  1458. */
  1459. public void setSpeakerphoneOn(boolean on){
  1460. final IAudioService service = getService();
  1461. try {
  1462. service.setSpeakerphoneOn(mICallBack, on);
  1463. } catch (RemoteException e) {
  1464. throw e.rethrowFromSystemServer();
  1465. }
  1466. }
  1467. /**
  1468. * Checks whether the speakerphone is on or off.
  1469. *
  1470. * @return true if speakerphone is on, false if it's off
  1471. */
  1472. public boolean isSpeakerphoneOn() {
  1473. final IAudioService service = getService();
  1474. try {
  1475. return service.isSpeakerphoneOn();
  1476. } catch (RemoteException e) {
  1477. throw e.rethrowFromSystemServer();
  1478. }
  1479. }
  1480. /**
  1481. * Specifies whether the audio played by this app may or may not be captured by other apps or
  1482. * the system.
  1483. *
  1484. * The default is {@link AudioAttributes#ALLOW_CAPTURE_BY_ALL}.
  1485. *
  1486. * There are multiple ways to set this policy:
  1487. * <ul>
  1488. * <li> for each track independently, see
  1489. * {@link AudioAttributes.Builder#setAllowedCapturePolicy(int)} </li>
  1490. * <li> application-wide at runtime, with this method </li>
  1491. * <li> application-wide at build time, see {@code allowAudioPlaybackCapture} in the application
  1492. * manifest. </li>
  1493. * </ul>
  1494. * The most restrictive policy is always applied.
  1495. *
  1496. * See {@link AudioPlaybackCaptureConfiguration} for more details on
  1497. * which audio signals can be captured.
  1498. *
  1499. * @param capturePolicy one of
  1500. * {@link AudioAttributes#ALLOW_CAPTURE_BY_ALL},
  1501. * {@link AudioAttributes#ALLOW_CAPTURE_BY_SYSTEM},
  1502. * {@link AudioAttributes#ALLOW_CAPTURE_BY_NONE}.
  1503. * @throws RuntimeException if the argument is not a valid value.
  1504. */
  1505. public void setAllowedCapturePolicy(@AudioAttributes.CapturePolicy int capturePolicy) {
  1506. // TODO: also pass the package in case multiple packages have the same UID
  1507. final IAudioService service = getService();
  1508. try {
  1509. int result = service.setAllowedCapturePolicy(capturePolicy);
  1510. if (result != AudioSystem.AUDIO_STATUS_OK) {
  1511. Log.e(TAG, "Could not setAllowedCapturePolicy: " + result);
  1512. return;
  1513. }
  1514. } catch (RemoteException e) {
  1515. throw e.rethrowFromSystemServer();
  1516. }
  1517. }
  1518. /**
  1519. * Return the capture policy.
  1520. * @return the capture policy set by {@link #setAllowedCapturePolicy(int)} or
  1521. * the default if it was not called.
  1522. */
  1523. @AudioAttributes.CapturePolicy
  1524. public int getAllowedCapturePolicy() {
  1525. int result = AudioAttributes.ALLOW_CAPTURE_BY_ALL;
  1526. try {
  1527. result = getService().getAllowedCapturePolicy();
  1528. } catch (RemoteException e) {
  1529. Log.e(TAG, "Failed to query allowed capture policy: " + e);
  1530. }
  1531. return result;
  1532. }
  1533. //====================================================================
  1534. // Audio Product Strategy routing
  1535. /**
  1536. * @hide
  1537. * Set the preferred device for a given strategy, i.e. the audio routing to be used by
  1538. * this audio strategy. Note that the device may not be available at the time the preferred
  1539. * device is set, but it will be used once made available.
  1540. * <p>Use {@link #removePreferredDeviceForStrategy(AudioProductStrategy)} to cancel setting
  1541. * this preference for this strategy.</p>
  1542. * @param strategy the audio strategy whose routing will be affected
  1543. * @param device the audio device to route to when available
  1544. * @return true if the operation was successful, false otherwise
  1545. */
  1546. @SystemApi
  1547. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1548. public boolean setPreferredDeviceForStrategy(@NonNull AudioProductStrategy strategy,
  1549. @NonNull AudioDeviceAttributes device) {
  1550. return setPreferredDevicesForStrategy(strategy, Arrays.asList(device));
  1551. }
  1552. /**
  1553. * @hide
  1554. * Removes the preferred audio device(s) previously set with
  1555. * {@link #setPreferredDeviceForStrategy(AudioProductStrategy, AudioDeviceAttributes)} or
  1556. * {@link #setPreferredDevicesForStrategy(AudioProductStrategy, List<AudioDeviceAttributes>)}.
  1557. * @param strategy the audio strategy whose routing will be affected
  1558. * @return true if the operation was successful, false otherwise (invalid strategy, or no
  1559. * device set for example)
  1560. */
  1561. @SystemApi
  1562. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1563. public boolean removePreferredDeviceForStrategy(@NonNull AudioProductStrategy strategy) {
  1564. Objects.requireNonNull(strategy);
  1565. try {
  1566. final int status =
  1567. getService().removePreferredDevicesForStrategy(strategy.getId());
  1568. return status == AudioSystem.SUCCESS;
  1569. } catch (RemoteException e) {
  1570. throw e.rethrowFromSystemServer();
  1571. }
  1572. }
  1573. /**
  1574. * @hide
  1575. * Return the preferred device for an audio strategy, previously set with
  1576. * {@link #setPreferredDeviceForStrategy(AudioProductStrategy, AudioDeviceAttributes)} or
  1577. * {@link #setPreferredDevicesForStrategy(AudioProductStrategy, List<AudioDeviceAttributes>)}
  1578. * @param strategy the strategy to query
  1579. * @return the preferred device for that strategy, if multiple devices are set as preferred
  1580. * devices, the first one in the list will be returned. Null will be returned if none was
  1581. * ever set or if the strategy is invalid
  1582. */
  1583. @SystemApi
  1584. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1585. @Nullable
  1586. public AudioDeviceAttributes getPreferredDeviceForStrategy(
  1587. @NonNull AudioProductStrategy strategy) {
  1588. List<AudioDeviceAttributes> devices = getPreferredDevicesForStrategy(strategy);
  1589. return devices.isEmpty() ? null : devices.get(0);
  1590. }
  1591. /**
  1592. * @hide
  1593. * Set the preferred devices for a given strategy, i.e. the audio routing to be used by
  1594. * this audio strategy. Note that the devices may not be available at the time the preferred
  1595. * devices is set, but it will be used once made available.
  1596. * <p>Use {@link #removePreferredDeviceForStrategy(AudioProductStrategy)} to cancel setting
  1597. * this preference for this strategy.</p>
  1598. * Note that the list of devices is not a list ranked by preference, but a list of one or more
  1599. * devices used simultaneously to output the same audio signal.
  1600. * @param strategy the audio strategy whose routing will be affected
  1601. * @param devices a non-empty list of the audio devices to route to when available
  1602. * @return true if the operation was successful, false otherwise
  1603. */
  1604. @SystemApi
  1605. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1606. public boolean setPreferredDevicesForStrategy(@NonNull AudioProductStrategy strategy,
  1607. @NonNull List<AudioDeviceAttributes> devices) {
  1608. Objects.requireNonNull(strategy);
  1609. Objects.requireNonNull(devices);
  1610. if (devices.isEmpty()) {
  1611. throw new IllegalArgumentException(
  1612. "Tried to set preferred devices for strategy with a empty list");
  1613. }
  1614. for (AudioDeviceAttributes device : devices) {
  1615. Objects.requireNonNull(device);
  1616. }
  1617. try {
  1618. final int status =
  1619. getService().setPreferredDevicesForStrategy(strategy.getId(), devices);
  1620. return status == AudioSystem.SUCCESS;
  1621. } catch (RemoteException e) {
  1622. throw e.rethrowFromSystemServer();
  1623. }
  1624. }
  1625. /**
  1626. * @hide
  1627. * Return the preferred devices for an audio strategy, previously set with
  1628. * {@link #setPreferredDeviceForStrategy(AudioProductStrategy, AudioDeviceAttributes)}
  1629. * {@link #setPreferredDevicesForStrategy(AudioProductStrategy, List<AudioDeviceAttributes>)}
  1630. * @param strategy the strategy to query
  1631. * @return the preferred device for that strategy, or null if none was ever set or if the
  1632. * strategy is invalid
  1633. */
  1634. @SystemApi
  1635. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1636. @NonNull
  1637. public List<AudioDeviceAttributes> getPreferredDevicesForStrategy(
  1638. @NonNull AudioProductStrategy strategy) {
  1639. Objects.requireNonNull(strategy);
  1640. try {
  1641. return getService().getPreferredDevicesForStrategy(strategy.getId());
  1642. } catch (RemoteException e) {
  1643. throw e.rethrowFromSystemServer();
  1644. }
  1645. }
  1646. /**
  1647. * @hide
  1648. * Interface to be notified of changes in the preferred audio device set for a given audio
  1649. * strategy.
  1650. * <p>Note that this listener will only be invoked whenever
  1651. * {@link #setPreferredDeviceForStrategy(AudioProductStrategy, AudioDeviceAttributes)} or
  1652. * {@link #setPreferredDevicesForStrategy(AudioProductStrategy, List<AudioDeviceAttributes>)}
  1653. * {@link #removePreferredDeviceForStrategy(AudioProductStrategy)} causes a change in
  1654. * preferred device. It will not be invoked directly after registration with
  1655. * {@link #addOnPreferredDeviceForStrategyChangedListener(Executor, OnPreferredDeviceForStrategyChangedListener)}
  1656. * to indicate which strategies had preferred devices at the time of registration.</p>
  1657. * @see #setPreferredDeviceForStrategy(AudioProductStrategy, AudioDeviceAttributes)
  1658. * @see #removePreferredDeviceForStrategy(AudioProductStrategy)
  1659. * @see #getPreferredDeviceForStrategy(AudioProductStrategy)
  1660. * @deprecated use #OnPreferredDevicesForStrategyChangedListener
  1661. */
  1662. @SystemApi
  1663. @Deprecated
  1664. public interface OnPreferredDeviceForStrategyChangedListener {
  1665. /**
  1666. * Called on the listener to indicate that the preferred audio device for the given
  1667. * strategy has changed.
  1668. * @param strategy the {@link AudioProductStrategy} whose preferred device changed
  1669. * @param device <code>null</code> if the preferred device was removed, or the newly set
  1670. * preferred audio device
  1671. */
  1672. void onPreferredDeviceForStrategyChanged(@NonNull AudioProductStrategy strategy,
  1673. @Nullable AudioDeviceAttributes device);
  1674. }
  1675. /**
  1676. * @hide
  1677. * Interface to be notified of changes in the preferred audio devices set for a given audio
  1678. * strategy.
  1679. * <p>Note that this listener will only be invoked whenever
  1680. * {@link #setPreferredDeviceForStrategy(AudioProductStrategy, AudioDeviceAttributes)} or
  1681. * {@link #setPreferredDevicesForStrategy(AudioProductStrategy, List<AudioDeviceAttributes>)}
  1682. * {@link #removePreferredDeviceForStrategy(AudioProductStrategy)} causes a change in
  1683. * preferred device(s). It will not be invoked directly after registration with
  1684. * {@link #addOnPreferredDevicesForStrategyChangedListener(
  1685. * Executor, OnPreferredDevicesForStrategyChangedListener)}
  1686. * to indicate which strategies had preferred devices at the time of registration.</p>
  1687. * @see #setPreferredDeviceForStrategy(AudioProductStrategy, AudioDeviceAttributes)
  1688. * @see #setPreferredDevicesForStrategy(AudioProductStrategy, List)
  1689. * @see #removePreferredDeviceForStrategy(AudioProductStrategy)
  1690. * @see #getPreferredDeviceForStrategy(AudioProductStrategy)
  1691. * @see #getPreferredDevicesForStrategy(AudioProductStrategy)
  1692. */
  1693. @SystemApi
  1694. public interface OnPreferredDevicesForStrategyChangedListener {
  1695. /**
  1696. * Called on the listener to indicate that the preferred audio devices for the given
  1697. * strategy has changed.
  1698. * @param strategy the {@link AudioProductStrategy} whose preferred device changed
  1699. * @param devices a list of newly set preferred audio devices
  1700. */
  1701. void onPreferredDevicesForStrategyChanged(@NonNull AudioProductStrategy strategy,
  1702. @NonNull List<AudioDeviceAttributes> devices);
  1703. }
  1704. /**
  1705. * @hide
  1706. * Adds a listener for being notified of changes to the strategy-preferred audio device.
  1707. * @param executor
  1708. * @param listener
  1709. * @throws SecurityException if the caller doesn't hold the required permission
  1710. * @deprecated use {@link #addOnPreferredDevicesForStrategyChangedListener(
  1711. * Executor, AudioManager.OnPreferredDevicesForStrategyChangedListener)} instead
  1712. */
  1713. @SystemApi
  1714. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1715. @Deprecated
  1716. public void addOnPreferredDeviceForStrategyChangedListener(
  1717. @NonNull @CallbackExecutor Executor executor,
  1718. @NonNull OnPreferredDeviceForStrategyChangedListener listener)
  1719. throws SecurityException {
  1720. // No-op, the method is deprecated.
  1721. }
  1722. /**
  1723. * @hide
  1724. * Removes a previously added listener of changes to the strategy-preferred audio device.
  1725. * @param listener
  1726. * @deprecated use {@link #removeOnPreferredDevicesForStrategyChangedListener(
  1727. * AudioManager.OnPreferredDevicesForStrategyChangedListener)} instead
  1728. */
  1729. @SystemApi
  1730. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1731. @Deprecated
  1732. public void removeOnPreferredDeviceForStrategyChangedListener(
  1733. @NonNull OnPreferredDeviceForStrategyChangedListener listener) {
  1734. // No-op, the method is deprecated.
  1735. }
  1736. /**
  1737. * @hide
  1738. * Adds a listener for being notified of changes to the strategy-preferred audio device.
  1739. * @param executor
  1740. * @param listener
  1741. * @throws SecurityException if the caller doesn't hold the required permission
  1742. */
  1743. @SystemApi
  1744. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1745. public void addOnPreferredDevicesForStrategyChangedListener(
  1746. @NonNull @CallbackExecutor Executor executor,
  1747. @NonNull OnPreferredDevicesForStrategyChangedListener listener)
  1748. throws SecurityException {
  1749. Objects.requireNonNull(executor);
  1750. Objects.requireNonNull(listener);
  1751. synchronized (mPrefDevListenerLock) {
  1752. if (hasPrefDevListener(listener)) {
  1753. throw new IllegalArgumentException(
  1754. "attempt to call addOnPreferredDevicesForStrategyChangedListener() "
  1755. + "on a previously registered listener");
  1756. }
  1757. // lazy initialization of the list of strategy-preferred device listener
  1758. if (mPrefDevListeners == null) {
  1759. mPrefDevListeners = new ArrayList<>();
  1760. }
  1761. final int oldCbCount = mPrefDevListeners.size();
  1762. mPrefDevListeners.add(new PrefDevListenerInfo(listener, executor));
  1763. if (oldCbCount == 0 && mPrefDevListeners.size() > 0) {
  1764. // register binder for callbacks
  1765. if (mPrefDevDispatcherStub == null) {
  1766. mPrefDevDispatcherStub = new StrategyPreferredDevicesDispatcherStub();
  1767. }
  1768. try {
  1769. getService().registerStrategyPreferredDevicesDispatcher(mPrefDevDispatcherStub);
  1770. } catch (RemoteException e) {
  1771. throw e.rethrowFromSystemServer();
  1772. }
  1773. }
  1774. }
  1775. }
  1776. /**
  1777. * @hide
  1778. * Removes a previously added listener of changes to the strategy-preferred audio device.
  1779. * @param listener
  1780. */
  1781. @SystemApi
  1782. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1783. public void removeOnPreferredDevicesForStrategyChangedListener(
  1784. @NonNull OnPreferredDevicesForStrategyChangedListener listener) {
  1785. Objects.requireNonNull(listener);
  1786. synchronized (mPrefDevListenerLock) {
  1787. if (!removePrefDevListener(listener)) {
  1788. throw new IllegalArgumentException(
  1789. "attempt to call removeOnPreferredDeviceForStrategyChangedListener() "
  1790. + "on an unregistered listener");
  1791. }
  1792. if (mPrefDevListeners.size() == 0) {
  1793. // unregister binder for callbacks
  1794. try {
  1795. getService().unregisterStrategyPreferredDevicesDispatcher(
  1796. mPrefDevDispatcherStub);
  1797. } catch (RemoteException e) {
  1798. throw e.rethrowFromSystemServer();
  1799. } finally {
  1800. mPrefDevDispatcherStub = null;
  1801. mPrefDevListeners = null;
  1802. }
  1803. }
  1804. }
  1805. }
  1806. private final Object mPrefDevListenerLock = new Object();
  1807. /**
  1808. * List of listeners for preferred device for strategy and their associated Executor.
  1809. * List is lazy-initialized on first registration
  1810. */
  1811. @GuardedBy("mPrefDevListenerLock")
  1812. private @Nullable ArrayList<PrefDevListenerInfo> mPrefDevListeners;
  1813. private static class PrefDevListenerInfo {
  1814. final @NonNull OnPreferredDevicesForStrategyChangedListener mListener;
  1815. final @NonNull Executor mExecutor;
  1816. PrefDevListenerInfo(OnPreferredDevicesForStrategyChangedListener listener, Executor exe) {
  1817. mListener = listener;
  1818. mExecutor = exe;
  1819. }
  1820. }
  1821. @GuardedBy("mPrefDevListenerLock")
  1822. private StrategyPreferredDevicesDispatcherStub mPrefDevDispatcherStub;
  1823. private final class StrategyPreferredDevicesDispatcherStub
  1824. extends IStrategyPreferredDevicesDispatcher.Stub {
  1825. @Override
  1826. public void dispatchPrefDevicesChanged(int strategyId,
  1827. @NonNull List<AudioDeviceAttributes> devices) {
  1828. // make a shallow copy of listeners so callback is not executed under lock
  1829. final ArrayList<PrefDevListenerInfo> prefDevListeners;
  1830. synchronized (mPrefDevListenerLock) {
  1831. if (mPrefDevListeners == null || mPrefDevListeners.size() == 0) {
  1832. return;
  1833. }
  1834. prefDevListeners = (ArrayList<PrefDevListenerInfo>) mPrefDevListeners.clone();
  1835. }
  1836. final AudioProductStrategy strategy =
  1837. AudioProductStrategy.getAudioProductStrategyWithId(strategyId);
  1838. final long ident = Binder.clearCallingIdentity();
  1839. try {
  1840. for (PrefDevListenerInfo info : prefDevListeners) {
  1841. info.mExecutor.execute(() ->
  1842. info.mListener.onPreferredDevicesForStrategyChanged(strategy, devices));
  1843. }
  1844. } finally {
  1845. Binder.restoreCallingIdentity(ident);
  1846. }
  1847. }
  1848. }
  1849. @GuardedBy("mPrefDevListenerLock")
  1850. private @Nullable PrefDevListenerInfo getPrefDevListenerInfo(
  1851. OnPreferredDevicesForStrategyChangedListener listener) {
  1852. if (mPrefDevListeners == null) {
  1853. return null;
  1854. }
  1855. for (PrefDevListenerInfo info : mPrefDevListeners) {
  1856. if (info.mListener == listener) {
  1857. return info;
  1858. }
  1859. }
  1860. return null;
  1861. }
  1862. @GuardedBy("mPrefDevListenerLock")
  1863. private boolean hasPrefDevListener(OnPreferredDevicesForStrategyChangedListener listener) {
  1864. return getPrefDevListenerInfo(listener) != null;
  1865. }
  1866. @GuardedBy("mPrefDevListenerLock")
  1867. /**
  1868. * @return true if the listener was removed from the list
  1869. */
  1870. private boolean removePrefDevListener(OnPreferredDevicesForStrategyChangedListener listener) {
  1871. final PrefDevListenerInfo infoToRemove = getPrefDevListenerInfo(listener);
  1872. if (infoToRemove != null) {
  1873. mPrefDevListeners.remove(infoToRemove);
  1874. return true;
  1875. }
  1876. return false;
  1877. }
  1878. //====================================================================
  1879. // Audio Capture Preset routing
  1880. /**
  1881. * @hide
  1882. * Set the preferred device for a given capture preset, i.e. the audio routing to be used by
  1883. * this capture preset. Note that the device may not be available at the time the preferred
  1884. * device is set, but it will be used once made available.
  1885. * <p>Use {@link #clearPreferredDevicesForCapturePreset(int)} to cancel setting this preference
  1886. * for this capture preset.</p>
  1887. * @param capturePreset the audio capture preset whose routing will be affected
  1888. * @param device the audio device to route to when available
  1889. * @return true if the operation was successful, false otherwise
  1890. */
  1891. @SystemApi
  1892. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1893. public boolean setPreferredDeviceForCapturePreset(@MediaRecorder.SystemSource int capturePreset,
  1894. @NonNull AudioDeviceAttributes device) {
  1895. return setPreferredDevicesForCapturePreset(capturePreset, Arrays.asList(device));
  1896. }
  1897. /**
  1898. * @hide
  1899. * Remove all the preferred audio devices previously set
  1900. * @param capturePreset the audio capture preset whose routing will be affected
  1901. * @return true if the operation was successful, false otherwise (invalid capture preset, or no
  1902. * device set for example)
  1903. */
  1904. @SystemApi
  1905. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1906. public boolean clearPreferredDevicesForCapturePreset(
  1907. @MediaRecorder.SystemSource int capturePreset) {
  1908. if (!MediaRecorder.isValidAudioSource(capturePreset)) {
  1909. return false;
  1910. }
  1911. try {
  1912. final int status = getService().clearPreferredDevicesForCapturePreset(capturePreset);
  1913. return status == AudioSystem.SUCCESS;
  1914. } catch (RemoteException e) {
  1915. throw e.rethrowFromSystemServer();
  1916. }
  1917. }
  1918. /**
  1919. * @hide
  1920. * Return the preferred devices for an audio capture preset, previously set with
  1921. * {@link #setPreferredDeviceForCapturePreset(int, AudioDeviceAttributes)}
  1922. * @param capturePreset the capture preset to query
  1923. * @return a list that contains preferred devices for that capture preset.
  1924. */
  1925. @NonNull
  1926. @SystemApi
  1927. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1928. public List<AudioDeviceAttributes> getPreferredDevicesForCapturePreset(
  1929. @MediaRecorder.SystemSource int capturePreset) {
  1930. if (!MediaRecorder.isValidAudioSource(capturePreset)) {
  1931. return new ArrayList<AudioDeviceAttributes>();
  1932. }
  1933. try {
  1934. return getService().getPreferredDevicesForCapturePreset(capturePreset);
  1935. } catch (RemoteException e) {
  1936. throw e.rethrowFromSystemServer();
  1937. }
  1938. }
  1939. private boolean setPreferredDevicesForCapturePreset(
  1940. @MediaRecorder.SystemSource int capturePreset,
  1941. @NonNull List<AudioDeviceAttributes> devices) {
  1942. Objects.requireNonNull(devices);
  1943. if (!MediaRecorder.isValidAudioSource(capturePreset)) {
  1944. return false;
  1945. }
  1946. if (devices.size() != 1) {
  1947. throw new IllegalArgumentException(
  1948. "Only support setting one preferred devices for capture preset");
  1949. }
  1950. for (AudioDeviceAttributes device : devices) {
  1951. Objects.requireNonNull(device);
  1952. }
  1953. try {
  1954. final int status =
  1955. getService().setPreferredDevicesForCapturePreset(capturePreset, devices);
  1956. return status == AudioSystem.SUCCESS;
  1957. } catch (RemoteException e) {
  1958. throw e.rethrowFromSystemServer();
  1959. }
  1960. }
  1961. /**
  1962. * @hide
  1963. * Interface to be notified of changes in the preferred audio devices set for a given capture
  1964. * preset.
  1965. * <p>Note that this listener will only be invoked whenever
  1966. * {@link #setPreferredDeviceForCapturePreset(int, AudioDeviceAttributes)} or
  1967. * {@link #clearPreferredDevicesForCapturePreset(int)} causes a change in
  1968. * preferred device. It will not be invoked directly after registration with
  1969. * {@link #addOnPreferredDevicesForCapturePresetChangedListener(
  1970. * Executor, OnPreferredDevicesForCapturePresetChangedListener)}
  1971. * to indicate which strategies had preferred devices at the time of registration.</p>
  1972. * @see #setPreferredDeviceForCapturePreset(int, AudioDeviceAttributes)
  1973. * @see #clearPreferredDevicesForCapturePreset(int)
  1974. * @see #getPreferredDevicesForCapturePreset(int)
  1975. */
  1976. @SystemApi
  1977. public interface OnPreferredDevicesForCapturePresetChangedListener {
  1978. /**
  1979. * Called on the listener to indicate that the preferred audio devices for the given
  1980. * capture preset has changed.
  1981. * @param capturePreset the capture preset whose preferred device changed
  1982. * @param devices a list of newly set preferred audio devices
  1983. */
  1984. void onPreferredDevicesForCapturePresetChanged(
  1985. @MediaRecorder.SystemSource int capturePreset,
  1986. @NonNull List<AudioDeviceAttributes> devices);
  1987. }
  1988. /**
  1989. * @hide
  1990. * Adds a listener for being notified of changes to the capture-preset-preferred audio device.
  1991. * @param executor
  1992. * @param listener
  1993. * @throws SecurityException if the caller doesn't hold the required permission
  1994. */
  1995. @SystemApi
  1996. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  1997. public void addOnPreferredDevicesForCapturePresetChangedListener(
  1998. @NonNull @CallbackExecutor Executor executor,
  1999. @NonNull OnPreferredDevicesForCapturePresetChangedListener listener)
  2000. throws SecurityException {
  2001. Objects.requireNonNull(executor);
  2002. Objects.requireNonNull(listener);
  2003. int status = addOnDevRoleForCapturePresetChangedListener(
  2004. executor, listener, AudioSystem.DEVICE_ROLE_PREFERRED);
  2005. if (status == AudioSystem.ERROR) {
  2006. // This must not happen
  2007. throw new RuntimeException("Unknown error happened");
  2008. }
  2009. if (status == AudioSystem.BAD_VALUE) {
  2010. throw new IllegalArgumentException(
  2011. "attempt to call addOnPreferredDevicesForCapturePresetChangedListener() "
  2012. + "on a previously registered listener");
  2013. }
  2014. }
  2015. /**
  2016. * @hide
  2017. * Removes a previously added listener of changes to the capture-preset-preferred audio device.
  2018. * @param listener
  2019. */
  2020. @SystemApi
  2021. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  2022. public void removeOnPreferredDevicesForCapturePresetChangedListener(
  2023. @NonNull OnPreferredDevicesForCapturePresetChangedListener listener) {
  2024. Objects.requireNonNull(listener);
  2025. int status = removeOnDevRoleForCapturePresetChangedListener(
  2026. listener, AudioSystem.DEVICE_ROLE_PREFERRED);
  2027. if (status == AudioSystem.ERROR) {
  2028. // This must not happen
  2029. throw new RuntimeException("Unknown error happened");
  2030. }
  2031. if (status == AudioSystem.BAD_VALUE) {
  2032. throw new IllegalArgumentException(
  2033. "attempt to call removeOnPreferredDevicesForCapturePresetChangedListener() "
  2034. + "on an unregistered listener");
  2035. }
  2036. }
  2037. private <T> int addOnDevRoleForCapturePresetChangedListener(
  2038. @NonNull @CallbackExecutor Executor executor,
  2039. @NonNull T listener, int deviceRole) {
  2040. Objects.requireNonNull(executor);
  2041. Objects.requireNonNull(listener);
  2042. DevRoleListeners<T> devRoleListeners =
  2043. (DevRoleListeners<T>) mDevRoleForCapturePresetListeners.get(deviceRole);
  2044. if (devRoleListeners == null) {
  2045. return AudioSystem.ERROR;
  2046. }
  2047. synchronized (devRoleListeners.mDevRoleListenersLock) {
  2048. if (devRoleListeners.hasDevRoleListener(listener)) {
  2049. return AudioSystem.BAD_VALUE;
  2050. }
  2051. // lazy initialization of the list of device role listener
  2052. if (devRoleListeners.mListenerInfos == null) {
  2053. devRoleListeners.mListenerInfos = new ArrayList<>();
  2054. }
  2055. final int oldCbCount = devRoleListeners.mListenerInfos.size();
  2056. devRoleListeners.mListenerInfos.add(new DevRoleListenerInfo<T>(executor, listener));
  2057. if (oldCbCount == 0 && devRoleListeners.mListenerInfos.size() > 0) {
  2058. // register binder for callbacks
  2059. synchronized (mDevRoleForCapturePresetListenersLock) {
  2060. int deviceRoleListenerStatus = mDeviceRoleListenersStatus;
  2061. mDeviceRoleListenersStatus |= (1 << deviceRole);
  2062. if (deviceRoleListenerStatus != 0) {
  2063. // There are already device role changed listeners active.
  2064. return AudioSystem.SUCCESS;
  2065. }
  2066. if (mDevicesRoleForCapturePresetDispatcherStub == null) {
  2067. mDevicesRoleForCapturePresetDispatcherStub =
  2068. new CapturePresetDevicesRoleDispatcherStub();
  2069. }
  2070. try {
  2071. getService().registerCapturePresetDevicesRoleDispatcher(
  2072. mDevicesRoleForCapturePresetDispatcherStub);
  2073. } catch (RemoteException e) {
  2074. throw e.rethrowFromSystemServer();
  2075. }
  2076. }
  2077. }
  2078. }
  2079. return AudioSystem.SUCCESS;
  2080. }
  2081. private <T> int removeOnDevRoleForCapturePresetChangedListener(
  2082. @NonNull T listener, int deviceRole) {
  2083. Objects.requireNonNull(listener);
  2084. DevRoleListeners<T> devRoleListeners =
  2085. (DevRoleListeners<T>) mDevRoleForCapturePresetListeners.get(deviceRole);
  2086. if (devRoleListeners == null) {
  2087. return AudioSystem.ERROR;
  2088. }
  2089. synchronized (devRoleListeners.mDevRoleListenersLock) {
  2090. if (!devRoleListeners.removeDevRoleListener(listener)) {
  2091. return AudioSystem.BAD_VALUE;
  2092. }
  2093. if (devRoleListeners.mListenerInfos.size() == 0) {
  2094. // unregister binder for callbacks
  2095. synchronized (mDevRoleForCapturePresetListenersLock) {
  2096. mDeviceRoleListenersStatus ^= (1 << deviceRole);
  2097. if (mDeviceRoleListenersStatus != 0) {
  2098. // There are some other device role changed listeners active.
  2099. return AudioSystem.SUCCESS;
  2100. }
  2101. try {
  2102. getService().unregisterCapturePresetDevicesRoleDispatcher(
  2103. mDevicesRoleForCapturePresetDispatcherStub);
  2104. } catch (RemoteException e) {
  2105. throw e.rethrowFromSystemServer();
  2106. }
  2107. }
  2108. }
  2109. }
  2110. return AudioSystem.SUCCESS;
  2111. }
  2112. private final Map<Integer, Object> mDevRoleForCapturePresetListeners = new HashMap<>(){{
  2113. put(AudioSystem.DEVICE_ROLE_PREFERRED,
  2114. new DevRoleListeners<OnPreferredDevicesForCapturePresetChangedListener>());
  2115. }};
  2116. private class DevRoleListenerInfo<T> {
  2117. final @NonNull Executor mExecutor;
  2118. final @NonNull T mListener;
  2119. DevRoleListenerInfo(Executor executor, T listener) {
  2120. mExecutor = executor;
  2121. mListener = listener;
  2122. }
  2123. }
  2124. private class DevRoleListeners<T> {
  2125. private final Object mDevRoleListenersLock = new Object();
  2126. @GuardedBy("mDevRoleListenersLock")
  2127. private @Nullable ArrayList<DevRoleListenerInfo<T>> mListenerInfos;
  2128. @GuardedBy("mDevRoleListenersLock")
  2129. private @Nullable DevRoleListenerInfo<T> getDevRoleListenerInfo(T listener) {
  2130. if (mListenerInfos == null) {
  2131. return null;
  2132. }
  2133. for (DevRoleListenerInfo<T> listenerInfo : mListenerInfos) {
  2134. if (listenerInfo.mListener == listener) {
  2135. return listenerInfo;
  2136. }
  2137. }
  2138. return null;
  2139. }
  2140. @GuardedBy("mDevRoleListenersLock")
  2141. private boolean hasDevRoleListener(T listener) {
  2142. return getDevRoleListenerInfo(listener) != null;
  2143. }
  2144. @GuardedBy("mDevRoleListenersLock")
  2145. private boolean removeDevRoleListener(T listener) {
  2146. final DevRoleListenerInfo<T> infoToRemove = getDevRoleListenerInfo(listener);
  2147. if (infoToRemove != null) {
  2148. mListenerInfos.remove(infoToRemove);
  2149. return true;
  2150. }
  2151. return false;
  2152. }
  2153. }
  2154. private final Object mDevRoleForCapturePresetListenersLock = new Object();
  2155. /**
  2156. * Record if there is a listener added for device role change. If there is a listener added for
  2157. * a specified device role change, the bit at position `1 << device_role` is set.
  2158. */
  2159. @GuardedBy("mDevRoleForCapturePresetListenersLock")
  2160. private int mDeviceRoleListenersStatus = 0;
  2161. @GuardedBy("mDevRoleForCapturePresetListenersLock")
  2162. private CapturePresetDevicesRoleDispatcherStub mDevicesRoleForCapturePresetDispatcherStub;
  2163. private final class CapturePresetDevicesRoleDispatcherStub
  2164. extends ICapturePresetDevicesRoleDispatcher.Stub {
  2165. @Override
  2166. public void dispatchDevicesRoleChanged(
  2167. int capturePreset, int role, List<AudioDeviceAttributes> devices) {
  2168. final Object listenersObj = mDevRoleForCapturePresetListeners.get(role);
  2169. if (listenersObj == null) {
  2170. return;
  2171. }
  2172. switch (role) {
  2173. case AudioSystem.DEVICE_ROLE_PREFERRED: {
  2174. final DevRoleListeners<OnPreferredDevicesForCapturePresetChangedListener>
  2175. listeners =
  2176. (DevRoleListeners<OnPreferredDevicesForCapturePresetChangedListener>)
  2177. listenersObj;
  2178. final ArrayList<DevRoleListenerInfo<
  2179. OnPreferredDevicesForCapturePresetChangedListener>> prefDevListeners;
  2180. synchronized (listeners.mDevRoleListenersLock) {
  2181. if (listeners.mListenerInfos.isEmpty()) {
  2182. return;
  2183. }
  2184. prefDevListeners = (ArrayList<DevRoleListenerInfo<
  2185. OnPreferredDevicesForCapturePresetChangedListener>>)
  2186. listeners.mListenerInfos.clone();
  2187. }
  2188. final long ident = Binder.clearCallingIdentity();
  2189. try {
  2190. for (DevRoleListenerInfo<
  2191. OnPreferredDevicesForCapturePresetChangedListener> info :
  2192. prefDevListeners) {
  2193. info.mExecutor.execute(() ->
  2194. info.mListener.onPreferredDevicesForCapturePresetChanged(
  2195. capturePreset, devices));
  2196. }
  2197. } finally {
  2198. Binder.restoreCallingIdentity(ident);
  2199. }
  2200. } break;
  2201. default:
  2202. break;
  2203. }
  2204. }
  2205. }
  2206. //====================================================================
  2207. // Offload query
  2208. /**
  2209. * Returns whether offloaded playback of an audio format is supported on the device.
  2210. * <p>Offloaded playback is the feature where the decoding and playback of an audio stream
  2211. * is not competing with other software resources. In general, it is supported by dedicated
  2212. * hardware, such as audio DSPs.
  2213. * <p>Note that this query only provides information about the support of an audio format,
  2214. * it does not indicate whether the resources necessary for the offloaded playback are
  2215. * available at that instant.
  2216. * @param format the audio format (codec, sample rate, channels) being checked.
  2217. * @param attributes the {@link AudioAttributes} to be used for playback
  2218. * @return true if the given audio format can be offloaded.
  2219. */
  2220. public static boolean isOffloadedPlaybackSupported(@NonNull AudioFormat format,
  2221. @NonNull AudioAttributes attributes) {
  2222. if (format == null) {
  2223. throw new NullPointerException("Illegal null AudioFormat");
  2224. }
  2225. if (attributes == null) {
  2226. throw new NullPointerException("Illegal null AudioAttributes");
  2227. }
  2228. return AudioSystem.getOffloadSupport(format, attributes) != PLAYBACK_OFFLOAD_NOT_SUPPORTED;
  2229. }
  2230. /** Return value for {@link #getPlaybackOffloadSupport(AudioFormat, AudioAttributes)}:
  2231. offload playback not supported */
  2232. public static final int PLAYBACK_OFFLOAD_NOT_SUPPORTED = AudioSystem.OFFLOAD_NOT_SUPPORTED;
  2233. /** Return value for {@link #getPlaybackOffloadSupport(AudioFormat, AudioAttributes)}:
  2234. offload playback supported */
  2235. public static final int PLAYBACK_OFFLOAD_SUPPORTED = AudioSystem.OFFLOAD_SUPPORTED;
  2236. /** Return value for {@link #getPlaybackOffloadSupport(AudioFormat, AudioAttributes)}:
  2237. offload playback supported with gapless transitions */
  2238. public static final int PLAYBACK_OFFLOAD_GAPLESS_SUPPORTED =
  2239. AudioSystem.OFFLOAD_GAPLESS_SUPPORTED;
  2240. /** @hide */
  2241. @IntDef(flag = false, prefix = "PLAYBACK_OFFLOAD_", value = {
  2242. PLAYBACK_OFFLOAD_NOT_SUPPORTED,
  2243. PLAYBACK_OFFLOAD_SUPPORTED,
  2244. PLAYBACK_OFFLOAD_GAPLESS_SUPPORTED }
  2245. )
  2246. @Retention(RetentionPolicy.SOURCE)
  2247. public @interface AudioOffloadMode {}
  2248. /**
  2249. * Returns whether offloaded playback of an audio format is supported on the device or not and
  2250. * when supported whether gapless transitions are possible or not.
  2251. * <p>Offloaded playback is the feature where the decoding and playback of an audio stream
  2252. * is not competing with other software resources. In general, it is supported by dedicated
  2253. * hardware, such as audio DSPs.
  2254. * <p>Note that this query only provides information about the support of an audio format,
  2255. * it does not indicate whether the resources necessary for the offloaded playback are
  2256. * available at that instant.
  2257. * @param format the audio format (codec, sample rate, channels) being checked.
  2258. * @param attributes the {@link AudioAttributes} to be used for playback
  2259. * @return {@link #PLAYBACK_OFFLOAD_NOT_SUPPORTED} if offload playback if not supported,
  2260. * {@link #PLAYBACK_OFFLOAD_SUPPORTED} if offload playback is supported or
  2261. * {@link #PLAYBACK_OFFLOAD_GAPLESS_SUPPORTED} if gapless transitions are
  2262. * also supported.
  2263. */
  2264. @AudioOffloadMode
  2265. public static int getPlaybackOffloadSupport(@NonNull AudioFormat format,
  2266. @NonNull AudioAttributes attributes) {
  2267. if (format == null) {
  2268. throw new NullPointerException("Illegal null AudioFormat");
  2269. }
  2270. if (attributes == null) {
  2271. throw new NullPointerException("Illegal null AudioAttributes");
  2272. }
  2273. return AudioSystem.getOffloadSupport(format, attributes);
  2274. }
  2275. //====================================================================
  2276. // Bluetooth SCO control
  2277. /**
  2278. * Sticky broadcast intent action indicating that the Bluetooth SCO audio
  2279. * connection state has changed. The intent contains on extra {@link #EXTRA_SCO_AUDIO_STATE}
  2280. * indicating the new state which is either {@link #SCO_AUDIO_STATE_DISCONNECTED}
  2281. * or {@link #SCO_AUDIO_STATE_CONNECTED}
  2282. *
  2283. * @see #startBluetoothSco()
  2284. * @deprecated Use {@link #ACTION_SCO_AUDIO_STATE_UPDATED} instead
  2285. */
  2286. @Deprecated
  2287. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  2288. public static final String ACTION_SCO_AUDIO_STATE_CHANGED =
  2289. "android.media.SCO_AUDIO_STATE_CHANGED";
  2290. /**
  2291. * Sticky broadcast intent action indicating that the Bluetooth SCO audio
  2292. * connection state has been updated.
  2293. * <p>This intent has two extras:
  2294. * <ul>
  2295. * <li> {@link #EXTRA_SCO_AUDIO_STATE} - The new SCO audio state. </li>
  2296. * <li> {@link #EXTRA_SCO_AUDIO_PREVIOUS_STATE}- The previous SCO audio state. </li>
  2297. * </ul>
  2298. * <p> EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE can be any of:
  2299. * <ul>
  2300. * <li> {@link #SCO_AUDIO_STATE_DISCONNECTED}, </li>
  2301. * <li> {@link #SCO_AUDIO_STATE_CONNECTING} or </li>
  2302. * <li> {@link #SCO_AUDIO_STATE_CONNECTED}, </li>
  2303. * </ul>
  2304. * @see #startBluetoothSco()
  2305. */
  2306. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  2307. public static final String ACTION_SCO_AUDIO_STATE_UPDATED =
  2308. "android.media.ACTION_SCO_AUDIO_STATE_UPDATED";
  2309. /**
  2310. * Extra for intent {@link #ACTION_SCO_AUDIO_STATE_CHANGED} or
  2311. * {@link #ACTION_SCO_AUDIO_STATE_UPDATED} containing the new bluetooth SCO connection state.
  2312. */
  2313. public static final String EXTRA_SCO_AUDIO_STATE =
  2314. "android.media.extra.SCO_AUDIO_STATE";
  2315. /**
  2316. * Extra for intent {@link #ACTION_SCO_AUDIO_STATE_UPDATED} containing the previous
  2317. * bluetooth SCO connection state.
  2318. */
  2319. public static final String EXTRA_SCO_AUDIO_PREVIOUS_STATE =
  2320. "android.media.extra.SCO_AUDIO_PREVIOUS_STATE";
  2321. /**
  2322. * Value for extra EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE
  2323. * indicating that the SCO audio channel is not established
  2324. */
  2325. public static final int SCO_AUDIO_STATE_DISCONNECTED = 0;
  2326. /**
  2327. * Value for extra {@link #EXTRA_SCO_AUDIO_STATE} or {@link #EXTRA_SCO_AUDIO_PREVIOUS_STATE}
  2328. * indicating that the SCO audio channel is established
  2329. */
  2330. public static final int SCO_AUDIO_STATE_CONNECTED = 1;
  2331. /**
  2332. * Value for extra EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE
  2333. * indicating that the SCO audio channel is being established
  2334. */
  2335. public static final int SCO_AUDIO_STATE_CONNECTING = 2;
  2336. /**
  2337. * Value for extra EXTRA_SCO_AUDIO_STATE indicating that
  2338. * there was an error trying to obtain the state
  2339. */
  2340. public static final int SCO_AUDIO_STATE_ERROR = -1;
  2341. /**
  2342. * Indicates if current platform supports use of SCO for off call use cases.
  2343. * Application wanted to use bluetooth SCO audio when the phone is not in call
  2344. * must first call this method to make sure that the platform supports this
  2345. * feature.
  2346. * @return true if bluetooth SCO can be used for audio when not in call
  2347. * false otherwise
  2348. * @see #startBluetoothSco()
  2349. */
  2350. public boolean isBluetoothScoAvailableOffCall() {
  2351. return getContext().getResources().getBoolean(
  2352. com.android.internal.R.bool.config_bluetooth_sco_off_call);
  2353. }
  2354. /**
  2355. * Start bluetooth SCO audio connection.
  2356. * <p>Requires Permission:
  2357. * {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
  2358. * <p>This method can be used by applications wanting to send and received audio
  2359. * to/from a bluetooth SCO headset while the phone is not in call.
  2360. * <p>As the SCO connection establishment can take several seconds,
  2361. * applications should not rely on the connection to be available when the method
  2362. * returns but instead register to receive the intent {@link #ACTION_SCO_AUDIO_STATE_UPDATED}
  2363. * and wait for the state to be {@link #SCO_AUDIO_STATE_CONNECTED}.
  2364. * <p>As the ACTION_SCO_AUDIO_STATE_UPDATED intent is sticky, the application can check the SCO
  2365. * audio state before calling startBluetoothSco() by reading the intent returned by the receiver
  2366. * registration. If the state is already CONNECTED, no state change will be received via the
  2367. * intent after calling startBluetoothSco(). It is however useful to call startBluetoothSco()
  2368. * so that the connection stays active in case the current initiator stops the connection.
  2369. * <p>Unless the connection is already active as described above, the state will always
  2370. * transition from DISCONNECTED to CONNECTING and then either to CONNECTED if the connection
  2371. * succeeds or back to DISCONNECTED if the connection fails (e.g no headset is connected).
  2372. * <p>When finished with the SCO connection or if the establishment fails, the application must
  2373. * call {@link #stopBluetoothSco()} to clear the request and turn down the bluetooth connection.
  2374. * <p>Even if a SCO connection is established, the following restrictions apply on audio
  2375. * output streams so that they can be routed to SCO headset:
  2376. * <ul>
  2377. * <li> the stream type must be {@link #STREAM_VOICE_CALL} </li>
  2378. * <li> the format must be mono </li>
  2379. * <li> the sampling must be 16kHz or 8kHz </li>
  2380. * </ul>
  2381. * <p>The following restrictions apply on input streams:
  2382. * <ul>
  2383. * <li> the format must be mono </li>
  2384. * <li> the sampling must be 8kHz </li>
  2385. * </ul>
  2386. * <p>Note that the phone application always has the priority on the usage of the SCO
  2387. * connection for telephony. If this method is called while the phone is in call
  2388. * it will be ignored. Similarly, if a call is received or sent while an application
  2389. * is using the SCO connection, the connection will be lost for the application and NOT
  2390. * returned automatically when the call ends.
  2391. * <p>NOTE: up to and including API version
  2392. * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}, this method initiates a virtual
  2393. * voice call to the bluetooth headset.
  2394. * After API version {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} only a raw SCO audio
  2395. * connection is established.
  2396. * @see #stopBluetoothSco()
  2397. * @see #ACTION_SCO_AUDIO_STATE_UPDATED
  2398. */
  2399. public void startBluetoothSco(){
  2400. final IAudioService service = getService();
  2401. try {
  2402. service.startBluetoothSco(mICallBack,
  2403. getContext().getApplicationInfo().targetSdkVersion);
  2404. } catch (RemoteException e) {
  2405. throw e.rethrowFromSystemServer();
  2406. }
  2407. }
  2408. /**
  2409. * @hide
  2410. * Start bluetooth SCO audio connection in virtual call mode.
  2411. * <p>Requires Permission:
  2412. * {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
  2413. * <p>Similar to {@link #startBluetoothSco()} with explicit selection of virtual call mode.
  2414. * Telephony and communication applications (VoIP, Video Chat) should preferably select
  2415. * virtual call mode.
  2416. * Applications using voice input for search or commands should first try raw audio connection
  2417. * with {@link #startBluetoothSco()} and fall back to startBluetoothScoVirtualCall() in case of
  2418. * failure.
  2419. * @see #startBluetoothSco()
  2420. * @see #stopBluetoothSco()
  2421. * @see #ACTION_SCO_AUDIO_STATE_UPDATED
  2422. */
  2423. @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  2424. public void startBluetoothScoVirtualCall() {
  2425. final IAudioService service = getService();
  2426. try {
  2427. service.startBluetoothScoVirtualCall(mICallBack);
  2428. } catch (RemoteException e) {
  2429. throw e.rethrowFromSystemServer();
  2430. }
  2431. }
  2432. /**
  2433. * Stop bluetooth SCO audio connection.
  2434. * <p>Requires Permission:
  2435. * {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
  2436. * <p>This method must be called by applications having requested the use of
  2437. * bluetooth SCO audio with {@link #startBluetoothSco()} when finished with the SCO
  2438. * connection or if connection fails.
  2439. * @see #startBluetoothSco()
  2440. */
  2441. // Also used for connections started with {@link #startBluetoothScoVirtualCall()}
  2442. public void stopBluetoothSco(){
  2443. final IAudioService service = getService();
  2444. try {
  2445. service.stopBluetoothSco(mICallBack);
  2446. } catch (RemoteException e) {
  2447. throw e.rethrowFromSystemServer();
  2448. }
  2449. }
  2450. /**
  2451. * Request use of Bluetooth SCO headset for communications.
  2452. * <p>
  2453. * This method should only be used by applications that replace the platform-wide
  2454. * management of audio settings or the main telephony application.
  2455. *
  2456. * @param on set <var>true</var> to use bluetooth SCO for communications;
  2457. * <var>false</var> to not use bluetooth SCO for communications
  2458. */
  2459. public void setBluetoothScoOn(boolean on){
  2460. final IAudioService service = getService();
  2461. try {
  2462. service.setBluetoothScoOn(on);
  2463. } catch (RemoteException e) {
  2464. throw e.rethrowFromSystemServer();
  2465. }
  2466. }
  2467. /**
  2468. * Checks whether communications use Bluetooth SCO.
  2469. *
  2470. * @return true if SCO is used for communications;
  2471. * false if otherwise
  2472. */
  2473. public boolean isBluetoothScoOn() {
  2474. final IAudioService service = getService();
  2475. try {
  2476. return service.isBluetoothScoOn();
  2477. } catch (RemoteException e) {
  2478. throw e.rethrowFromSystemServer();
  2479. }
  2480. }
  2481. /**
  2482. * @param on set <var>true</var> to route A2DP audio to/from Bluetooth
  2483. * headset; <var>false</var> disable A2DP audio
  2484. * @deprecated Do not use.
  2485. */
  2486. @Deprecated public void setBluetoothA2dpOn(boolean on){
  2487. }
  2488. /**
  2489. * Checks whether a Bluetooth A2DP audio peripheral is connected or not.
  2490. *
  2491. * @return true if a Bluetooth A2DP peripheral is connected
  2492. * false if otherwise
  2493. * @deprecated Use {@link AudioManager#getDevices(int)} instead to list available audio devices.
  2494. */
  2495. public boolean isBluetoothA2dpOn() {
  2496. if (AudioSystem.getDeviceConnectionState(DEVICE_OUT_BLUETOOTH_A2DP,"")
  2497. == AudioSystem.DEVICE_STATE_AVAILABLE) {
  2498. return true;
  2499. } else if (AudioSystem.getDeviceConnectionState(DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"")
  2500. == AudioSystem.DEVICE_STATE_AVAILABLE) {
  2501. return true;
  2502. } else if (AudioSystem.getDeviceConnectionState(DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER,"")
  2503. == AudioSystem.DEVICE_STATE_AVAILABLE) {
  2504. return true;
  2505. }
  2506. return false;
  2507. }
  2508. /**
  2509. * Sets audio routing to the wired headset on or off.
  2510. *
  2511. * @param on set <var>true</var> to route audio to/from wired
  2512. * headset; <var>false</var> disable wired headset audio
  2513. * @deprecated Do not use.
  2514. */
  2515. @Deprecated public void setWiredHeadsetOn(boolean on){
  2516. }
  2517. /**
  2518. * Checks whether a wired headset is connected or not.
  2519. * <p>This is not a valid indication that audio playback is
  2520. * actually over the wired headset as audio routing depends on other conditions.
  2521. *
  2522. * @return true if a wired headset is connected.
  2523. * false if otherwise
  2524. * @deprecated Use {@link AudioManager#getDevices(int)} instead to list available audio devices.
  2525. */
  2526. public boolean isWiredHeadsetOn() {
  2527. if (AudioSystem.getDeviceConnectionState(DEVICE_OUT_WIRED_HEADSET,"")
  2528. == AudioSystem.DEVICE_STATE_UNAVAILABLE &&
  2529. AudioSystem.getDeviceConnectionState(DEVICE_OUT_WIRED_HEADPHONE,"")
  2530. == AudioSystem.DEVICE_STATE_UNAVAILABLE &&
  2531. AudioSystem.getDeviceConnectionState(DEVICE_OUT_USB_HEADSET, "")
  2532. == AudioSystem.DEVICE_STATE_UNAVAILABLE) {
  2533. return false;
  2534. } else {
  2535. return true;
  2536. }
  2537. }
  2538. /**
  2539. * Sets the microphone mute on or off.
  2540. * <p>
  2541. * This method should only be used by applications that replace the platform-wide
  2542. * management of audio settings or the main telephony application.
  2543. *
  2544. * @param on set <var>true</var> to mute the microphone;
  2545. * <var>false</var> to turn mute off
  2546. */
  2547. public void setMicrophoneMute(boolean on) {
  2548. final IAudioService service = getService();
  2549. try {
  2550. service.setMicrophoneMute(on, getContext().getOpPackageName(),
  2551. UserHandle.getCallingUserId());
  2552. } catch (RemoteException e) {
  2553. throw e.rethrowFromSystemServer();
  2554. }
  2555. }
  2556. /**
  2557. * @hide
  2558. * Sets the microphone from switch mute on or off.
  2559. * <p>
  2560. * This method should only be used by InputManager to notify
  2561. * Audio Subsystem about Microphone Mute switch state.
  2562. *
  2563. * @param on set <var>true</var> to mute the microphone;
  2564. * <var>false</var> to turn mute off
  2565. */
  2566. @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  2567. public void setMicrophoneMuteFromSwitch(boolean on) {
  2568. final IAudioService service = getService();
  2569. try {
  2570. service.setMicrophoneMuteFromSwitch(on);
  2571. } catch (RemoteException e) {
  2572. throw e.rethrowFromSystemServer();
  2573. }
  2574. }
  2575. /**
  2576. * Checks whether the microphone mute is on or off.
  2577. *
  2578. * @return true if microphone is muted, false if it's not
  2579. */
  2580. public boolean isMicrophoneMute() {
  2581. final IAudioService service = getService();
  2582. try {
  2583. return service.isMicrophoneMuted();
  2584. } catch (RemoteException e) {
  2585. throw e.rethrowFromSystemServer();
  2586. }
  2587. }
  2588. /**
  2589. * Broadcast Action: microphone muting state changed.
  2590. *
  2591. * You <em>cannot</em> receive this through components declared
  2592. * in manifests, only by explicitly registering for it with
  2593. * {@link Context#registerReceiver(BroadcastReceiver, IntentFilter)
  2594. * Context.registerReceiver()}.
  2595. *
  2596. * <p>The intent has no extra values, use {@link #isMicrophoneMute} to check whether the
  2597. * microphone is muted.
  2598. */
  2599. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  2600. public static final String ACTION_MICROPHONE_MUTE_CHANGED =
  2601. "android.media.action.MICROPHONE_MUTE_CHANGED";
  2602. /**
  2603. * Broadcast Action: speakerphone state changed.
  2604. *
  2605. * You <em>cannot</em> receive this through components declared
  2606. * in manifests, only by explicitly registering for it with
  2607. * {@link Context#registerReceiver(BroadcastReceiver, IntentFilter)
  2608. * Context.registerReceiver()}.
  2609. *
  2610. * <p>The intent has no extra values, use {@link #isSpeakerphoneOn} to check whether the
  2611. * speakerphone functionality is enabled or not.
  2612. */
  2613. @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
  2614. public static final String ACTION_SPEAKERPHONE_STATE_CHANGED =
  2615. "android.media.action.SPEAKERPHONE_STATE_CHANGED";
  2616. /**
  2617. * Sets the audio mode.
  2618. * <p>
  2619. * The audio mode encompasses audio routing AND the behavior of
  2620. * the telephony layer. Therefore this method should only be used by applications that
  2621. * replace the platform-wide management of audio settings or the main telephony application.
  2622. * In particular, the {@link #MODE_IN_CALL} mode should only be used by the telephony
  2623. * application when it places a phone call, as it will cause signals from the radio layer
  2624. * to feed the platform mixer.
  2625. *
  2626. * @param mode the requested audio mode.
  2627. * Informs the HAL about the current audio state so that
  2628. * it can route the audio appropriately.
  2629. */
  2630. public void setMode(@AudioMode int mode) {
  2631. final IAudioService service = getService();
  2632. try {
  2633. service.setMode(mode, mICallBack, mApplicationContext.getOpPackageName());
  2634. } catch (RemoteException e) {
  2635. throw e.rethrowFromSystemServer();
  2636. }
  2637. }
  2638. /**
  2639. * Returns the current audio mode.
  2640. *
  2641. * @return the current audio mode.
  2642. */
  2643. @AudioMode
  2644. public int getMode() {
  2645. final IAudioService service = getService();
  2646. try {
  2647. int mode = service.getMode();
  2648. int sdk;
  2649. try {
  2650. sdk = getContext().getApplicationInfo().targetSdkVersion;
  2651. } catch (NullPointerException e) {
  2652. // some tests don't have a Context
  2653. sdk = Build.VERSION.SDK_INT;
  2654. }
  2655. if (mode == MODE_CALL_SCREENING && sdk <= Build.VERSION_CODES.Q) {
  2656. mode = MODE_IN_CALL;
  2657. }
  2658. return mode;
  2659. } catch (RemoteException e) {
  2660. throw e.rethrowFromSystemServer();
  2661. }
  2662. }
  2663. /**
  2664. * Interface definition of a callback that is notified when the audio mode changes
  2665. */
  2666. public interface OnModeChangedListener {
  2667. /**
  2668. * Called on the listener to indicate that the audio mode has changed
  2669. *
  2670. * @param mode The current audio mode
  2671. */
  2672. void onModeChanged(@AudioMode int mode);
  2673. }
  2674. private final Object mModeListenerLock = new Object();
  2675. /**
  2676. * List of listeners for audio mode and their associated Executor.
  2677. * List is lazy-initialized on first registration
  2678. */
  2679. @GuardedBy("mModeListenerLock")
  2680. private @Nullable ArrayList<ModeListenerInfo> mModeListeners;
  2681. @GuardedBy("mModeListenerLock")
  2682. private ModeDispatcherStub mModeDispatcherStub;
  2683. private final class ModeDispatcherStub
  2684. extends IAudioModeDispatcher.Stub {
  2685. @Override
  2686. public void dispatchAudioModeChanged(int mode) {
  2687. // make a shallow copy of listeners so callback is not executed under lock
  2688. final ArrayList<ModeListenerInfo> modeListeners;
  2689. synchronized (mModeListenerLock) {
  2690. if (mModeListeners == null || mModeListeners.size() == 0) {
  2691. return;
  2692. }
  2693. modeListeners = (ArrayList<ModeListenerInfo>) mModeListeners.clone();
  2694. }
  2695. final long ident = Binder.clearCallingIdentity();
  2696. try {
  2697. for (ModeListenerInfo info : modeListeners) {
  2698. info.mExecutor.execute(() ->
  2699. info.mListener.onModeChanged(mode));
  2700. }
  2701. } finally {
  2702. Binder.restoreCallingIdentity(ident);
  2703. }
  2704. }
  2705. }
  2706. private static class ModeListenerInfo {
  2707. final @NonNull OnModeChangedListener mListener;
  2708. final @NonNull Executor mExecutor;
  2709. ModeListenerInfo(OnModeChangedListener listener, Executor exe) {
  2710. mListener = listener;
  2711. mExecutor = exe;
  2712. }
  2713. }
  2714. @GuardedBy("mModeListenerLock")
  2715. private boolean hasModeListener(OnModeChangedListener listener) {
  2716. return getModeListenerInfo(listener) != null;
  2717. }
  2718. @GuardedBy("mModeListenerLock")
  2719. private @Nullable ModeListenerInfo getModeListenerInfo(
  2720. OnModeChangedListener listener) {
  2721. if (mModeListeners == null) {
  2722. return null;
  2723. }
  2724. for (ModeListenerInfo info : mModeListeners) {
  2725. if (info.mListener == listener) {
  2726. return info;
  2727. }
  2728. }
  2729. return null;
  2730. }
  2731. @GuardedBy("mModeListenerLock")
  2732. /**
  2733. * @return true if the listener was removed from the list
  2734. */
  2735. private boolean removeModeListener(OnModeChangedListener listener) {
  2736. final ModeListenerInfo infoToRemove = getModeListenerInfo(listener);
  2737. if (infoToRemove != null) {
  2738. mModeListeners.remove(infoToRemove);
  2739. return true;
  2740. }
  2741. return false;
  2742. }
  2743. /**
  2744. * Adds a listener to be notified of changes to the audio mode.
  2745. * See {@link #getMode()}
  2746. * @param executor
  2747. * @param listener
  2748. */
  2749. public void addOnModeChangedListener(
  2750. @NonNull @CallbackExecutor Executor executor,
  2751. @NonNull OnModeChangedListener listener) {
  2752. Objects.requireNonNull(executor);
  2753. Objects.requireNonNull(listener);
  2754. synchronized (mModeListenerLock) {
  2755. if (hasModeListener(listener)) {
  2756. throw new IllegalArgumentException("attempt to call addOnModeChangedListener() "
  2757. + "on a previously registered listener");
  2758. }
  2759. // lazy initialization of the list of strategy-preferred device listener
  2760. if (mModeListeners == null) {
  2761. mModeListeners = new ArrayList<>();
  2762. }
  2763. final int oldCbCount = mModeListeners.size();
  2764. mModeListeners.add(new ModeListenerInfo(listener, executor));
  2765. if (oldCbCount == 0) {
  2766. // register binder for callbacks
  2767. if (mModeDispatcherStub == null) {
  2768. mModeDispatcherStub = new ModeDispatcherStub();
  2769. }
  2770. try {
  2771. getService().registerModeDispatcher(mModeDispatcherStub);
  2772. } catch (RemoteException e) {
  2773. throw e.rethrowFromSystemServer();
  2774. }
  2775. }
  2776. }
  2777. }
  2778. /**
  2779. * Removes a previously added listener for changes to audio mode.
  2780. * See {@link #getMode()}
  2781. * @param listener
  2782. */
  2783. public void removeOnModeChangedListener(@NonNull OnModeChangedListener listener) {
  2784. Objects.requireNonNull(listener);
  2785. synchronized (mModeListenerLock) {
  2786. if (!removeModeListener(listener)) {
  2787. throw new IllegalArgumentException("attempt to call removeOnModeChangedListener() "
  2788. + "on an unregistered listener");
  2789. }
  2790. if (mModeListeners.size() == 0) {
  2791. // unregister binder for callbacks
  2792. try {
  2793. getService().unregisterModeDispatcher(mModeDispatcherStub);
  2794. } catch (RemoteException e) {
  2795. throw e.rethrowFromSystemServer();
  2796. } finally {
  2797. mModeDispatcherStub = null;
  2798. mModeListeners = null;
  2799. }
  2800. }
  2801. }
  2802. }
  2803. /**
  2804. * Indicates if the platform supports a special call screening and call monitoring mode.
  2805. * <p>
  2806. * When this mode is supported, it is possible to perform call screening and monitoring
  2807. * functions while other use cases like music or movie playback are active.
  2808. * <p>
  2809. * Use {@link #setMode(int)} with mode {@link #MODE_CALL_SCREENING} to place the platform in
  2810. * call screening mode.
  2811. * <p>
  2812. * If call screening mode is not supported, setting mode to
  2813. * MODE_CALL_SCREENING will be ignored and will not change current mode reported by
  2814. * {@link #getMode()}.
  2815. * @return true if call screening mode is supported, false otherwise.
  2816. */
  2817. public boolean isCallScreeningModeSupported() {
  2818. final IAudioService service = getService();
  2819. try {
  2820. return service.isCallScreeningModeSupported();
  2821. } catch (RemoteException e) {
  2822. throw e.rethrowFromSystemServer();
  2823. }
  2824. }
  2825. /* modes for setMode/getMode/setRoute/getRoute */
  2826. /**
  2827. * Audio harware modes.
  2828. */
  2829. /**
  2830. * Invalid audio mode.
  2831. */
  2832. public static final int MODE_INVALID = AudioSystem.MODE_INVALID;
  2833. /**
  2834. * Current audio mode. Used to apply audio routing to current mode.
  2835. */
  2836. public static final int MODE_CURRENT = AudioSystem.MODE_CURRENT;
  2837. /**
  2838. * Normal audio mode: not ringing and no call established.
  2839. */
  2840. public static final int MODE_NORMAL = AudioSystem.MODE_NORMAL;
  2841. /**
  2842. * Ringing audio mode. An incoming is being signaled.
  2843. */
  2844. public static final int MODE_RINGTONE = AudioSystem.MODE_RINGTONE;
  2845. /**
  2846. * In call audio mode. A telephony call is established.
  2847. */
  2848. public static final int MODE_IN_CALL = AudioSystem.MODE_IN_CALL;
  2849. /**
  2850. * In communication audio mode. An audio/video chat or VoIP call is established.
  2851. */
  2852. public static final int MODE_IN_COMMUNICATION = AudioSystem.MODE_IN_COMMUNICATION;
  2853. /**
  2854. * Call screening in progress. Call is connected and audio is accessible to call
  2855. * screening applications but other audio use cases are still possible.
  2856. */
  2857. public static final int MODE_CALL_SCREENING = AudioSystem.MODE_CALL_SCREENING;
  2858. /** @hide */
  2859. @IntDef(flag = false, prefix = "MODE_", value = {
  2860. MODE_NORMAL,
  2861. MODE_RINGTONE,
  2862. MODE_IN_CALL,
  2863. MODE_IN_COMMUNICATION,
  2864. MODE_CALL_SCREENING }
  2865. )
  2866. @Retention(RetentionPolicy.SOURCE)
  2867. public @interface AudioMode {}
  2868. /* Routing bits for setRouting/getRouting API */
  2869. /**
  2870. * Routing audio output to earpiece
  2871. * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
  2872. * setBluetoothScoOn() methods instead.
  2873. */
  2874. @Deprecated public static final int ROUTE_EARPIECE = AudioSystem.ROUTE_EARPIECE;
  2875. /**
  2876. * Routing audio output to speaker
  2877. * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
  2878. * setBluetoothScoOn() methods instead.
  2879. */
  2880. @Deprecated public static final int ROUTE_SPEAKER = AudioSystem.ROUTE_SPEAKER;
  2881. /**
  2882. * @deprecated use {@link #ROUTE_BLUETOOTH_SCO}
  2883. * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
  2884. * setBluetoothScoOn() methods instead.
  2885. */
  2886. @Deprecated public static final int ROUTE_BLUETOOTH = AudioSystem.ROUTE_BLUETOOTH_SCO;
  2887. /**
  2888. * Routing audio output to bluetooth SCO
  2889. * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
  2890. * setBluetoothScoOn() methods instead.
  2891. */
  2892. @Deprecated public static final int ROUTE_BLUETOOTH_SCO = AudioSystem.ROUTE_BLUETOOTH_SCO;
  2893. /**
  2894. * Routing audio output to headset
  2895. * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
  2896. * setBluetoothScoOn() methods instead.
  2897. */
  2898. @Deprecated public static final int ROUTE_HEADSET = AudioSystem.ROUTE_HEADSET;
  2899. /**
  2900. * Routing audio output to bluetooth A2DP
  2901. * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
  2902. * setBluetoothScoOn() methods instead.
  2903. */
  2904. @Deprecated public static final int ROUTE_BLUETOOTH_A2DP = AudioSystem.ROUTE_BLUETOOTH_A2DP;
  2905. /**
  2906. * Used for mask parameter of {@link #setRouting(int,int,int)}.
  2907. * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
  2908. * setBluetoothScoOn() methods instead.
  2909. */
  2910. @Deprecated public static final int ROUTE_ALL = AudioSystem.ROUTE_ALL;
  2911. /**
  2912. * Sets the audio routing for a specified mode
  2913. *
  2914. * @param mode audio mode to change route. E.g., MODE_RINGTONE.
  2915. * @param routes bit vector of routes requested, created from one or
  2916. * more of ROUTE_xxx types. Set bits indicate that route should be on
  2917. * @param mask bit vector of routes to change, created from one or more of
  2918. * ROUTE_xxx types. Unset bits indicate the route should be left unchanged
  2919. *
  2920. * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
  2921. * setBluetoothScoOn() methods instead.
  2922. */
  2923. @Deprecated
  2924. public void setRouting(int mode, int routes, int mask) {
  2925. }
  2926. /**
  2927. * Returns the current audio routing bit vector for a specified mode.
  2928. *
  2929. * @param mode audio mode to get route (e.g., MODE_RINGTONE)
  2930. * @return an audio route bit vector that can be compared with ROUTE_xxx
  2931. * bits
  2932. * @deprecated Do not query audio routing directly, use isSpeakerphoneOn(),
  2933. * isBluetoothScoOn(), isBluetoothA2dpOn() and isWiredHeadsetOn() methods instead.
  2934. */
  2935. @Deprecated
  2936. public int getRouting(int mode) {
  2937. return -1;
  2938. }
  2939. /**
  2940. * Checks whether any music is active.
  2941. *
  2942. * @return true if any music tracks are active.
  2943. */
  2944. public boolean isMusicActive() {
  2945. final IAudioService service = getService();
  2946. try {
  2947. return service.isMusicActive(false /*remotely*/);
  2948. } catch (RemoteException e) {
  2949. throw e.rethrowFromSystemServer();
  2950. }
  2951. }
  2952. /**
  2953. * @hide
  2954. * Checks whether any music or media is actively playing on a remote device (e.g. wireless
  2955. * display). Note that BT audio sinks are not considered remote devices.
  2956. * @return true if {@link AudioManager#STREAM_MUSIC} is active on a remote device
  2957. */
  2958. @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  2959. public boolean isMusicActiveRemotely() {
  2960. final IAudioService service = getService();
  2961. try {
  2962. return service.isMusicActive(true /*remotely*/);
  2963. } catch (RemoteException e) {
  2964. throw e.rethrowFromSystemServer();
  2965. }
  2966. }
  2967. /**
  2968. * @hide
  2969. * Checks whether the current audio focus is exclusive.
  2970. * @return true if the top of the audio focus stack requested focus
  2971. * with {@link #AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE}
  2972. */
  2973. public boolean isAudioFocusExclusive() {
  2974. final IAudioService service = getService();
  2975. try {
  2976. return service.getCurrentAudioFocus() == AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE;
  2977. } catch (RemoteException e) {
  2978. throw e.rethrowFromSystemServer();
  2979. }
  2980. }
  2981. /**
  2982. * Return a new audio session identifier not associated with any player or effect.
  2983. * An audio session identifier is a system wide unique identifier for a set of audio streams
  2984. * (one or more mixed together).
  2985. * <p>The primary use of the audio session ID is to associate audio effects to audio players,
  2986. * such as {@link MediaPlayer} or {@link AudioTrack}: all audio effects sharing the same audio
  2987. * session ID will be applied to the mixed audio content of the players that share the same
  2988. * audio session.
  2989. * <p>This method can for instance be used when creating one of the
  2990. * {@link android.media.audiofx.AudioEffect} objects to define the audio session of the effect,
  2991. * or to specify a session for a speech synthesis utterance
  2992. * in {@link android.speech.tts.TextToSpeech.Engine}.
  2993. * @return a new unclaimed and unused audio session identifier, or {@link #ERROR} when the
  2994. * system failed to generate a new session, a condition in which audio playback or recording
  2995. * will subsequently fail as well.
  2996. */
  2997. public int generateAudioSessionId() {
  2998. int session = AudioSystem.newAudioSessionId();
  2999. if (session > 0) {
  3000. return session;
  3001. } else {
  3002. Log.e(TAG, "Failure to generate a new audio session ID");
  3003. return ERROR;
  3004. }
  3005. }
  3006. /**
  3007. * A special audio session ID to indicate that the audio session ID isn't known and the
  3008. * framework should generate a new value. This can be used when building a new
  3009. * {@link AudioTrack} instance with
  3010. * {@link AudioTrack#AudioTrack(AudioAttributes, AudioFormat, int, int, int)}.
  3011. */
  3012. public static final int AUDIO_SESSION_ID_GENERATE = AudioSystem.AUDIO_SESSION_ALLOCATE;
  3013. /*
  3014. * Sets a generic audio configuration parameter. The use of these parameters
  3015. * are platform dependant, see libaudio
  3016. *
  3017. * ** Temporary interface - DO NOT USE
  3018. *
  3019. * TODO: Replace with a more generic key:value get/set mechanism
  3020. *
  3021. * param key name of parameter to set. Must not be null.
  3022. * param value value of parameter. Must not be null.
  3023. */
  3024. /**
  3025. * @hide
  3026. * @deprecated Use {@link #setParameters(String)} instead
  3027. */
  3028. @Deprecated public void setParameter(String key, String value) {
  3029. setParameters(key+"="+value);
  3030. }
  3031. /**
  3032. * Sets a variable number of parameter values to audio hardware.
  3033. *
  3034. * @param keyValuePairs list of parameters key value pairs in the form:
  3035. * key1=value1;key2=value2;...
  3036. *
  3037. */
  3038. public void setParameters(String keyValuePairs) {
  3039. AudioSystem.setParameters(keyValuePairs);
  3040. }
  3041. /**
  3042. * @hide
  3043. */
  3044. @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
  3045. @RequiresPermission(android.Manifest.permission.BLUETOOTH_STACK)
  3046. public void setHfpEnabled(boolean enable) {
  3047. AudioSystem.setParameters("hfp_enable=" + enable);
  3048. }
  3049. /**
  3050. * @hide
  3051. */
  3052. @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
  3053. @RequiresPermission(android.Manifest.permission.BLUETOOTH_STACK)
  3054. public void setHfpVolume(int volume) {
  3055. AudioSystem.setParameters("hfp_volume=" + volume);
  3056. }
  3057. /**
  3058. * @hide
  3059. */
  3060. @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
  3061. @RequiresPermission(android.Manifest.permission.BLUETOOTH_STACK)
  3062. public void setHfpSamplingRate(int rate) {
  3063. AudioSystem.setParameters("hfp_set_sampling_rate=" + rate);
  3064. }
  3065. /**
  3066. * @hide
  3067. */
  3068. @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
  3069. @RequiresPermission(android.Manifest.permission.BLUETOOTH_STACK)
  3070. public void setBluetoothHeadsetProperties(@NonNull String name, boolean hasNrecEnabled,
  3071. boolean hasWbsEnabled) {
  3072. AudioSystem.setParameters("bt_headset_name=" + name
  3073. + ";bt_headset_nrec=" + (hasNrecEnabled ? "on" : "off")
  3074. + ";bt_wbs=" + (hasWbsEnabled ? "on" : "off"));
  3075. }
  3076. /**
  3077. * @hide
  3078. */
  3079. @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
  3080. @RequiresPermission(android.Manifest.permission.BLUETOOTH_STACK)
  3081. public void setA2dpSuspended(boolean enable) {
  3082. AudioSystem.setParameters("A2dpSuspended=" + enable);
  3083. }
  3084. /**
  3085. * Gets a variable number of parameter values from audio hardware.
  3086. *
  3087. * @param keys list of parameters
  3088. * @return list of parameters key value pairs in the form:
  3089. * key1=value1;key2=value2;...
  3090. */
  3091. public String getParameters(String keys) {
  3092. return AudioSystem.getParameters(keys);
  3093. }
  3094. /* Sound effect identifiers */
  3095. /**
  3096. * Keyboard and direction pad click sound
  3097. * @see #playSoundEffect(int)
  3098. */
  3099. public static final int FX_KEY_CLICK = 0;
  3100. /**
  3101. * Focus has moved up
  3102. * @see #playSoundEffect(int)
  3103. */
  3104. public static final int FX_FOCUS_NAVIGATION_UP = 1;
  3105. /**
  3106. * Focus has moved down
  3107. * @see #playSoundEffect(int)
  3108. */
  3109. public static final int FX_FOCUS_NAVIGATION_DOWN = 2;
  3110. /**
  3111. * Focus has moved left
  3112. * @see #playSoundEffect(int)
  3113. */
  3114. public static final int FX_FOCUS_NAVIGATION_LEFT = 3;
  3115. /**
  3116. * Focus has moved right
  3117. * @see #playSoundEffect(int)
  3118. */
  3119. public static final int FX_FOCUS_NAVIGATION_RIGHT = 4;
  3120. /**
  3121. * IME standard keypress sound
  3122. * @see #playSoundEffect(int)
  3123. */
  3124. public static final int FX_KEYPRESS_STANDARD = 5;
  3125. /**
  3126. * IME spacebar keypress sound
  3127. * @see #playSoundEffect(int)
  3128. */
  3129. public static final int FX_KEYPRESS_SPACEBAR = 6;
  3130. /**
  3131. * IME delete keypress sound
  3132. * @see #playSoundEffect(int)
  3133. */
  3134. public static final int FX_KEYPRESS_DELETE = 7;
  3135. /**
  3136. * IME return_keypress sound
  3137. * @see #playSoundEffect(int)
  3138. */
  3139. public static final int FX_KEYPRESS_RETURN = 8;
  3140. /**
  3141. * Invalid keypress sound
  3142. * @see #playSoundEffect(int)
  3143. */
  3144. public static final int FX_KEYPRESS_INVALID = 9;
  3145. /**
  3146. * Back sound
  3147. * @see #playSoundEffect(int)
  3148. */
  3149. public static final int FX_BACK = 10;
  3150. /**
  3151. * @hide Home sound
  3152. * <p>
  3153. * To be played by the framework when the home app becomes active if config_enableHomeSound is
  3154. * set to true. This is currently only used on TV devices.
  3155. * Note that this sound is only available if a sound file is specified in audio_assets.xml.
  3156. * @see #playSoundEffect(int)
  3157. */
  3158. public static final int FX_HOME = 11;
  3159. /**
  3160. * @hide Navigation repeat sound 1
  3161. * <p>
  3162. * To be played by the framework when a focus navigation is repeatedly triggered
  3163. * (e.g. due to long-pressing) and {@link #areNavigationRepeatSoundEffectsEnabled()} is true.
  3164. * This is currently only used on TV devices.
  3165. * Note that this sound is only available if a sound file is specified in audio_assets.xml
  3166. * @see #playSoundEffect(int)
  3167. */
  3168. public static final int FX_FOCUS_NAVIGATION_REPEAT_1 = 12;
  3169. /**
  3170. * @hide Navigation repeat sound 2
  3171. * <p>
  3172. * To be played by the framework when a focus navigation is repeatedly triggered
  3173. * (e.g. due to long-pressing) and {@link #areNavigationRepeatSoundEffectsEnabled()} is true.
  3174. * This is currently only used on TV devices.
  3175. * Note that this sound is only available if a sound file is specified in audio_assets.xml
  3176. * @see #playSoundEffect(int)
  3177. */
  3178. public static final int FX_FOCUS_NAVIGATION_REPEAT_2 = 13;
  3179. /**
  3180. * @hide Navigation repeat sound 3
  3181. * <p>
  3182. * To be played by the framework when a focus navigation is repeatedly triggered
  3183. * (e.g. due to long-pressing) and {@link #areNavigationRepeatSoundEffectsEnabled()} is true.
  3184. * This is currently only used on TV devices.
  3185. * Note that this sound is only available if a sound file is specified in audio_assets.xml
  3186. * @see #playSoundEffect(int)
  3187. */
  3188. public static final int FX_FOCUS_NAVIGATION_REPEAT_3 = 14;
  3189. /**
  3190. * @hide Navigation repeat sound 4
  3191. * <p>
  3192. * To be played by the framework when a focus navigation is repeatedly triggered
  3193. * (e.g. due to long-pressing) and {@link #areNavigationRepeatSoundEffectsEnabled()} is true.
  3194. * This is currently only used on TV devices.
  3195. * Note that this sound is only available if a sound file is specified in audio_assets.xml
  3196. * @see #playSoundEffect(int)
  3197. */
  3198. public static final int FX_FOCUS_NAVIGATION_REPEAT_4 = 15;
  3199. /**
  3200. * @hide Number of sound effects
  3201. */
  3202. @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  3203. public static final int NUM_SOUND_EFFECTS = 16;
  3204. /** @hide */
  3205. @IntDef(prefix = { "FX_" }, value = {
  3206. FX_KEY_CLICK,
  3207. FX_FOCUS_NAVIGATION_UP,
  3208. FX_FOCUS_NAVIGATION_DOWN,
  3209. FX_FOCUS_NAVIGATION_LEFT,
  3210. FX_FOCUS_NAVIGATION_RIGHT,
  3211. FX_KEYPRESS_STANDARD,
  3212. FX_KEYPRESS_SPACEBAR,
  3213. FX_KEYPRESS_DELETE,
  3214. FX_KEYPRESS_RETURN,
  3215. FX_KEYPRESS_INVALID,
  3216. FX_BACK
  3217. })
  3218. @Retention(RetentionPolicy.SOURCE)
  3219. public @interface SystemSoundEffect {}
  3220. /**
  3221. * @hide Number of FX_FOCUS_NAVIGATION_REPEAT_* sound effects
  3222. */
  3223. public static final int NUM_NAVIGATION_REPEAT_SOUND_EFFECTS = 4;
  3224. /**
  3225. * @hide
  3226. * @param n a value in [0, {@link #NUM_NAVIGATION_REPEAT_SOUND_EFFECTS}[
  3227. * @return The id of a navigation repeat sound effect or -1 if out of bounds
  3228. */
  3229. public static int getNthNavigationRepeatSoundEffect(int n) {
  3230. switch (n) {
  3231. case 0:
  3232. return FX_FOCUS_NAVIGATION_REPEAT_1;
  3233. case 1:
  3234. return FX_FOCUS_NAVIGATION_REPEAT_2;
  3235. case 2:
  3236. return FX_FOCUS_NAVIGATION_REPEAT_3;
  3237. case 3:
  3238. return FX_FOCUS_NAVIGATION_REPEAT_4;
  3239. default:
  3240. Log.w(TAG, "Invalid navigation repeat sound effect id: " + n);
  3241. return -1;
  3242. }
  3243. }
  3244. /**
  3245. * @hide
  3246. */
  3247. public void setNavigationRepeatSoundEffectsEnabled(boolean enabled) {
  3248. try {
  3249. getService().setNavigationRepeatSoundEffectsEnabled(enabled);
  3250. } catch (RemoteException e) {
  3251. }
  3252. }
  3253. /**
  3254. * @hide
  3255. * @return true if the navigation repeat sound effects are enabled
  3256. */
  3257. public boolean areNavigationRepeatSoundEffectsEnabled() {
  3258. try {
  3259. return getService().areNavigationRepeatSoundEffectsEnabled();
  3260. } catch (RemoteException e) {
  3261. throw e.rethrowFromSystemServer();
  3262. }
  3263. }
  3264. /**
  3265. * @hide
  3266. * @param enabled
  3267. */
  3268. public void setHomeSoundEffectEnabled(boolean enabled) {
  3269. try {
  3270. getService().setHomeSoundEffectEnabled(enabled);
  3271. } catch (RemoteException e) {
  3272. }
  3273. }
  3274. /**
  3275. * @hide
  3276. * @return true if the home sound effect is enabled
  3277. */
  3278. public boolean isHomeSoundEffectEnabled() {
  3279. try {
  3280. return getService().isHomeSoundEffectEnabled();
  3281. } catch (RemoteException e) {
  3282. throw e.rethrowFromSystemServer();
  3283. }
  3284. }
  3285. /**
  3286. * Plays a sound effect (Key clicks, lid open/close...)
  3287. * @param effectType The type of sound effect.
  3288. * NOTE: This version uses the UI settings to determine
  3289. * whether sounds are heard or not.
  3290. */
  3291. public void playSoundEffect(@SystemSoundEffect int effectType) {
  3292. if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
  3293. return;
  3294. }
  3295. if (!querySoundEffectsEnabled(Process.myUserHandle().getIdentifier())) {
  3296. return;
  3297. }
  3298. final IAudioService service = getService();
  3299. try {
  3300. service.playSoundEffect(effectType);
  3301. } catch (RemoteException e) {
  3302. throw e.rethrowFromSystemServer();
  3303. }
  3304. }
  3305. /**
  3306. * Plays a sound effect (Key clicks, lid open/close...)
  3307. * @param effectType The type of sound effect.
  3308. * @param userId The current user to pull sound settings from
  3309. * NOTE: This version uses the UI settings to determine
  3310. * whether sounds are heard or not.
  3311. * @hide
  3312. */
  3313. public void playSoundEffect(@SystemSoundEffect int effectType, int userId) {
  3314. if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
  3315. return;
  3316. }
  3317. if (!querySoundEffectsEnabled(userId)) {
  3318. return;
  3319. }
  3320. final IAudioService service = getService();
  3321. try {
  3322. service.playSoundEffect(effectType);
  3323. } catch (RemoteException e) {
  3324. throw e.rethrowFromSystemServer();
  3325. }
  3326. }
  3327. /**
  3328. * Plays a sound effect (Key clicks, lid open/close...)
  3329. * @param effectType The type of sound effect.
  3330. * @param volume Sound effect volume.
  3331. * The volume value is a raw scalar so UI controls should be scaled logarithmically.
  3332. * If a volume of -1 is specified, the AudioManager.STREAM_MUSIC stream volume minus 3dB will be used.
  3333. * NOTE: This version is for applications that have their own
  3334. * settings panel for enabling and controlling volume.
  3335. */
  3336. public void playSoundEffect(@SystemSoundEffect int effectType, float volume) {
  3337. if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
  3338. return;
  3339. }
  3340. final IAudioService service = getService();
  3341. try {
  3342. service.playSoundEffectVolume(effectType, volume);
  3343. } catch (RemoteException e) {
  3344. throw e.rethrowFromSystemServer();
  3345. }
  3346. }
  3347. /**
  3348. * Settings has an in memory cache, so this is fast.
  3349. */
  3350. private boolean querySoundEffectsEnabled(int user) {
  3351. return Settings.System.getIntForUser(getContext().getContentResolver(),
  3352. Settings.System.SOUND_EFFECTS_ENABLED, 0, user) != 0;
  3353. }
  3354. /**
  3355. * Load Sound effects.
  3356. * This method must be called when sound effects are enabled.
  3357. */
  3358. public void loadSoundEffects() {
  3359. final IAudioService service = getService();
  3360. try {
  3361. service.loadSoundEffects();
  3362. } catch (RemoteException e) {
  3363. throw e.rethrowFromSystemServer();
  3364. }
  3365. }
  3366. /**
  3367. * Unload Sound effects.
  3368. * This method can be called to free some memory when
  3369. * sound effects are disabled.
  3370. */
  3371. public void unloadSoundEffects() {
  3372. final IAudioService service = getService();
  3373. try {
  3374. service.unloadSoundEffects();
  3375. } catch (RemoteException e) {
  3376. throw e.rethrowFromSystemServer();
  3377. }
  3378. }
  3379. /**
  3380. * @hide
  3381. */
  3382. public static String audioFocusToString(int focus) {
  3383. switch (focus) {
  3384. case AUDIOFOCUS_NONE:
  3385. return "AUDIOFOCUS_NONE";
  3386. case AUDIOFOCUS_GAIN:
  3387. return "AUDIOFOCUS_GAIN";
  3388. case AUDIOFOCUS_GAIN_TRANSIENT:
  3389. return "AUDIOFOCUS_GAIN_TRANSIENT";
  3390. case AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
  3391. return "AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK";
  3392. case AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE:
  3393. return "AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE";
  3394. case AUDIOFOCUS_LOSS:
  3395. return "AUDIOFOCUS_LOSS";
  3396. case AUDIOFOCUS_LOSS_TRANSIENT:
  3397. return "AUDIOFOCUS_LOSS_TRANSIENT";
  3398. case AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: // Note CAN_DUCK not MAY_DUCK.
  3399. return "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK";
  3400. default:
  3401. return "AUDIO_FOCUS_UNKNOWN(" + focus + ")";
  3402. }
  3403. }
  3404. /**
  3405. * Used to indicate no audio focus has been gained or lost, or requested.
  3406. */
  3407. public static final int AUDIOFOCUS_NONE = 0;
  3408. /**
  3409. * Used to indicate a gain of audio focus, or a request of audio focus, of unknown duration.
  3410. * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
  3411. * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
  3412. */
  3413. public static final int AUDIOFOCUS_GAIN = 1;
  3414. /**
  3415. * Used to indicate a temporary gain or request of audio focus, anticipated to last a short
  3416. * amount of time. Examples of temporary changes are the playback of driving directions, or an
  3417. * event notification.
  3418. * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
  3419. * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
  3420. */
  3421. public static final int AUDIOFOCUS_GAIN_TRANSIENT = 2;
  3422. /**
  3423. * Used to indicate a temporary request of audio focus, anticipated to last a short
  3424. * amount of time, and where it is acceptable for other audio applications to keep playing
  3425. * after having lowered their output level (also referred to as "ducking").
  3426. * Examples of temporary changes are the playback of driving directions where playback of music
  3427. * in the background is acceptable.
  3428. * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
  3429. * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
  3430. */
  3431. public static final int AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK = 3;
  3432. /**
  3433. * Used to indicate a temporary request of audio focus, anticipated to last a short
  3434. * amount of time, during which no other applications, or system components, should play
  3435. * anything. Examples of exclusive and transient audio focus requests are voice
  3436. * memo recording and speech recognition, during which the system shouldn't play any
  3437. * notifications, and media playback should have paused.
  3438. * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
  3439. */
  3440. public static final int AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE = 4;
  3441. /**
  3442. * Used to indicate a loss of audio focus of unknown duration.
  3443. * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
  3444. */
  3445. public static final int AUDIOFOCUS_LOSS = -1 * AUDIOFOCUS_GAIN;
  3446. /**
  3447. * Used to indicate a transient loss of audio focus.
  3448. * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
  3449. */
  3450. public static final int AUDIOFOCUS_LOSS_TRANSIENT = -1 * AUDIOFOCUS_GAIN_TRANSIENT;
  3451. /**
  3452. * Used to indicate a transient loss of audio focus where the loser of the audio focus can
  3453. * lower its output volume if it wants to continue playing (also referred to as "ducking"), as
  3454. * the new focus owner doesn't require others to be silent.
  3455. * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
  3456. */
  3457. public static final int AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK =
  3458. -1 * AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;
  3459. /**
  3460. * Interface definition for a callback to be invoked when the audio focus of the system is
  3461. * updated.
  3462. */
  3463. public interface OnAudioFocusChangeListener {
  3464. /**
  3465. * Called on the listener to notify it the audio focus for this listener has been changed.
  3466. * The focusChange value indicates whether the focus was gained,
  3467. * whether the focus was lost, and whether that loss is transient, or whether the new focus
  3468. * holder will hold it for an unknown amount of time.
  3469. * When losing focus, listeners can use the focus change information to decide what
  3470. * behavior to adopt when losing focus. A music player could for instance elect to lower
  3471. * the volume of its music stream (duck) for transient focus losses, and pause otherwise.
  3472. * @param focusChange the type of focus change, one of {@link AudioManager#AUDIOFOCUS_GAIN},
  3473. * {@link AudioManager#AUDIOFOCUS_LOSS}, {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT}
  3474. * and {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK}.
  3475. */
  3476. public void onAudioFocusChange(int focusChange);
  3477. }
  3478. /**
  3479. * Internal class to hold the AudioFocusRequest as well as the Handler for the callback
  3480. */
  3481. private static class FocusRequestInfo {
  3482. @NonNull final AudioFocusRequest mRequest;
  3483. @Nullable final Handler mHandler;
  3484. FocusRequestInfo(@NonNull AudioFocusRequest afr, @Nullable Handler handler) {
  3485. mRequest = afr;
  3486. mHandler = handler;
  3487. }
  3488. }
  3489. /**
  3490. * Map to convert focus event listener IDs, as used in the AudioService audio focus stack,
  3491. * to actual listener objects.
  3492. */
  3493. @UnsupportedAppUsage
  3494. private final ConcurrentHashMap<String, FocusRequestInfo> mAudioFocusIdListenerMap =
  3495. new ConcurrentHashMap<String, FocusRequestInfo>();
  3496. private FocusRequestInfo findFocusRequestInfo(String id) {
  3497. return mAudioFocusIdListenerMap.get(id);
  3498. }
  3499. /**
  3500. * Handler for events (audio focus change, recording config change) coming from the
  3501. * audio service.
  3502. */
  3503. private final ServiceEventHandlerDelegate mServiceEventHandlerDelegate =
  3504. new ServiceEventHandlerDelegate(null);
  3505. /**
  3506. * Event types
  3507. */
  3508. private final static int MSSG_FOCUS_CHANGE = 0;
  3509. private final static int MSSG_RECORDING_CONFIG_CHANGE = 1;
  3510. private final static int MSSG_PLAYBACK_CONFIG_CHANGE = 2;
  3511. /**
  3512. * Helper class to handle the forwarding of audio service events to the appropriate listener
  3513. */
  3514. private class ServiceEventHandlerDelegate {
  3515. private final Handler mHandler;
  3516. ServiceEventHandlerDelegate(Handler handler) {
  3517. Looper looper;
  3518. if (handler == null) {
  3519. if ((looper = Looper.myLooper()) == null) {
  3520. looper = Looper.getMainLooper();
  3521. }
  3522. } else {
  3523. looper = handler.getLooper();
  3524. }
  3525. if (looper != null) {
  3526. // implement the event handler delegate to receive events from audio service
  3527. mHandler = new Handler(looper) {
  3528. @Override
  3529. public void handleMessage(Message msg) {
  3530. switch (msg.what) {
  3531. case MSSG_FOCUS_CHANGE: {
  3532. final FocusRequestInfo fri = findFocusRequestInfo((String)msg.obj);
  3533. if (fri != null) {
  3534. final OnAudioFocusChangeListener listener =
  3535. fri.mRequest.getOnAudioFocusChangeListener();
  3536. if (listener != null) {
  3537. Log.d(TAG, "dispatching onAudioFocusChange("
  3538. + msg.arg1 + ") to " + msg.obj);
  3539. listener.onAudioFocusChange(msg.arg1);
  3540. }
  3541. }
  3542. } break;
  3543. case MSSG_RECORDING_CONFIG_CHANGE: {
  3544. final RecordConfigChangeCallbackData cbData =
  3545. (RecordConfigChangeCallbackData) msg.obj;
  3546. if (cbData.mCb != null) {
  3547. cbData.mCb.onRecordingConfigChanged(cbData.mConfigs);
  3548. }
  3549. } break;
  3550. case MSSG_PLAYBACK_CONFIG_CHANGE: {
  3551. final PlaybackConfigChangeCallbackData cbData =
  3552. (PlaybackConfigChangeCallbackData) msg.obj;
  3553. if (cbData.mCb != null) {
  3554. if (DEBUG) {
  3555. Log.d(TAG, "dispatching onPlaybackConfigChanged()");
  3556. }
  3557. cbData.mCb.onPlaybackConfigChanged(cbData.mConfigs);
  3558. }
  3559. } break;
  3560. default:
  3561. Log.e(TAG, "Unknown event " + msg.what);
  3562. }
  3563. }
  3564. };
  3565. } else {
  3566. mHandler = null;
  3567. }
  3568. }
  3569. Handler getHandler() {
  3570. return mHandler;
  3571. }
  3572. }
  3573. private final IAudioFocusDispatcher mAudioFocusDispatcher = new IAudioFocusDispatcher.Stub() {
  3574. @Override
  3575. public void dispatchAudioFocusChange(int focusChange, String id) {
  3576. final FocusRequestInfo fri = findFocusRequestInfo(id);
  3577. if (fri != null) {
  3578. final OnAudioFocusChangeListener listener =
  3579. fri.mRequest.getOnAudioFocusChangeListener();
  3580. if (listener != null) {
  3581. final Handler h = (fri.mHandler == null) ?
  3582. mServiceEventHandlerDelegate.getHandler() : fri.mHandler;
  3583. final Message m = h.obtainMessage(
  3584. MSSG_FOCUS_CHANGE/*what*/, focusChange/*arg1*/, 0/*arg2 ignored*/,
  3585. id/*obj*/);
  3586. h.sendMessage(m);
  3587. }
  3588. }
  3589. }
  3590. @Override
  3591. public void dispatchFocusResultFromExtPolicy(int requestResult, String clientId) {
  3592. synchronized (mFocusRequestsLock) {
  3593. // TODO use generation counter as the key instead
  3594. final BlockingFocusResultReceiver focusReceiver =
  3595. mFocusRequestsAwaitingResult.remove(clientId);
  3596. if (focusReceiver != null) {
  3597. focusReceiver.notifyResult(requestResult);
  3598. } else {
  3599. Log.e(TAG, "dispatchFocusResultFromExtPolicy found no result receiver");
  3600. }
  3601. }
  3602. }
  3603. };
  3604. private String getIdForAudioFocusListener(OnAudioFocusChangeListener l) {
  3605. if (l == null) {
  3606. return new String(this.toString());
  3607. } else {
  3608. return new String(this.toString() + l.toString());
  3609. }
  3610. }
  3611. /**
  3612. * @hide
  3613. * Registers a listener to be called when audio focus changes and keeps track of the associated
  3614. * focus request (including Handler to use for the listener).
  3615. * @param afr the full request parameters
  3616. */
  3617. public void registerAudioFocusRequest(@NonNull AudioFocusRequest afr) {
  3618. final Handler h = afr.getOnAudioFocusChangeListenerHandler();
  3619. final FocusRequestInfo fri = new FocusRequestInfo(afr, (h == null) ? null :
  3620. new ServiceEventHandlerDelegate(h).getHandler());
  3621. final String key = getIdForAudioFocusListener(afr.getOnAudioFocusChangeListener());
  3622. mAudioFocusIdListenerMap.put(key, fri);
  3623. }
  3624. /**
  3625. * @hide
  3626. * Causes the specified listener to not be called anymore when focus is gained or lost.
  3627. * @param l the listener to unregister.
  3628. */
  3629. public void unregisterAudioFocusRequest(OnAudioFocusChangeListener l) {
  3630. // remove locally
  3631. mAudioFocusIdListenerMap.remove(getIdForAudioFocusListener(l));
  3632. }
  3633. /**
  3634. * A failed focus change request.
  3635. */
  3636. public static final int AUDIOFOCUS_REQUEST_FAILED = 0;
  3637. /**
  3638. * A successful focus change request.
  3639. */
  3640. public static final int AUDIOFOCUS_REQUEST_GRANTED = 1;
  3641. /**
  3642. * A focus change request whose granting is delayed: the request was successful, but the
  3643. * requester will only be granted audio focus once the condition that prevented immediate
  3644. * granting has ended.
  3645. * See {@link #requestAudioFocus(AudioFocusRequest)} and
  3646. * {@link AudioFocusRequest.Builder#setAcceptsDelayedFocusGain(boolean)}
  3647. */
  3648. public static final int AUDIOFOCUS_REQUEST_DELAYED = 2;
  3649. /** @hide */
  3650. @IntDef(flag = false, prefix = "AUDIOFOCUS_REQUEST", value = {
  3651. AUDIOFOCUS_REQUEST_FAILED,
  3652. AUDIOFOCUS_REQUEST_GRANTED,
  3653. AUDIOFOCUS_REQUEST_DELAYED }
  3654. )
  3655. @Retention(RetentionPolicy.SOURCE)
  3656. public @interface FocusRequestResult {}
  3657. /**
  3658. * @hide
  3659. * code returned when a synchronous focus request on the client-side is to be blocked
  3660. * until the external audio focus policy decides on the response for the client
  3661. */
  3662. public static final int AUDIOFOCUS_REQUEST_WAITING_FOR_EXT_POLICY = 100;
  3663. /**
  3664. * Timeout duration in ms when waiting on an external focus policy for the result for a
  3665. * focus request
  3666. */
  3667. private static final int EXT_FOCUS_POLICY_TIMEOUT_MS = 200;
  3668. private static final String FOCUS_CLIENT_ID_STRING = "android_audio_focus_client_id";
  3669. private final Object mFocusRequestsLock = new Object();
  3670. /**
  3671. * Map of all receivers of focus request results, one per unresolved focus request.
  3672. * Receivers are added before sending the request to the external focus policy,
  3673. * and are removed either after receiving the result, or after the timeout.
  3674. * This variable is lazily initialized.
  3675. */
  3676. @GuardedBy("mFocusRequestsLock")
  3677. private HashMap<String, BlockingFocusResultReceiver> mFocusRequestsAwaitingResult;
  3678. /**
  3679. * Request audio focus.
  3680. * Send a request to obtain the audio focus
  3681. * @param l the listener to be notified of audio focus changes
  3682. * @param streamType the main audio stream type affected by the focus request
  3683. * @param durationHint use {@link #AUDIOFOCUS_GAIN_TRANSIENT} to indicate this focus request
  3684. * is temporary, and focus will be abandonned shortly. Examples of transient requests are
  3685. * for the playback of driving directions, or notifications sounds.
  3686. * Use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} to indicate also that it's ok for
  3687. * the previous focus owner to keep playing if it ducks its audio output.
  3688. * Alternatively use {@link #AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE} for a temporary request
  3689. * that benefits from the system not playing disruptive sounds like notifications, for
  3690. * usecases such as voice memo recording, or speech recognition.
  3691. * Use {@link #AUDIOFOCUS_GAIN} for a focus request of unknown duration such
  3692. * as the playback of a song or a video.
  3693. * @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
  3694. * @deprecated use {@link #requestAudioFocus(AudioFocusRequest)}
  3695. */
  3696. public int requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint) {
  3697. PlayerBase.deprecateStreamTypeForPlayback(streamType,
  3698. "AudioManager", "requestAudioFocus()");
  3699. int status = AUDIOFOCUS_REQUEST_FAILED;
  3700. try {
  3701. // status is guaranteed to be either AUDIOFOCUS_REQUEST_FAILED or
  3702. // AUDIOFOCUS_REQUEST_GRANTED as focus is requested without the
  3703. // AUDIOFOCUS_FLAG_DELAY_OK flag
  3704. status = requestAudioFocus(l,
  3705. new AudioAttributes.Builder()
  3706. .setInternalLegacyStreamType(streamType).build(),
  3707. durationHint,
  3708. 0 /* flags, legacy behavior */);
  3709. } catch (IllegalArgumentException e) {
  3710. Log.e(TAG, "Audio focus request denied due to ", e);
  3711. }
  3712. return status;
  3713. }
  3714. // when adding new flags, add them to the relevant AUDIOFOCUS_FLAGS_APPS or SYSTEM masks
  3715. /**
  3716. * @hide
  3717. * Use this flag when requesting audio focus to indicate it is ok for the requester to not be
  3718. * granted audio focus immediately (as indicated by {@link #AUDIOFOCUS_REQUEST_DELAYED}) when
  3719. * the system is in a state where focus cannot change, but be granted focus later when
  3720. * this condition ends.
  3721. */
  3722. @SystemApi
  3723. public static final int AUDIOFOCUS_FLAG_DELAY_OK = 0x1 << 0;
  3724. /**
  3725. * @hide
  3726. * Use this flag when requesting audio focus to indicate that the requester
  3727. * will pause its media playback (if applicable) when losing audio focus with
  3728. * {@link #AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK}, rather than ducking.
  3729. * <br>On some platforms, the ducking may be handled without the application being aware of it
  3730. * (i.e. it will not transiently lose focus). For applications that for instance play spoken
  3731. * content, such as audio book or podcast players, ducking may never be acceptable, and will
  3732. * thus always pause. This flag enables them to be declared as such whenever they request focus.
  3733. */
  3734. @SystemApi
  3735. public static final int AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS = 0x1 << 1;
  3736. /**
  3737. * @hide
  3738. * Use this flag to lock audio focus so granting is temporarily disabled.
  3739. * <br>This flag can only be used by owners of a registered
  3740. * {@link android.media.audiopolicy.AudioPolicy} in
  3741. * {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int, AudioPolicy)}
  3742. */
  3743. @SystemApi
  3744. public static final int AUDIOFOCUS_FLAG_LOCK = 0x1 << 2;
  3745. /**
  3746. * @hide
  3747. * flag set on test API calls,
  3748. * see {@link #requestAudioFocusForTest(AudioFocusRequest, String, int, int)},
  3749. * note that it isn't used in conjunction with other flags, it is passed as the single
  3750. * value for flags */
  3751. public static final int AUDIOFOCUS_FLAG_TEST = 0x1 << 3;
  3752. /** @hide */
  3753. public static final int AUDIOFOCUS_FLAGS_APPS = AUDIOFOCUS_FLAG_DELAY_OK
  3754. | AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS;
  3755. /** @hide */
  3756. public static final int AUDIOFOCUS_FLAGS_SYSTEM = AUDIOFOCUS_FLAG_DELAY_OK
  3757. | AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS | AUDIOFOCUS_FLAG_LOCK;
  3758. /**
  3759. * Request audio focus.
  3760. * See the {@link AudioFocusRequest} for information about the options available to configure
  3761. * your request, and notification of focus gain and loss.
  3762. * @param focusRequest a {@link AudioFocusRequest} instance used to configure how focus is
  3763. * requested.
  3764. * @return {@link #AUDIOFOCUS_REQUEST_FAILED}, {@link #AUDIOFOCUS_REQUEST_GRANTED}
  3765. * or {@link #AUDIOFOCUS_REQUEST_DELAYED}.
  3766. * <br>Note that the return value is never {@link #AUDIOFOCUS_REQUEST_DELAYED} when focus
  3767. * is requested without building the {@link AudioFocusRequest} with
  3768. * {@link AudioFocusRequest.Builder#setAcceptsDelayedFocusGain(boolean)} set to
  3769. * {@code true}.
  3770. * @throws NullPointerException if passed a null argument
  3771. */
  3772. public int requestAudioFocus(@NonNull AudioFocusRequest focusRequest) {
  3773. return requestAudioFocus(focusRequest, null /* no AudioPolicy*/);
  3774. }
  3775. /**
  3776. * Abandon audio focus. Causes the previous focus owner, if any, to receive focus.
  3777. * @param focusRequest the {@link AudioFocusRequest} that was used when requesting focus
  3778. * with {@link #requestAudioFocus(AudioFocusRequest)}.
  3779. * @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
  3780. * @throws IllegalArgumentException if passed a null argument
  3781. */
  3782. public int abandonAudioFocusRequest(@NonNull AudioFocusRequest focusRequest) {
  3783. if (focusRequest == null) {
  3784. throw new IllegalArgumentException("Illegal null AudioFocusRequest");
  3785. }
  3786. return abandonAudioFocus(focusRequest.getOnAudioFocusChangeListener(),
  3787. focusRequest.getAudioAttributes());
  3788. }
  3789. /**
  3790. * @hide
  3791. * Request audio focus.
  3792. * Send a request to obtain the audio focus. This method differs from
  3793. * {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)} in that it can express
  3794. * that the requester accepts delayed grants of audio focus.
  3795. * @param l the listener to be notified of audio focus changes. It is not allowed to be null
  3796. * when the request is flagged with {@link #AUDIOFOCUS_FLAG_DELAY_OK}.
  3797. * @param requestAttributes non null {@link AudioAttributes} describing the main reason for
  3798. * requesting audio focus.
  3799. * @param durationHint use {@link #AUDIOFOCUS_GAIN_TRANSIENT} to indicate this focus request
  3800. * is temporary, and focus will be abandonned shortly. Examples of transient requests are
  3801. * for the playback of driving directions, or notifications sounds.
  3802. * Use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} to indicate also that it's ok for
  3803. * the previous focus owner to keep playing if it ducks its audio output.
  3804. * Alternatively use {@link #AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE} for a temporary request
  3805. * that benefits from the system not playing disruptive sounds like notifications, for
  3806. * usecases such as voice memo recording, or speech recognition.
  3807. * Use {@link #AUDIOFOCUS_GAIN} for a focus request of unknown duration such
  3808. * as the playback of a song or a video.
  3809. * @param flags 0 or a combination of {link #AUDIOFOCUS_FLAG_DELAY_OK},
  3810. * {@link #AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS} and {@link #AUDIOFOCUS_FLAG_LOCK}.
  3811. * <br>Use 0 when not using any flags for the request, which behaves like
  3812. * {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)}, where either audio
  3813. * focus is granted immediately, or the grant request fails because the system is in a
  3814. * state where focus cannot change (e.g. a phone call).
  3815. * @return {@link #AUDIOFOCUS_REQUEST_FAILED}, {@link #AUDIOFOCUS_REQUEST_GRANTED}
  3816. * or {@link #AUDIOFOCUS_REQUEST_DELAYED}.
  3817. * The return value is never {@link #AUDIOFOCUS_REQUEST_DELAYED} when focus is requested
  3818. * without the {@link #AUDIOFOCUS_FLAG_DELAY_OK} flag.
  3819. * @throws IllegalArgumentException
  3820. */
  3821. @SystemApi
  3822. @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
  3823. public int requestAudioFocus(OnAudioFocusChangeListener l,
  3824. @NonNull AudioAttributes requestAttributes,
  3825. int durationHint,
  3826. int flags) throws IllegalArgumentException {
  3827. if (flags != (flags & AUDIOFOCUS_FLAGS_APPS)) {
  3828. throw new IllegalArgumentException("Invalid flags 0x"
  3829. + Integer.toHexString(flags).toUpperCase());
  3830. }
  3831. return requestAudioFocus(l, requestAttributes, durationHint,
  3832. flags & AUDIOFOCUS_FLAGS_APPS,
  3833. null /* no AudioPolicy*/);
  3834. }
  3835. /**
  3836. * @hide
  3837. * Request or lock audio focus.
  3838. * This method is to be used by system components that have registered an
  3839. * {@link android.media.audiopolicy.AudioPolicy} to request audio focus, but also to "lock" it
  3840. * so focus granting is temporarily disabled.
  3841. * @param l see the description of the same parameter in
  3842. * {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int)}
  3843. * @param requestAttributes non null {@link AudioAttributes} describing the main reason for
  3844. * requesting audio focus.
  3845. * @param durationHint see the description of the same parameter in
  3846. * {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int)}
  3847. * @param flags 0 or a combination of {link #AUDIOFOCUS_FLAG_DELAY_OK},
  3848. * {@link #AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS}, and {@link #AUDIOFOCUS_FLAG_LOCK}.
  3849. * <br>Use 0 when not using any flags for the request, which behaves like
  3850. * {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)}, where either audio
  3851. * focus is granted immediately, or the grant request fails because the system is in a
  3852. * state where focus cannot change (e.g. a phone call).
  3853. * @param ap a registered {@link android.media.audiopolicy.AudioPolicy} instance when locking
  3854. * focus, or null.
  3855. * @return see the description of the same return value in
  3856. * {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int)}
  3857. * @throws IllegalArgumentException
  3858. * @deprecated use {@link #requestAudioFocus(AudioFocusRequest, AudioPolicy)}
  3859. */
  3860. @SystemApi
  3861. @RequiresPermission(anyOf= {
  3862. android.Manifest.permission.MODIFY_PHONE_STATE,
  3863. android.Manifest.permission.MODIFY_AUDIO_ROUTING
  3864. })
  3865. public int requestAudioFocus(OnAudioFocusChangeListener l,
  3866. @NonNull AudioAttributes requestAttributes,
  3867. int durationHint,
  3868. int flags,
  3869. AudioPolicy ap) throws IllegalArgumentException {
  3870. // parameter checking
  3871. if (requestAttributes == null) {
  3872. throw new IllegalArgumentException("Illegal null AudioAttributes argument");
  3873. }
  3874. if (!AudioFocusRequest.isValidFocusGain(durationHint)) {
  3875. throw new IllegalArgumentException("Invalid duration hint");
  3876. }
  3877. if (flags != (flags & AUDIOFOCUS_FLAGS_SYSTEM)) {
  3878. throw new IllegalArgumentException("Illegal flags 0x"
  3879. + Integer.toHexString(flags).toUpperCase());
  3880. }
  3881. if (((flags & AUDIOFOCUS_FLAG_DELAY_OK) == AUDIOFOCUS_FLAG_DELAY_OK) && (l == null)) {
  3882. throw new IllegalArgumentException(
  3883. "Illegal null focus listener when flagged as accepting delayed focus grant");
  3884. }
  3885. if (((flags & AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS)
  3886. == AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS) && (l == null)) {
  3887. throw new IllegalArgumentException(
  3888. "Illegal null focus listener when flagged as pausing instead of ducking");
  3889. }
  3890. if (((flags & AUDIOFOCUS_FLAG_LOCK) == AUDIOFOCUS_FLAG_LOCK) && (ap == null)) {
  3891. throw new IllegalArgumentException(
  3892. "Illegal null audio policy when locking audio focus");
  3893. }
  3894. final AudioFocusRequest afr = new AudioFocusRequest.Builder(durationHint)
  3895. .setOnAudioFocusChangeListenerInt(l, null /* no Handler for this legacy API */)
  3896. .setAudioAttributes(requestAttributes)
  3897. .setAcceptsDelayedFocusGain((flags & AUDIOFOCUS_FLAG_DELAY_OK)
  3898. == AUDIOFOCUS_FLAG_DELAY_OK)
  3899. .setWillPauseWhenDucked((flags & AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS)
  3900. == AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS)
  3901. .setLocksFocus((flags & AUDIOFOCUS_FLAG_LOCK) == AUDIOFOCUS_FLAG_LOCK)
  3902. .build();
  3903. return requestAudioFocus(afr, ap);
  3904. }
  3905. /**
  3906. * @hide
  3907. * Test API to request audio focus for an arbitrary client operating from a (fake) given UID.
  3908. * Used to simulate conditions of the test, not the behavior of the focus requester under test.
  3909. * @param afr the parameters of the request
  3910. * @param clientFakeId the identifier of the AudioManager the client would be requesting from
  3911. * @param clientFakeUid the UID of the client, here an arbitrary int,
  3912. * doesn't have to be a real UID
  3913. * @param clientTargetSdk the target SDK used by the client
  3914. * @return return code indicating status of the request
  3915. */
  3916. @TestApi
  3917. @RequiresPermission("android.permission.QUERY_AUDIO_STATE")
  3918. public @FocusRequestResult int requestAudioFocusForTest(@NonNull AudioFocusRequest afr,
  3919. @NonNull String clientFakeId, int clientFakeUid, int clientTargetSdk) {
  3920. Objects.requireNonNull(afr);
  3921. Objects.requireNonNull(clientFakeId);
  3922. try {
  3923. return getService().requestAudioFocusForTest(afr.getAudioAttributes(),
  3924. afr.getFocusGain(),
  3925. mICallBack,
  3926. mAudioFocusDispatcher,
  3927. clientFakeId, "com.android.test.fakeclient", clientFakeUid, clientTargetSdk);
  3928. } catch (RemoteException e) {
  3929. throw e.rethrowFromSystemServer();
  3930. }
  3931. }
  3932. /**
  3933. * @hide
  3934. * Test API to abandon audio focus for an arbitrary client.
  3935. * Used to simulate conditions of the test, not the behavior of the focus requester under test.
  3936. * @param afr the parameters used for the request
  3937. * @param clientFakeId clientFakeId the identifier of the AudioManager from which the client
  3938. * would be requesting
  3939. * @return return code indicating status of the request
  3940. */
  3941. @TestApi
  3942. @RequiresPermission("android.permission.QUERY_AUDIO_STATE")
  3943. public @FocusRequestResult int abandonAudioFocusForTest(@NonNull AudioFocusRequest afr,
  3944. @NonNull String clientFakeId) {
  3945. Objects.requireNonNull(afr);
  3946. Objects.requireNonNull(clientFakeId);
  3947. try {
  3948. return getService().abandonAudioFocusForTest(mAudioFocusDispatcher,
  3949. clientFakeId, afr.getAudioAttributes(), "com.android.test.fakeclient");
  3950. } catch (RemoteException e) {
  3951. throw e.rethrowFromSystemServer();
  3952. }
  3953. }
  3954. /**
  3955. * @hide
  3956. * Return the duration of the fade out applied when a player of the given AudioAttributes
  3957. * is losing audio focus
  3958. * @param aa the AudioAttributes of the player losing focus with {@link #AUDIOFOCUS_LOSS}
  3959. * @return a duration in ms, 0 indicates no fade out is applied
  3960. */
  3961. @TestApi
  3962. @RequiresPermission("android.permission.QUERY_AUDIO_STATE")
  3963. public @IntRange(from = 0) long getFadeOutDurationOnFocusLossMillis(@NonNull AudioAttributes aa)
  3964. {
  3965. Objects.requireNonNull(aa);
  3966. try {
  3967. return getService().getFadeOutDurationOnFocusLossMillis(aa);
  3968. } catch (RemoteException e) {
  3969. throw e.rethrowFromSystemServer();
  3970. }
  3971. }
  3972. /**
  3973. * @hide
  3974. * Request or lock audio focus.
  3975. * This method is to be used by system components that have registered an
  3976. * {@link android.media.audiopolicy.AudioPolicy} to request audio focus, but also to "lock" it
  3977. * so focus granting is temporarily disabled.
  3978. * @param afr see the description of the same parameter in
  3979. * {@link #requestAudioFocus(AudioFocusRequest)}
  3980. * @param ap a registered {@link android.media.audiopolicy.AudioPolicy} instance when locking
  3981. * focus, or null.
  3982. * @return {@link #AUDIOFOCUS_REQUEST_FAILED}, {@link #AUDIOFOCUS_REQUEST_GRANTED}
  3983. * or {@link #AUDIOFOCUS_REQUEST_DELAYED}.
  3984. * @throws NullPointerException if the AudioFocusRequest is null
  3985. * @throws IllegalArgumentException when trying to lock focus without an AudioPolicy
  3986. */
  3987. @SystemApi
  3988. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  3989. public int requestAudioFocus(@NonNull AudioFocusRequest afr, @Nullable AudioPolicy ap) {
  3990. if (afr == null) {
  3991. throw new NullPointerException("Illegal null AudioFocusRequest");
  3992. }
  3993. // this can only be checked now, not during the creation of the AudioFocusRequest instance
  3994. if (afr.locksFocus() && ap == null) {
  3995. throw new IllegalArgumentException(
  3996. "Illegal null audio policy when locking audio focus");
  3997. }
  3998. registerAudioFocusRequest(afr);
  3999. final IAudioService service = getService();
  4000. final int status;
  4001. int sdk;
  4002. try {
  4003. sdk = getContext().getApplicationInfo().targetSdkVersion;
  4004. } catch (NullPointerException e) {
  4005. // some tests don't have a Context
  4006. sdk = Build.VERSION.SDK_INT;
  4007. }
  4008. final String clientId = getIdForAudioFocusListener(afr.getOnAudioFocusChangeListener());
  4009. final BlockingFocusResultReceiver focusReceiver;
  4010. synchronized (mFocusRequestsLock) {
  4011. try {
  4012. // TODO status contains result and generation counter for ext policy
  4013. status = service.requestAudioFocus(afr.getAudioAttributes(),
  4014. afr.getFocusGain(), mICallBack,
  4015. mAudioFocusDispatcher,
  4016. clientId,
  4017. getContext().getOpPackageName() /* package name */, afr.getFlags(),
  4018. ap != null ? ap.cb() : null,
  4019. sdk);
  4020. } catch (RemoteException e) {
  4021. throw e.rethrowFromSystemServer();
  4022. }
  4023. if (status != AudioManager.AUDIOFOCUS_REQUEST_WAITING_FOR_EXT_POLICY) {
  4024. // default path with no external focus policy
  4025. return status;
  4026. }
  4027. if (mFocusRequestsAwaitingResult == null) {
  4028. mFocusRequestsAwaitingResult =
  4029. new HashMap<String, BlockingFocusResultReceiver>(1);
  4030. }
  4031. focusReceiver = new BlockingFocusResultReceiver(clientId);
  4032. mFocusRequestsAwaitingResult.put(clientId, focusReceiver);
  4033. }
  4034. focusReceiver.waitForResult(EXT_FOCUS_POLICY_TIMEOUT_MS);
  4035. if (DEBUG && !focusReceiver.receivedResult()) {
  4036. Log.e(TAG, "requestAudio response from ext policy timed out, denying request");
  4037. }
  4038. synchronized (mFocusRequestsLock) {
  4039. mFocusRequestsAwaitingResult.remove(clientId);
  4040. }
  4041. return focusReceiver.requestResult();
  4042. }
  4043. // helper class that abstracts out the handling of spurious wakeups in Object.wait()
  4044. private static final class SafeWaitObject {
  4045. private boolean mQuit = false;
  4046. public void safeNotify() {
  4047. synchronized (this) {
  4048. mQuit = true;
  4049. this.notify();
  4050. }
  4051. }
  4052. public void safeWait(long millis) throws InterruptedException {
  4053. final long timeOutTime = java.lang.System.currentTimeMillis() + millis;
  4054. synchronized (this) {
  4055. while (!mQuit) {
  4056. final long timeToWait = timeOutTime - java.lang.System.currentTimeMillis();
  4057. if (timeToWait < 0) { break; }
  4058. this.wait(timeToWait);
  4059. }
  4060. }
  4061. }
  4062. }
  4063. private static final class BlockingFocusResultReceiver {
  4064. private final SafeWaitObject mLock = new SafeWaitObject();
  4065. @GuardedBy("mLock")
  4066. private boolean mResultReceived = false;
  4067. // request denied by default (e.g. timeout)
  4068. private int mFocusRequestResult = AudioManager.AUDIOFOCUS_REQUEST_FAILED;
  4069. private final String mFocusClientId;
  4070. BlockingFocusResultReceiver(String clientId) {
  4071. mFocusClientId = clientId;
  4072. }
  4073. boolean receivedResult() { return mResultReceived; }
  4074. int requestResult() { return mFocusRequestResult; }
  4075. void notifyResult(int requestResult) {
  4076. synchronized (mLock) {
  4077. mResultReceived = true;
  4078. mFocusRequestResult = requestResult;
  4079. mLock.safeNotify();
  4080. }
  4081. }
  4082. public void waitForResult(long timeOutMs) {
  4083. synchronized (mLock) {
  4084. if (mResultReceived) {
  4085. // the result was received before waiting
  4086. return;
  4087. }
  4088. try {
  4089. mLock.safeWait(timeOutMs);
  4090. } catch (InterruptedException e) { }
  4091. }
  4092. }
  4093. }
  4094. /**
  4095. * @hide
  4096. * Used internally by telephony package to request audio focus. Will cause the focus request
  4097. * to be associated with the "voice communication" identifier only used in AudioService
  4098. * to identify this use case.
  4099. * @param streamType use STREAM_RING for focus requests when ringing, VOICE_CALL for
  4100. * the establishment of the call
  4101. * @param durationHint the type of focus request. AUDIOFOCUS_GAIN_TRANSIENT is recommended so
  4102. * media applications resume after a call
  4103. */
  4104. @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  4105. public void requestAudioFocusForCall(int streamType, int durationHint) {
  4106. final IAudioService service = getService();
  4107. try {
  4108. service.requestAudioFocus(new AudioAttributes.Builder()
  4109. .setInternalLegacyStreamType(streamType).build(),
  4110. durationHint, mICallBack, null,
  4111. AudioSystem.IN_VOICE_COMM_FOCUS_ID,
  4112. getContext().getOpPackageName(),
  4113. AUDIOFOCUS_FLAG_LOCK,
  4114. null /* policy token */, 0 /* sdk n/a here*/);
  4115. } catch (RemoteException e) {
  4116. throw e.rethrowFromSystemServer();
  4117. }
  4118. }
  4119. /**
  4120. * @hide
  4121. * Return the volume ramping time for a sound to be played after the given focus request,
  4122. * and to play a sound of the given attributes
  4123. * @param focusGain
  4124. * @param attr
  4125. * @return
  4126. */
  4127. public int getFocusRampTimeMs(int focusGain, AudioAttributes attr) {
  4128. final IAudioService service = getService();
  4129. try {
  4130. return service.getFocusRampTimeMs(focusGain, attr);
  4131. } catch (RemoteException e) {
  4132. throw e.rethrowFromSystemServer();
  4133. }
  4134. }
  4135. /**
  4136. * @hide
  4137. * Set the result to the audio focus request received through
  4138. * {@link AudioPolicyFocusListener#onAudioFocusRequest(AudioFocusInfo, int)}.
  4139. * @param afi the information about the focus requester
  4140. * @param requestResult the result to the focus request to be passed to the requester
  4141. * @param ap a valid registered {@link AudioPolicy} configured as a focus policy.
  4142. */
  4143. @SystemApi
  4144. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  4145. public void setFocusRequestResult(@NonNull AudioFocusInfo afi,
  4146. @FocusRequestResult int requestResult, @NonNull AudioPolicy ap) {
  4147. if (afi == null) {
  4148. throw new IllegalArgumentException("Illegal null AudioFocusInfo");
  4149. }
  4150. if (ap == null) {
  4151. throw new IllegalArgumentException("Illegal null AudioPolicy");
  4152. }
  4153. final IAudioService service = getService();
  4154. try {
  4155. service.setFocusRequestResultFromExtPolicy(afi, requestResult, ap.cb());
  4156. } catch (RemoteException e) {
  4157. throw e.rethrowFromSystemServer();
  4158. }
  4159. }
  4160. /**
  4161. * @hide
  4162. * Notifies an application with a focus listener of gain or loss of audio focus.
  4163. * This method can only be used by owners of an {@link AudioPolicy} configured with
  4164. * {@link AudioPolicy.Builder#setIsAudioFocusPolicy(boolean)} set to true.
  4165. * @param afi the recipient of the focus change, that has previously requested audio focus, and
  4166. * that was received by the {@code AudioPolicy} through
  4167. * {@link AudioPolicy.AudioPolicyFocusListener#onAudioFocusRequest(AudioFocusInfo, int)}.
  4168. * @param focusChange one of focus gain types ({@link #AUDIOFOCUS_GAIN},
  4169. * {@link #AUDIOFOCUS_GAIN_TRANSIENT}, {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} or
  4170. * {@link #AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE})
  4171. * or one of the focus loss types ({@link AudioManager#AUDIOFOCUS_LOSS},
  4172. * {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT},
  4173. * or {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK}).
  4174. * <br>For the focus gain, the change type should be the same as the app requested.
  4175. * @param ap a valid registered {@link AudioPolicy} configured as a focus policy.
  4176. * @return {@link #AUDIOFOCUS_REQUEST_GRANTED} if the dispatch was successfully sent, or
  4177. * {@link #AUDIOFOCUS_REQUEST_FAILED} if the focus client didn't have a listener, or
  4178. * if there was an error sending the request.
  4179. * @throws NullPointerException if the {@link AudioFocusInfo} or {@link AudioPolicy} are null.
  4180. */
  4181. @SystemApi
  4182. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  4183. public int dispatchAudioFocusChange(@NonNull AudioFocusInfo afi, int focusChange,
  4184. @NonNull AudioPolicy ap) {
  4185. if (afi == null) {
  4186. throw new NullPointerException("Illegal null AudioFocusInfo");
  4187. }
  4188. if (ap == null) {
  4189. throw new NullPointerException("Illegal null AudioPolicy");
  4190. }
  4191. final IAudioService service = getService();
  4192. try {
  4193. return service.dispatchFocusChange(afi, focusChange, ap.cb());
  4194. } catch (RemoteException e) {
  4195. throw e.rethrowFromSystemServer();
  4196. }
  4197. }
  4198. /**
  4199. * @hide
  4200. * Used internally by telephony package to abandon audio focus, typically after a call or
  4201. * when ringing ends and the call is rejected or not answered.
  4202. * Should match one or more calls to {@link #requestAudioFocusForCall(int, int)}.
  4203. */
  4204. @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  4205. public void abandonAudioFocusForCall() {
  4206. final IAudioService service = getService();
  4207. try {
  4208. service.abandonAudioFocus(null, AudioSystem.IN_VOICE_COMM_FOCUS_ID,
  4209. null /*AudioAttributes, legacy behavior*/, getContext().getOpPackageName());
  4210. } catch (RemoteException e) {
  4211. throw e.rethrowFromSystemServer();
  4212. }
  4213. }
  4214. /**
  4215. * Abandon audio focus. Causes the previous focus owner, if any, to receive focus.
  4216. * @param l the listener with which focus was requested.
  4217. * @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
  4218. * @deprecated use {@link #abandonAudioFocusRequest(AudioFocusRequest)}
  4219. */
  4220. public int abandonAudioFocus(OnAudioFocusChangeListener l) {
  4221. return abandonAudioFocus(l, null /*AudioAttributes, legacy behavior*/);
  4222. }
  4223. /**
  4224. * @hide
  4225. * Abandon audio focus. Causes the previous focus owner, if any, to receive focus.
  4226. * @param l the listener with which focus was requested.
  4227. * @param aa the {@link AudioAttributes} with which audio focus was requested
  4228. * @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
  4229. * @deprecated use {@link #abandonAudioFocusRequest(AudioFocusRequest)}
  4230. */
  4231. @SystemApi
  4232. @SuppressLint("RequiresPermission") // no permission enforcement, but only "undoes" what would
  4233. // have been done by a matching requestAudioFocus
  4234. public int abandonAudioFocus(OnAudioFocusChangeListener l, AudioAttributes aa) {
  4235. int status = AUDIOFOCUS_REQUEST_FAILED;
  4236. unregisterAudioFocusRequest(l);
  4237. final IAudioService service = getService();
  4238. try {
  4239. status = service.abandonAudioFocus(mAudioFocusDispatcher,
  4240. getIdForAudioFocusListener(l), aa, getContext().getOpPackageName());
  4241. } catch (RemoteException e) {
  4242. throw e.rethrowFromSystemServer();
  4243. }
  4244. return status;
  4245. }
  4246. //====================================================================
  4247. // Remote Control
  4248. /**
  4249. * Register a component to be the sole receiver of MEDIA_BUTTON intents.
  4250. * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
  4251. * that will receive the media button intent. This broadcast receiver must be declared
  4252. * in the application manifest. The package of the component must match that of
  4253. * the context you're registering from.
  4254. * @deprecated Use {@link MediaSession#setMediaButtonReceiver(PendingIntent)} instead.
  4255. */
  4256. @Deprecated
  4257. public void registerMediaButtonEventReceiver(ComponentName eventReceiver) {
  4258. if (eventReceiver == null) {
  4259. return;
  4260. }
  4261. if (!eventReceiver.getPackageName().equals(getContext().getPackageName())) {
  4262. Log.e(TAG, "registerMediaButtonEventReceiver() error: " +
  4263. "receiver and context package names don't match");
  4264. return;
  4265. }
  4266. // construct a PendingIntent for the media button and register it
  4267. Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
  4268. // the associated intent will be handled by the component being registered
  4269. mediaButtonIntent.setComponent(eventReceiver);
  4270. PendingIntent pi = PendingIntent.getBroadcast(getContext(),
  4271. 0/*requestCode, ignored*/, mediaButtonIntent,
  4272. PendingIntent.FLAG_IMMUTABLE);
  4273. registerMediaButtonIntent(pi, eventReceiver);
  4274. }
  4275. /**
  4276. * Register a component to be the sole receiver of MEDIA_BUTTON intents. This is like
  4277. * {@link #registerMediaButtonEventReceiver(android.content.ComponentName)}, but allows
  4278. * the buttons to go to any PendingIntent. Note that you should only use this form if
  4279. * you know you will continue running for the full time until unregistering the
  4280. * PendingIntent.
  4281. * @param eventReceiver target that will receive media button intents. The PendingIntent
  4282. * will be sent an {@link Intent#ACTION_MEDIA_BUTTON} event when a media button action
  4283. * occurs, with {@link Intent#EXTRA_KEY_EVENT} added and holding the key code of the
  4284. * media button that was pressed.
  4285. * @deprecated Use {@link MediaSession#setMediaButtonReceiver(PendingIntent)} instead.
  4286. */
  4287. @Deprecated
  4288. public void registerMediaButtonEventReceiver(PendingIntent eventReceiver) {
  4289. if (eventReceiver == null) {
  4290. return;
  4291. }
  4292. registerMediaButtonIntent(eventReceiver, null);
  4293. }
  4294. /**
  4295. * @hide
  4296. * no-op if (pi == null) or (eventReceiver == null)
  4297. */
  4298. public void registerMediaButtonIntent(PendingIntent pi, ComponentName eventReceiver) {
  4299. if (pi == null) {
  4300. Log.e(TAG, "Cannot call registerMediaButtonIntent() with a null parameter");
  4301. return;
  4302. }
  4303. MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(getContext());
  4304. helper.addMediaButtonListener(pi, eventReceiver, getContext());
  4305. }
  4306. /**
  4307. * Unregister the receiver of MEDIA_BUTTON intents.
  4308. * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
  4309. * that was registered with {@link #registerMediaButtonEventReceiver(ComponentName)}.
  4310. * @deprecated Use {@link MediaSession} instead.
  4311. */
  4312. @Deprecated
  4313. public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) {
  4314. if (eventReceiver == null) {
  4315. return;
  4316. }
  4317. // construct a PendingIntent for the media button and unregister it
  4318. Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
  4319. // the associated intent will be handled by the component being registered
  4320. mediaButtonIntent.setComponent(eventReceiver);
  4321. PendingIntent pi = PendingIntent.getBroadcast(getContext(),
  4322. 0/*requestCode, ignored*/, mediaButtonIntent,
  4323. PendingIntent.FLAG_IMMUTABLE);
  4324. unregisterMediaButtonIntent(pi);
  4325. }
  4326. /**
  4327. * Unregister the receiver of MEDIA_BUTTON intents.
  4328. * @param eventReceiver same PendingIntent that was registed with
  4329. * {@link #registerMediaButtonEventReceiver(PendingIntent)}.
  4330. * @deprecated Use {@link MediaSession} instead.
  4331. */
  4332. @Deprecated
  4333. public void unregisterMediaButtonEventReceiver(PendingIntent eventReceiver) {
  4334. if (eventReceiver == null) {
  4335. return;
  4336. }
  4337. unregisterMediaButtonIntent(eventReceiver);
  4338. }
  4339. /**
  4340. * @hide
  4341. */
  4342. public void unregisterMediaButtonIntent(PendingIntent pi) {
  4343. MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(getContext());
  4344. helper.removeMediaButtonListener(pi);
  4345. }
  4346. /**
  4347. * Registers the remote control client for providing information to display on the remote
  4348. * controls.
  4349. * @param rcClient The remote control client from which remote controls will receive
  4350. * information to display.
  4351. * @see RemoteControlClient
  4352. * @deprecated Use {@link MediaSession} instead.
  4353. */
  4354. @Deprecated
  4355. public void registerRemoteControlClient(RemoteControlClient rcClient) {
  4356. if ((rcClient == null) || (rcClient.getRcMediaIntent() == null)) {
  4357. return;
  4358. }
  4359. rcClient.registerWithSession(MediaSessionLegacyHelper.getHelper(getContext()));
  4360. }
  4361. /**
  4362. * Unregisters the remote control client that was providing information to display on the
  4363. * remote controls.
  4364. * @param rcClient The remote control client to unregister.
  4365. * @see #registerRemoteControlClient(RemoteControlClient)
  4366. * @deprecated Use {@link MediaSession} instead.
  4367. */
  4368. @Deprecated
  4369. public void unregisterRemoteControlClient(RemoteControlClient rcClient) {
  4370. if ((rcClient == null) || (rcClient.getRcMediaIntent() == null)) {
  4371. return;
  4372. }
  4373. rcClient.unregisterWithSession(MediaSessionLegacyHelper.getHelper(getContext()));
  4374. }
  4375. /**
  4376. * Registers a {@link RemoteController} instance for it to receive media
  4377. * metadata updates and playback state information from applications using
  4378. * {@link RemoteControlClient}, and control their playback.
  4379. * <p>
  4380. * Registration requires the {@link RemoteController.OnClientUpdateListener} listener to be
  4381. * one of the enabled notification listeners (see
  4382. * {@link android.service.notification.NotificationListenerService}).
  4383. *
  4384. * @param rctlr the object to register.
  4385. * @return true if the {@link RemoteController} was successfully registered,
  4386. * false if an error occurred, due to an internal system error, or
  4387. * insufficient permissions.
  4388. * @deprecated Use
  4389. * {@link MediaSessionManager#addOnActiveSessionsChangedListener(android.media.session.MediaSessionManager.OnActiveSessionsChangedListener, ComponentName)}
  4390. * and {@link MediaController} instead.
  4391. */
  4392. @Deprecated
  4393. public boolean registerRemoteController(RemoteController rctlr) {
  4394. if (rctlr == null) {
  4395. return false;
  4396. }
  4397. rctlr.startListeningToSessions();
  4398. return true;
  4399. }
  4400. /**
  4401. * Unregisters a {@link RemoteController}, causing it to no longer receive
  4402. * media metadata and playback state information, and no longer be capable
  4403. * of controlling playback.
  4404. *
  4405. * @param rctlr the object to unregister.
  4406. * @deprecated Use
  4407. * {@link MediaSessionManager#removeOnActiveSessionsChangedListener(android.media.session.MediaSessionManager.OnActiveSessionsChangedListener)}
  4408. * instead.
  4409. */
  4410. @Deprecated
  4411. public void unregisterRemoteController(RemoteController rctlr) {
  4412. if (rctlr == null) {
  4413. return;
  4414. }
  4415. rctlr.stopListeningToSessions();
  4416. }
  4417. //====================================================================
  4418. // Audio policy
  4419. /**
  4420. * @hide
  4421. * Register the given {@link AudioPolicy}.
  4422. * This call is synchronous and blocks until the registration process successfully completed
  4423. * or failed to complete.
  4424. * @param policy the non-null {@link AudioPolicy} to register.
  4425. * @return {@link #ERROR} if there was an error communicating with the registration service
  4426. * or if the user doesn't have the required
  4427. * {@link android.Manifest.permission#MODIFY_AUDIO_ROUTING} permission,
  4428. * {@link #SUCCESS} otherwise.
  4429. */
  4430. @SystemApi
  4431. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  4432. public int registerAudioPolicy(@NonNull AudioPolicy policy) {
  4433. return registerAudioPolicyStatic(policy);
  4434. }
  4435. static int registerAudioPolicyStatic(@NonNull AudioPolicy policy) {
  4436. if (policy == null) {
  4437. throw new IllegalArgumentException("Illegal null AudioPolicy argument");
  4438. }
  4439. final IAudioService service = getService();
  4440. try {
  4441. MediaProjection projection = policy.getMediaProjection();
  4442. String regId = service.registerAudioPolicy(policy.getConfig(), policy.cb(),
  4443. policy.hasFocusListener(), policy.isFocusPolicy(), policy.isTestFocusPolicy(),
  4444. policy.isVolumeController(),
  4445. projection == null ? null : projection.getProjection());
  4446. if (regId == null) {
  4447. return ERROR;
  4448. } else {
  4449. policy.setRegistration(regId);
  4450. }
  4451. // successful registration
  4452. } catch (RemoteException e) {
  4453. throw e.rethrowFromSystemServer();
  4454. }
  4455. return SUCCESS;
  4456. }
  4457. /**
  4458. * @hide
  4459. * Unregisters an {@link AudioPolicy} asynchronously.
  4460. * @param policy the non-null {@link AudioPolicy} to unregister.
  4461. */
  4462. @SystemApi
  4463. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  4464. public void unregisterAudioPolicyAsync(@NonNull AudioPolicy policy) {
  4465. unregisterAudioPolicyAsyncStatic(policy);
  4466. }
  4467. static void unregisterAudioPolicyAsyncStatic(@NonNull AudioPolicy policy) {
  4468. if (policy == null) {
  4469. throw new IllegalArgumentException("Illegal null AudioPolicy argument");
  4470. }
  4471. final IAudioService service = getService();
  4472. try {
  4473. service.unregisterAudioPolicyAsync(policy.cb());
  4474. policy.reset();
  4475. } catch (RemoteException e) {
  4476. throw e.rethrowFromSystemServer();
  4477. }
  4478. }
  4479. /**
  4480. * @hide
  4481. * Unregisters an {@link AudioPolicy} synchronously.
  4482. * This method also invalidates all {@link AudioRecord} and {@link AudioTrack} objects
  4483. * associated with mixes of this policy.
  4484. * @param policy the non-null {@link AudioPolicy} to unregister.
  4485. */
  4486. @SystemApi
  4487. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  4488. public void unregisterAudioPolicy(@NonNull AudioPolicy policy) {
  4489. Preconditions.checkNotNull(policy, "Illegal null AudioPolicy argument");
  4490. final IAudioService service = getService();
  4491. try {
  4492. policy.invalidateCaptorsAndInjectors();
  4493. service.unregisterAudioPolicy(policy.cb());
  4494. policy.reset();
  4495. } catch (RemoteException e) {
  4496. throw e.rethrowFromSystemServer();
  4497. }
  4498. }
  4499. /**
  4500. * @hide
  4501. * @return true if an AudioPolicy was previously registered
  4502. */
  4503. @TestApi
  4504. public boolean hasRegisteredDynamicPolicy() {
  4505. final IAudioService service = getService();
  4506. try {
  4507. return service.hasRegisteredDynamicPolicy();
  4508. } catch (RemoteException e) {
  4509. throw e.rethrowFromSystemServer();
  4510. }
  4511. }
  4512. //====================================================================
  4513. // Notification of playback activity & playback configuration
  4514. /**
  4515. * Interface for receiving update notifications about the playback activity on the system.
  4516. * Extend this abstract class and register it with
  4517. * {@link AudioManager#registerAudioPlaybackCallback(AudioPlaybackCallback, Handler)}
  4518. * to be notified.
  4519. * Use {@link AudioManager#getActivePlaybackConfigurations()} to query the current
  4520. * configuration.
  4521. * @see AudioPlaybackConfiguration
  4522. */
  4523. public static abstract class AudioPlaybackCallback {
  4524. /**
  4525. * Called whenever the playback activity and configuration has changed.
  4526. * @param configs list containing the results of
  4527. * {@link AudioManager#getActivePlaybackConfigurations()}.
  4528. */
  4529. public void onPlaybackConfigChanged(List<AudioPlaybackConfiguration> configs) {}
  4530. }
  4531. private static class AudioPlaybackCallbackInfo {
  4532. final AudioPlaybackCallback mCb;
  4533. final Handler mHandler;
  4534. AudioPlaybackCallbackInfo(AudioPlaybackCallback cb, Handler handler) {
  4535. mCb = cb;
  4536. mHandler = handler;
  4537. }
  4538. }
  4539. private final static class PlaybackConfigChangeCallbackData {
  4540. final AudioPlaybackCallback mCb;
  4541. final List<AudioPlaybackConfiguration> mConfigs;
  4542. PlaybackConfigChangeCallbackData(AudioPlaybackCallback cb,
  4543. List<AudioPlaybackConfiguration> configs) {
  4544. mCb = cb;
  4545. mConfigs = configs;
  4546. }
  4547. }
  4548. /**
  4549. * Register a callback to be notified of audio playback changes through
  4550. * {@link AudioPlaybackCallback}
  4551. * @param cb non-null callback to register
  4552. * @param handler the {@link Handler} object for the thread on which to execute
  4553. * the callback. If <code>null</code>, the {@link Handler} associated with the main
  4554. * {@link Looper} will be used.
  4555. */
  4556. public void registerAudioPlaybackCallback(@NonNull AudioPlaybackCallback cb,
  4557. @Nullable Handler handler)
  4558. {
  4559. if (cb == null) {
  4560. throw new IllegalArgumentException("Illegal null AudioPlaybackCallback argument");
  4561. }
  4562. synchronized(mPlaybackCallbackLock) {
  4563. // lazy initialization of the list of playback callbacks
  4564. if (mPlaybackCallbackList == null) {
  4565. mPlaybackCallbackList = new ArrayList<AudioPlaybackCallbackInfo>();
  4566. }
  4567. final int oldCbCount = mPlaybackCallbackList.size();
  4568. if (!hasPlaybackCallback_sync(cb)) {
  4569. mPlaybackCallbackList.add(new AudioPlaybackCallbackInfo(cb,
  4570. new ServiceEventHandlerDelegate(handler).getHandler()));
  4571. final int newCbCount = mPlaybackCallbackList.size();
  4572. if ((oldCbCount == 0) && (newCbCount > 0)) {
  4573. // register binder for callbacks
  4574. try {
  4575. getService().registerPlaybackCallback(mPlayCb);
  4576. } catch (RemoteException e) {
  4577. throw e.rethrowFromSystemServer();
  4578. }
  4579. }
  4580. } else {
  4581. Log.w(TAG, "attempt to call registerAudioPlaybackCallback() on a previously"
  4582. + "registered callback");
  4583. }
  4584. }
  4585. }
  4586. /**
  4587. * Unregister an audio playback callback previously registered with
  4588. * {@link #registerAudioPlaybackCallback(AudioPlaybackCallback, Handler)}.
  4589. * @param cb non-null callback to unregister
  4590. */
  4591. public void unregisterAudioPlaybackCallback(@NonNull AudioPlaybackCallback cb) {
  4592. if (cb == null) {
  4593. throw new IllegalArgumentException("Illegal null AudioPlaybackCallback argument");
  4594. }
  4595. synchronized(mPlaybackCallbackLock) {
  4596. if (mPlaybackCallbackList == null) {
  4597. Log.w(TAG, "attempt to call unregisterAudioPlaybackCallback() on a callback"
  4598. + " that was never registered");
  4599. return;
  4600. }
  4601. final int oldCbCount = mPlaybackCallbackList.size();
  4602. if (removePlaybackCallback_sync(cb)) {
  4603. final int newCbCount = mPlaybackCallbackList.size();
  4604. if ((oldCbCount > 0) && (newCbCount == 0)) {
  4605. // unregister binder for callbacks
  4606. try {
  4607. getService().unregisterPlaybackCallback(mPlayCb);
  4608. } catch (RemoteException e) {
  4609. throw e.rethrowFromSystemServer();
  4610. }
  4611. }
  4612. } else {
  4613. Log.w(TAG, "attempt to call unregisterAudioPlaybackCallback() on a callback"
  4614. + " already unregistered or never registered");
  4615. }
  4616. }
  4617. }
  4618. /**
  4619. * Returns the current active audio playback configurations of the device
  4620. * @return a non-null list of playback configurations. An empty list indicates there is no
  4621. * playback active when queried.
  4622. * @see AudioPlaybackConfiguration
  4623. */
  4624. public @NonNull List<AudioPlaybackConfiguration> getActivePlaybackConfigurations() {
  4625. final IAudioService service = getService();
  4626. try {
  4627. return service.getActivePlaybackConfigurations();
  4628. } catch (RemoteException e) {
  4629. throw e.rethrowFromSystemServer();
  4630. }
  4631. }
  4632. /**
  4633. * All operations on this list are sync'd on mPlaybackCallbackLock.
  4634. * List is lazy-initialized in
  4635. * {@link #registerAudioPlaybackCallback(AudioPlaybackCallback, Handler)}.
  4636. * List can be null.
  4637. */
  4638. private List<AudioPlaybackCallbackInfo> mPlaybackCallbackList;
  4639. private final Object mPlaybackCallbackLock = new Object();
  4640. /**
  4641. * Must be called synchronized on mPlaybackCallbackLock
  4642. */
  4643. private boolean hasPlaybackCallback_sync(@NonNull AudioPlaybackCallback cb) {
  4644. if (mPlaybackCallbackList != null) {
  4645. for (int i=0 ; i < mPlaybackCallbackList.size() ; i++) {
  4646. if (cb.equals(mPlaybackCallbackList.get(i).mCb)) {
  4647. return true;
  4648. }
  4649. }
  4650. }
  4651. return false;
  4652. }
  4653. /**
  4654. * Must be called synchronized on mPlaybackCallbackLock
  4655. */
  4656. private boolean removePlaybackCallback_sync(@NonNull AudioPlaybackCallback cb) {
  4657. if (mPlaybackCallbackList != null) {
  4658. for (int i=0 ; i < mPlaybackCallbackList.size() ; i++) {
  4659. if (cb.equals(mPlaybackCallbackList.get(i).mCb)) {
  4660. mPlaybackCallbackList.remove(i);
  4661. return true;
  4662. }
  4663. }
  4664. }
  4665. return false;
  4666. }
  4667. private final IPlaybackConfigDispatcher mPlayCb = new IPlaybackConfigDispatcher.Stub() {
  4668. @Override
  4669. public void dispatchPlaybackConfigChange(List<AudioPlaybackConfiguration> configs,
  4670. boolean flush) {
  4671. if (flush) {
  4672. Binder.flushPendingCommands();
  4673. }
  4674. synchronized(mPlaybackCallbackLock) {
  4675. if (mPlaybackCallbackList != null) {
  4676. for (int i=0 ; i < mPlaybackCallbackList.size() ; i++) {
  4677. final AudioPlaybackCallbackInfo arci = mPlaybackCallbackList.get(i);
  4678. if (arci.mHandler != null) {
  4679. final Message m = arci.mHandler.obtainMessage(
  4680. MSSG_PLAYBACK_CONFIG_CHANGE/*what*/,
  4681. new PlaybackConfigChangeCallbackData(arci.mCb, configs)/*obj*/);
  4682. arci.mHandler.sendMessage(m);
  4683. }
  4684. }
  4685. }
  4686. }
  4687. }
  4688. };
  4689. //====================================================================
  4690. // Notification of recording activity & recording configuration
  4691. /**
  4692. * Interface for receiving update notifications about the recording configuration. Extend
  4693. * this abstract class and register it with
  4694. * {@link AudioManager#registerAudioRecordingCallback(AudioRecordingCallback, Handler)}
  4695. * to be notified.
  4696. * Use {@link AudioManager#getActiveRecordingConfigurations()} to query the current
  4697. * configuration.
  4698. * @see AudioRecordingConfiguration
  4699. */
  4700. public static abstract class AudioRecordingCallback {
  4701. /**
  4702. * Called whenever the device recording configuration has changed.
  4703. * @param configs list containing the results of
  4704. * {@link AudioManager#getActiveRecordingConfigurations()}.
  4705. */
  4706. public void onRecordingConfigChanged(List<AudioRecordingConfiguration> configs) {}
  4707. }
  4708. private static class AudioRecordingCallbackInfo {
  4709. final AudioRecordingCallback mCb;
  4710. final Handler mHandler;
  4711. AudioRecordingCallbackInfo(AudioRecordingCallback cb, Handler handler) {
  4712. mCb = cb;
  4713. mHandler = handler;
  4714. }
  4715. }
  4716. private final static class RecordConfigChangeCallbackData {
  4717. final AudioRecordingCallback mCb;
  4718. final List<AudioRecordingConfiguration> mConfigs;
  4719. RecordConfigChangeCallbackData(AudioRecordingCallback cb,
  4720. List<AudioRecordingConfiguration> configs) {
  4721. mCb = cb;
  4722. mConfigs = configs;
  4723. }
  4724. }
  4725. /**
  4726. * Register a callback to be notified of audio recording changes through
  4727. * {@link AudioRecordingCallback}
  4728. * @param cb non-null callback to register
  4729. * @param handler the {@link Handler} object for the thread on which to execute
  4730. * the callback. If <code>null</code>, the {@link Handler} associated with the main
  4731. * {@link Looper} will be used.
  4732. */
  4733. public void registerAudioRecordingCallback(@NonNull AudioRecordingCallback cb,
  4734. @Nullable Handler handler)
  4735. {
  4736. if (cb == null) {
  4737. throw new IllegalArgumentException("Illegal null AudioRecordingCallback argument");
  4738. }
  4739. synchronized(mRecordCallbackLock) {
  4740. // lazy initialization of the list of recording callbacks
  4741. if (mRecordCallbackList == null) {
  4742. mRecordCallbackList = new ArrayList<AudioRecordingCallbackInfo>();
  4743. }
  4744. final int oldCbCount = mRecordCallbackList.size();
  4745. if (!hasRecordCallback_sync(cb)) {
  4746. mRecordCallbackList.add(new AudioRecordingCallbackInfo(cb,
  4747. new ServiceEventHandlerDelegate(handler).getHandler()));
  4748. final int newCbCount = mRecordCallbackList.size();
  4749. if ((oldCbCount == 0) && (newCbCount > 0)) {
  4750. // register binder for callbacks
  4751. final IAudioService service = getService();
  4752. try {
  4753. service.registerRecordingCallback(mRecCb);
  4754. } catch (RemoteException e) {
  4755. throw e.rethrowFromSystemServer();
  4756. }
  4757. }
  4758. } else {
  4759. Log.w(TAG, "attempt to call registerAudioRecordingCallback() on a previously"
  4760. + "registered callback");
  4761. }
  4762. }
  4763. }
  4764. /**
  4765. * Unregister an audio recording callback previously registered with
  4766. * {@link #registerAudioRecordingCallback(AudioRecordingCallback, Handler)}.
  4767. * @param cb non-null callback to unregister
  4768. */
  4769. public void unregisterAudioRecordingCallback(@NonNull AudioRecordingCallback cb) {
  4770. if (cb == null) {
  4771. throw new IllegalArgumentException("Illegal null AudioRecordingCallback argument");
  4772. }
  4773. synchronized(mRecordCallbackLock) {
  4774. if (mRecordCallbackList == null) {
  4775. return;
  4776. }
  4777. final int oldCbCount = mRecordCallbackList.size();
  4778. if (removeRecordCallback_sync(cb)) {
  4779. final int newCbCount = mRecordCallbackList.size();
  4780. if ((oldCbCount > 0) && (newCbCount == 0)) {
  4781. // unregister binder for callbacks
  4782. final IAudioService service = getService();
  4783. try {
  4784. service.unregisterRecordingCallback(mRecCb);
  4785. } catch (RemoteException e) {
  4786. throw e.rethrowFromSystemServer();
  4787. }
  4788. }
  4789. } else {
  4790. Log.w(TAG, "attempt to call unregisterAudioRecordingCallback() on a callback"
  4791. + " already unregistered or never registered");
  4792. }
  4793. }
  4794. }
  4795. /**
  4796. * Returns the current active audio recording configurations of the device.
  4797. * @return a non-null list of recording configurations. An empty list indicates there is
  4798. * no recording active when queried.
  4799. * @see AudioRecordingConfiguration
  4800. */
  4801. public @NonNull List<AudioRecordingConfiguration> getActiveRecordingConfigurations() {
  4802. final IAudioService service = getService();
  4803. try {
  4804. return service.getActiveRecordingConfigurations();
  4805. } catch (RemoteException e) {
  4806. throw e.rethrowFromSystemServer();
  4807. }
  4808. }
  4809. /**
  4810. * constants for the recording events, to keep in sync
  4811. * with frameworks/av/include/media/AudioPolicy.h
  4812. */
  4813. /** @hide */
  4814. public static final int RECORD_CONFIG_EVENT_NONE = -1;
  4815. /** @hide */
  4816. public static final int RECORD_CONFIG_EVENT_START = 0;
  4817. /** @hide */
  4818. public static final int RECORD_CONFIG_EVENT_STOP = 1;
  4819. /** @hide */
  4820. public static final int RECORD_CONFIG_EVENT_UPDATE = 2;
  4821. /** @hide */
  4822. public static final int RECORD_CONFIG_EVENT_RELEASE = 3;
  4823. /**
  4824. * keep in sync with frameworks/native/include/audiomanager/AudioManager.h
  4825. */
  4826. /** @hide */
  4827. public static final int RECORD_RIID_INVALID = -1;
  4828. /** @hide */
  4829. public static final int RECORDER_STATE_STARTED = 0;
  4830. /** @hide */
  4831. public static final int RECORDER_STATE_STOPPED = 1;
  4832. /**
  4833. * All operations on this list are sync'd on mRecordCallbackLock.
  4834. * List is lazy-initialized in
  4835. * {@link #registerAudioRecordingCallback(AudioRecordingCallback, Handler)}.
  4836. * List can be null.
  4837. */
  4838. private List<AudioRecordingCallbackInfo> mRecordCallbackList;
  4839. private final Object mRecordCallbackLock = new Object();
  4840. /**
  4841. * Must be called synchronized on mRecordCallbackLock
  4842. */
  4843. private boolean hasRecordCallback_sync(@NonNull AudioRecordingCallback cb) {
  4844. if (mRecordCallbackList != null) {
  4845. for (int i=0 ; i < mRecordCallbackList.size() ; i++) {
  4846. if (cb.equals(mRecordCallbackList.get(i).mCb)) {
  4847. return true;
  4848. }
  4849. }
  4850. }
  4851. return false;
  4852. }
  4853. /**
  4854. * Must be called synchronized on mRecordCallbackLock
  4855. */
  4856. private boolean removeRecordCallback_sync(@NonNull AudioRecordingCallback cb) {
  4857. if (mRecordCallbackList != null) {
  4858. for (int i=0 ; i < mRecordCallbackList.size() ; i++) {
  4859. if (cb.equals(mRecordCallbackList.get(i).mCb)) {
  4860. mRecordCallbackList.remove(i);
  4861. return true;
  4862. }
  4863. }
  4864. }
  4865. return false;
  4866. }
  4867. private final IRecordingConfigDispatcher mRecCb = new IRecordingConfigDispatcher.Stub() {
  4868. @Override
  4869. public void dispatchRecordingConfigChange(List<AudioRecordingConfiguration> configs) {
  4870. synchronized(mRecordCallbackLock) {
  4871. if (mRecordCallbackList != null) {
  4872. for (int i=0 ; i < mRecordCallbackList.size() ; i++) {
  4873. final AudioRecordingCallbackInfo arci = mRecordCallbackList.get(i);
  4874. if (arci.mHandler != null) {
  4875. final Message m = arci.mHandler.obtainMessage(
  4876. MSSG_RECORDING_CONFIG_CHANGE/*what*/,
  4877. new RecordConfigChangeCallbackData(arci.mCb, configs)/*obj*/);
  4878. arci.mHandler.sendMessage(m);
  4879. }
  4880. }
  4881. }
  4882. }
  4883. }
  4884. };
  4885. //=====================================================================
  4886. /**
  4887. * @hide
  4888. * Reload audio settings. This method is called by Settings backup
  4889. * agent when audio settings are restored and causes the AudioService
  4890. * to read and apply restored settings.
  4891. */
  4892. @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
  4893. public void reloadAudioSettings() {
  4894. final IAudioService service = getService();
  4895. try {
  4896. service.reloadAudioSettings();
  4897. } catch (RemoteException e) {
  4898. throw e.rethrowFromSystemServer();
  4899. }
  4900. }
  4901. /**
  4902. * {@hide}
  4903. */
  4904. private final IBinder mICallBack = new Binder();
  4905. /**
  4906. * Checks whether the phone is in silent mode, with or without vibrate.
  4907. *
  4908. * @return true if phone is in silent mode, with or without vibrate.
  4909. *
  4910. * @see #getRingerMode()
  4911. *
  4912. * @hide pending API Council approval
  4913. */
  4914. @UnsupportedAppUsage
  4915. public boolean isSilentMode() {
  4916. int ringerMode = getRingerMode();
  4917. boolean silentMode =
  4918. (ringerMode == RINGER_MODE_SILENT) ||
  4919. (ringerMode == RINGER_MODE_VIBRATE);
  4920. return silentMode;
  4921. }
  4922. // This section re-defines new output device constants from AudioSystem, because the AudioSystem
  4923. // class is not used by other parts of the framework, which instead use definitions and methods
  4924. // from AudioManager. AudioSystem is an internal class used by AudioManager and AudioService.
  4925. /** @hide
  4926. * The audio device code for representing "no device." */
  4927. public static final int DEVICE_NONE = AudioSystem.DEVICE_NONE;
  4928. /** @hide
  4929. * The audio output device code for the small speaker at the front of the device used
  4930. * when placing calls. Does not refer to an in-ear headphone without attached microphone,
  4931. * such as earbuds, earphones, or in-ear monitors (IEM). Those would be handled as a
  4932. * {@link #DEVICE_OUT_WIRED_HEADPHONE}.
  4933. */
  4934. @UnsupportedAppUsage
  4935. public static final int DEVICE_OUT_EARPIECE = AudioSystem.DEVICE_OUT_EARPIECE;
  4936. /** @hide
  4937. * The audio output device code for the built-in speaker */
  4938. @UnsupportedAppUsage
  4939. public static final int DEVICE_OUT_SPEAKER = AudioSystem.DEVICE_OUT_SPEAKER;
  4940. /** @hide
  4941. * The audio output device code for a wired headset with attached microphone */
  4942. @UnsupportedAppUsage
  4943. public static final int DEVICE_OUT_WIRED_HEADSET = AudioSystem.DEVICE_OUT_WIRED_HEADSET;
  4944. /** @hide
  4945. * The audio output device code for a wired headphone without attached microphone */
  4946. @UnsupportedAppUsage
  4947. public static final int DEVICE_OUT_WIRED_HEADPHONE = AudioSystem.DEVICE_OUT_WIRED_HEADPHONE;
  4948. /** @hide
  4949. * The audio output device code for a USB headphone with attached microphone */
  4950. public static final int DEVICE_OUT_USB_HEADSET = AudioSystem.DEVICE_OUT_USB_HEADSET;
  4951. /** @hide
  4952. * The audio output device code for generic Bluetooth SCO, for voice */
  4953. public static final int DEVICE_OUT_BLUETOOTH_SCO = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
  4954. /** @hide
  4955. * The audio output device code for Bluetooth SCO Headset Profile (HSP) and
  4956. * Hands-Free Profile (HFP), for voice
  4957. */
  4958. @UnsupportedAppUsage
  4959. public static final int DEVICE_OUT_BLUETOOTH_SCO_HEADSET =
  4960. AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
  4961. /** @hide
  4962. * The audio output device code for Bluetooth SCO car audio, for voice */
  4963. public static final int DEVICE_OUT_BLUETOOTH_SCO_CARKIT =
  4964. AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
  4965. /** @hide
  4966. * The audio output device code for generic Bluetooth A2DP, for music */
  4967. @UnsupportedAppUsage
  4968. public static final int DEVICE_OUT_BLUETOOTH_A2DP = AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP;
  4969. /** @hide
  4970. * The audio output device code for Bluetooth A2DP headphones, for music */
  4971. @UnsupportedAppUsage
  4972. public static final int DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES =
  4973. AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
  4974. /** @hide
  4975. * The audio output device code for Bluetooth A2DP external speaker, for music */
  4976. @UnsupportedAppUsage
  4977. public static final int DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER =
  4978. AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
  4979. /** @hide
  4980. * The audio output device code for S/PDIF (legacy) or HDMI
  4981. * Deprecated: replaced by {@link #DEVICE_OUT_HDMI} */
  4982. public static final int DEVICE_OUT_AUX_DIGITAL = AudioSystem.DEVICE_OUT_AUX_DIGITAL;
  4983. /** @hide
  4984. * The audio output device code for HDMI */
  4985. @UnsupportedAppUsage
  4986. public static final int DEVICE_OUT_HDMI = AudioSystem.DEVICE_OUT_HDMI;
  4987. /** @hide
  4988. * The audio output device code for an analog wired headset attached via a
  4989. * docking station
  4990. */
  4991. @UnsupportedAppUsage
  4992. public static final int DEVICE_OUT_ANLG_DOCK_HEADSET = AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
  4993. /** @hide
  4994. * The audio output device code for a digital wired headset attached via a
  4995. * docking station
  4996. */
  4997. @UnsupportedAppUsage
  4998. public static final int DEVICE_OUT_DGTL_DOCK_HEADSET = AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET;
  4999. /** @hide
  5000. * The audio output device code for a USB audio accessory. The accessory is in USB host
  5001. * mode and the Android device in USB device mode
  5002. */
  5003. public static final int DEVICE_OUT_USB_ACCESSORY = AudioSystem.DEVICE_OUT_USB_ACCESSORY;
  5004. /** @hide
  5005. * The audio output device code for a USB audio device. The device is in USB device
  5006. * mode and the Android device in USB host mode
  5007. */
  5008. public static final int DEVICE_OUT_USB_DEVICE = AudioSystem.DEVICE_OUT_USB_DEVICE;
  5009. /** @hide
  5010. * The audio output device code for projection output.
  5011. */
  5012. public static final int DEVICE_OUT_REMOTE_SUBMIX = AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
  5013. /** @hide
  5014. * The audio output device code the telephony voice TX path.
  5015. */
  5016. public static final int DEVICE_OUT_TELEPHONY_TX = AudioSystem.DEVICE_OUT_TELEPHONY_TX;
  5017. /** @hide
  5018. * The audio output device code for an analog jack with line impedance detected.
  5019. */
  5020. public static final int DEVICE_OUT_LINE = AudioSystem.DEVICE_OUT_LINE;
  5021. /** @hide
  5022. * The audio output device code for HDMI Audio Return Channel.
  5023. */
  5024. public static final int DEVICE_OUT_HDMI_ARC = AudioSystem.DEVICE_OUT_HDMI_ARC;
  5025. /** @hide
  5026. * The audio output device code for HDMI enhanced Audio Return Channel.
  5027. */
  5028. public static final int DEVICE_OUT_HDMI_EARC = AudioSystem.DEVICE_OUT_HDMI_EARC;
  5029. /** @hide
  5030. * The audio output device code for S/PDIF digital connection.
  5031. */
  5032. public static final int DEVICE_OUT_SPDIF = AudioSystem.DEVICE_OUT_SPDIF;
  5033. /** @hide
  5034. * The audio output device code for built-in FM transmitter.
  5035. */
  5036. public static final int DEVICE_OUT_FM = AudioSystem.DEVICE_OUT_FM;
  5037. /** @hide
  5038. * The audio output device code for echo reference injection point.
  5039. */
  5040. public static final int DEVICE_OUT_ECHO_CANCELLER = AudioSystem.DEVICE_OUT_ECHO_CANCELLER;
  5041. /** @hide
  5042. * The audio output device code for a BLE audio headset.
  5043. */
  5044. public static final int DEVICE_OUT_BLE_HEADSET = AudioSystem.DEVICE_OUT_BLE_HEADSET;
  5045. /** @hide
  5046. * The audio output device code for a BLE audio speaker.
  5047. */
  5048. public static final int DEVICE_OUT_BLE_SPEAKER = AudioSystem.DEVICE_OUT_BLE_SPEAKER;
  5049. /** @hide
  5050. * This is not used as a returned value from {@link #getDevicesForStream}, but could be
  5051. * used in the future in a set method to select whatever default device is chosen by the
  5052. * platform-specific implementation.
  5053. */
  5054. public static final int DEVICE_OUT_DEFAULT = AudioSystem.DEVICE_OUT_DEFAULT;
  5055. /** @hide
  5056. * The audio input device code for default built-in microphone
  5057. */
  5058. public static final int DEVICE_IN_BUILTIN_MIC = AudioSystem.DEVICE_IN_BUILTIN_MIC;
  5059. /** @hide
  5060. * The audio input device code for a Bluetooth SCO headset
  5061. */
  5062. public static final int DEVICE_IN_BLUETOOTH_SCO_HEADSET =
  5063. AudioSystem.DEVICE_IN_BLUETOOTH_SCO_HEADSET;
  5064. /** @hide
  5065. * The audio input device code for wired headset microphone
  5066. */
  5067. public static final int DEVICE_IN_WIRED_HEADSET =
  5068. AudioSystem.DEVICE_IN_WIRED_HEADSET;
  5069. /** @hide
  5070. * The audio input device code for HDMI
  5071. */
  5072. public static final int DEVICE_IN_HDMI =
  5073. AudioSystem.DEVICE_IN_HDMI;
  5074. /** @hide
  5075. * The audio input device code for HDMI ARC
  5076. */
  5077. public static final int DEVICE_IN_HDMI_ARC =
  5078. AudioSystem.DEVICE_IN_HDMI_ARC;
  5079. /** @hide
  5080. * The audio input device code for HDMI EARC
  5081. */
  5082. public static final int DEVICE_IN_HDMI_EARC =
  5083. AudioSystem.DEVICE_IN_HDMI_EARC;
  5084. /** @hide
  5085. * The audio input device code for telephony voice RX path
  5086. */
  5087. public static final int DEVICE_IN_TELEPHONY_RX =
  5088. AudioSystem.DEVICE_IN_TELEPHONY_RX;
  5089. /** @hide
  5090. * The audio input device code for built-in microphone pointing to the back
  5091. */
  5092. public static final int DEVICE_IN_BACK_MIC =
  5093. AudioSystem.DEVICE_IN_BACK_MIC;
  5094. /** @hide
  5095. * The audio input device code for analog from a docking station
  5096. */
  5097. public static final int DEVICE_IN_ANLG_DOCK_HEADSET =
  5098. AudioSystem.DEVICE_IN_ANLG_DOCK_HEADSET;
  5099. /** @hide
  5100. * The audio input device code for digital from a docking station
  5101. */
  5102. public static final int DEVICE_IN_DGTL_DOCK_HEADSET =
  5103. AudioSystem.DEVICE_IN_DGTL_DOCK_HEADSET;
  5104. /** @hide
  5105. * The audio input device code for a USB audio accessory. The accessory is in USB host
  5106. * mode and the Android device in USB device mode
  5107. */
  5108. public static final int DEVICE_IN_USB_ACCESSORY =
  5109. AudioSystem.DEVICE_IN_USB_ACCESSORY;
  5110. /** @hide
  5111. * The audio input device code for a USB audio device. The device is in USB device
  5112. * mode and the Android device in USB host mode
  5113. */
  5114. public static final int DEVICE_IN_USB_DEVICE =
  5115. AudioSystem.DEVICE_IN_USB_DEVICE;
  5116. /** @hide
  5117. * The audio input device code for a FM radio tuner
  5118. */
  5119. public static final int DEVICE_IN_FM_TUNER = AudioSystem.DEVICE_IN_FM_TUNER;
  5120. /** @hide
  5121. * The audio input device code for a TV tuner
  5122. */
  5123. public static final int DEVICE_IN_TV_TUNER = AudioSystem.DEVICE_IN_TV_TUNER;
  5124. /** @hide
  5125. * The audio input device code for an analog jack with line impedance detected
  5126. */
  5127. public static final int DEVICE_IN_LINE = AudioSystem.DEVICE_IN_LINE;
  5128. /** @hide
  5129. * The audio input device code for a S/PDIF digital connection
  5130. */
  5131. public static final int DEVICE_IN_SPDIF = AudioSystem.DEVICE_IN_SPDIF;
  5132. /** @hide
  5133. * The audio input device code for audio loopback
  5134. */
  5135. public static final int DEVICE_IN_LOOPBACK = AudioSystem.DEVICE_IN_LOOPBACK;
  5136. /** @hide
  5137. * The audio input device code for an echo reference capture point.
  5138. */
  5139. public static final int DEVICE_IN_ECHO_REFERENCE = AudioSystem.DEVICE_IN_ECHO_REFERENCE;
  5140. /** @hide
  5141. * The audio input device code for a BLE audio headset.
  5142. */
  5143. public static final int DEVICE_IN_BLE_HEADSET = AudioSystem.DEVICE_IN_BLE_HEADSET;
  5144. /**
  5145. * Return true if the device code corresponds to an output device.
  5146. * @hide
  5147. */
  5148. public static boolean isOutputDevice(int device)
  5149. {
  5150. return (device & AudioSystem.DEVICE_BIT_IN) == 0;
  5151. }
  5152. /**
  5153. * Return true if the device code corresponds to an input device.
  5154. * @hide
  5155. */
  5156. public static boolean isInputDevice(int device)
  5157. {
  5158. return (device & AudioSystem.DEVICE_BIT_IN) == AudioSystem.DEVICE_BIT_IN;
  5159. }
  5160. /**
  5161. * Return the enabled devices for the specified output stream type.
  5162. *
  5163. * @param streamType The stream type to query. One of
  5164. * {@link #STREAM_VOICE_CALL},
  5165. * {@link #STREAM_SYSTEM},
  5166. * {@link #STREAM_RING},
  5167. * {@link #STREAM_MUSIC},
  5168. * {@link #STREAM_ALARM},
  5169. * {@link #STREAM_NOTIFICATION},
  5170. * {@link #STREAM_DTMF},
  5171. * {@link #STREAM_ACCESSIBILITY}.
  5172. *
  5173. * @return The bit-mask "or" of audio output device codes for all enabled devices on this
  5174. * stream. Zero or more of
  5175. * {@link #DEVICE_OUT_EARPIECE},
  5176. * {@link #DEVICE_OUT_SPEAKER},
  5177. * {@link #DEVICE_OUT_WIRED_HEADSET},
  5178. * {@link #DEVICE_OUT_WIRED_HEADPHONE},
  5179. * {@link #DEVICE_OUT_BLUETOOTH_SCO},
  5180. * {@link #DEVICE_OUT_BLUETOOTH_SCO_HEADSET},
  5181. * {@link #DEVICE_OUT_BLUETOOTH_SCO_CARKIT},
  5182. * {@link #DEVICE_OUT_BLUETOOTH_A2DP},
  5183. * {@link #DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES},
  5184. * {@link #DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER},
  5185. * {@link #DEVICE_OUT_HDMI},
  5186. * {@link #DEVICE_OUT_ANLG_DOCK_HEADSET},
  5187. * {@link #DEVICE_OUT_DGTL_DOCK_HEADSET}.
  5188. * {@link #DEVICE_OUT_USB_ACCESSORY}.
  5189. * {@link #DEVICE_OUT_USB_DEVICE}.
  5190. * {@link #DEVICE_OUT_REMOTE_SUBMIX}.
  5191. * {@link #DEVICE_OUT_TELEPHONY_TX}.
  5192. * {@link #DEVICE_OUT_LINE}.
  5193. * {@link #DEVICE_OUT_HDMI_ARC}.
  5194. * {@link #DEVICE_OUT_HDMI_EARC}.
  5195. * {@link #DEVICE_OUT_SPDIF}.
  5196. * {@link #DEVICE_OUT_FM}.
  5197. * {@link #DEVICE_OUT_DEFAULT} is not used here.
  5198. *
  5199. * The implementation may support additional device codes beyond those listed, so
  5200. * the application should ignore any bits which it does not recognize.
  5201. * Note that the information may be imprecise when the implementation
  5202. * cannot distinguish whether a particular device is enabled.
  5203. *
  5204. * {@hide}
  5205. */
  5206. @UnsupportedAppUsage
  5207. public int getDevicesForStream(int streamType) {
  5208. switch (streamType) {
  5209. case STREAM_VOICE_CALL:
  5210. case STREAM_SYSTEM:
  5211. case STREAM_RING:
  5212. case STREAM_MUSIC:
  5213. case STREAM_ALARM:
  5214. case STREAM_NOTIFICATION:
  5215. case STREAM_DTMF:
  5216. case STREAM_ACCESSIBILITY:
  5217. final IAudioService service = getService();
  5218. try {
  5219. return service.getDevicesForStream(streamType);
  5220. } catch (RemoteException e) {
  5221. throw e.rethrowFromSystemServer();
  5222. }
  5223. default:
  5224. return 0;
  5225. }
  5226. }
  5227. /**
  5228. * @hide
  5229. * Get the audio devices that would be used for the routing of the given audio attributes.
  5230. * @param attributes the {@link AudioAttributes} for which the routing is being queried
  5231. * @return an empty list if there was an issue with the request, a list of audio devices
  5232. * otherwise (typically one device, except for duplicated paths).
  5233. */
  5234. @SystemApi
  5235. @RequiresPermission(anyOf = {
  5236. android.Manifest.permission.MODIFY_AUDIO_ROUTING,
  5237. android.Manifest.permission.QUERY_AUDIO_STATE
  5238. })
  5239. public @NonNull List<AudioDeviceAttributes> getDevicesForAttributes(
  5240. @NonNull AudioAttributes attributes) {
  5241. Objects.requireNonNull(attributes);
  5242. final IAudioService service = getService();
  5243. try {
  5244. return service.getDevicesForAttributes(attributes);
  5245. } catch (RemoteException e) {
  5246. throw e.rethrowFromSystemServer();
  5247. }
  5248. }
  5249. /**
  5250. * @hide
  5251. * Volume behavior for an audio device that has no particular volume behavior set. Invalid as
  5252. * an argument to {@link #setDeviceVolumeBehavior(AudioDeviceAttributes, int)} and should not
  5253. * be returned by {@link #getDeviceVolumeBehavior(AudioDeviceAttributes)}.
  5254. */
  5255. public static final int DEVICE_VOLUME_BEHAVIOR_UNSET = -1;
  5256. /**
  5257. * @hide
  5258. * Volume behavior for an audio device where a software attenuation is applied
  5259. * @see #setDeviceVolumeBehavior(AudioDeviceAttributes, int)
  5260. */
  5261. @SystemApi
  5262. public static final int DEVICE_VOLUME_BEHAVIOR_VARIABLE = 0;
  5263. /**
  5264. * @hide
  5265. * Volume behavior for an audio device where the volume is always set to provide no attenuation
  5266. * nor gain (e.g. unit gain).
  5267. * @see #setDeviceVolumeBehavior(AudioDeviceAttributes, int)
  5268. */
  5269. @SystemApi
  5270. public static final int DEVICE_VOLUME_BEHAVIOR_FULL = 1;
  5271. /**
  5272. * @hide
  5273. * Volume behavior for an audio device where the volume is either set to muted, or to provide
  5274. * no attenuation nor gain (e.g. unit gain).
  5275. * @see #setDeviceVolumeBehavior(AudioDeviceAttributes, int)
  5276. */
  5277. @SystemApi
  5278. public static final int DEVICE_VOLUME_BEHAVIOR_FIXED = 2;
  5279. /**
  5280. * @hide
  5281. * Volume behavior for an audio device where no software attenuation is applied, and
  5282. * the volume is kept synchronized between the host and the device itself through a
  5283. * device-specific protocol such as BT AVRCP.
  5284. * @see #setDeviceVolumeBehavior(AudioDeviceAttributes, int)
  5285. */
  5286. @SystemApi
  5287. public static final int DEVICE_VOLUME_BEHAVIOR_ABSOLUTE = 3;
  5288. /**
  5289. * @hide
  5290. * Volume behavior for an audio device where no software attenuation is applied, and
  5291. * the volume is kept synchronized between the host and the device itself through a
  5292. * device-specific protocol (such as for hearing aids), based on the audio mode (e.g.
  5293. * normal vs in phone call).
  5294. * @see #setMode(int)
  5295. * @see #setDeviceVolumeBehavior(AudioDeviceAttributes, int)
  5296. */
  5297. @SystemApi
  5298. public static final int DEVICE_VOLUME_BEHAVIOR_ABSOLUTE_MULTI_MODE = 4;
  5299. /** @hide */
  5300. @IntDef({
  5301. DEVICE_VOLUME_BEHAVIOR_VARIABLE,
  5302. DEVICE_VOLUME_BEHAVIOR_FULL,
  5303. DEVICE_VOLUME_BEHAVIOR_FIXED,
  5304. DEVICE_VOLUME_BEHAVIOR_ABSOLUTE,
  5305. DEVICE_VOLUME_BEHAVIOR_ABSOLUTE_MULTI_MODE,
  5306. })
  5307. @Retention(RetentionPolicy.SOURCE)
  5308. public @interface DeviceVolumeBehavior {}
  5309. /** @hide */
  5310. @IntDef({
  5311. DEVICE_VOLUME_BEHAVIOR_UNSET,
  5312. DEVICE_VOLUME_BEHAVIOR_VARIABLE,
  5313. DEVICE_VOLUME_BEHAVIOR_FULL,
  5314. DEVICE_VOLUME_BEHAVIOR_FIXED,
  5315. DEVICE_VOLUME_BEHAVIOR_ABSOLUTE,
  5316. DEVICE_VOLUME_BEHAVIOR_ABSOLUTE_MULTI_MODE,
  5317. })
  5318. @Retention(RetentionPolicy.SOURCE)
  5319. public @interface DeviceVolumeBehaviorState {}
  5320. /**
  5321. * @hide
  5322. * Throws IAE on an invalid volume behavior value
  5323. * @param volumeBehavior behavior value to check
  5324. */
  5325. public static void enforceValidVolumeBehavior(int volumeBehavior) {
  5326. switch (volumeBehavior) {
  5327. case DEVICE_VOLUME_BEHAVIOR_VARIABLE:
  5328. case DEVICE_VOLUME_BEHAVIOR_FULL:
  5329. case DEVICE_VOLUME_BEHAVIOR_FIXED:
  5330. case DEVICE_VOLUME_BEHAVIOR_ABSOLUTE:
  5331. case DEVICE_VOLUME_BEHAVIOR_ABSOLUTE_MULTI_MODE:
  5332. return;
  5333. default:
  5334. throw new IllegalArgumentException("Illegal volume behavior " + volumeBehavior);
  5335. }
  5336. }
  5337. /**
  5338. * @hide
  5339. * Sets the volume behavior for an audio output device.
  5340. * @see #DEVICE_VOLUME_BEHAVIOR_VARIABLE
  5341. * @see #DEVICE_VOLUME_BEHAVIOR_FULL
  5342. * @see #DEVICE_VOLUME_BEHAVIOR_FIXED
  5343. * @see #DEVICE_VOLUME_BEHAVIOR_ABSOLUTE
  5344. * @see #DEVICE_VOLUME_BEHAVIOR_ABSOLUTE_MULTI_MODE
  5345. * @param device the device to be affected
  5346. * @param deviceVolumeBehavior one of the device behaviors
  5347. */
  5348. @SystemApi
  5349. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  5350. public void setDeviceVolumeBehavior(@NonNull AudioDeviceAttributes device,
  5351. @DeviceVolumeBehavior int deviceVolumeBehavior) {
  5352. // verify arguments (validity of device type is enforced in server)
  5353. Objects.requireNonNull(device);
  5354. enforceValidVolumeBehavior(deviceVolumeBehavior);
  5355. // communicate with service
  5356. final IAudioService service = getService();
  5357. try {
  5358. service.setDeviceVolumeBehavior(device, deviceVolumeBehavior,
  5359. mApplicationContext.getOpPackageName());
  5360. } catch (RemoteException e) {
  5361. throw e.rethrowFromSystemServer();
  5362. }
  5363. }
  5364. /**
  5365. * @hide
  5366. * Returns the volume device behavior for the given audio device
  5367. * @param device the audio device
  5368. * @return the volume behavior for the device
  5369. */
  5370. @SystemApi
  5371. @RequiresPermission(anyOf = {
  5372. android.Manifest.permission.MODIFY_AUDIO_ROUTING,
  5373. android.Manifest.permission.QUERY_AUDIO_STATE
  5374. })
  5375. public @DeviceVolumeBehavior
  5376. int getDeviceVolumeBehavior(@NonNull AudioDeviceAttributes device) {
  5377. // verify arguments (validity of device type is enforced in server)
  5378. Objects.requireNonNull(device);
  5379. // communicate with service
  5380. final IAudioService service = getService();
  5381. try {
  5382. return service.getDeviceVolumeBehavior(device);
  5383. } catch (RemoteException e) {
  5384. throw e.rethrowFromSystemServer();
  5385. }
  5386. }
  5387. /**
  5388. * @hide
  5389. * Returns {@code true} if the volume device behavior is {@link #DEVICE_VOLUME_BEHAVIOR_FULL}.
  5390. */
  5391. @TestApi
  5392. @RequiresPermission(anyOf = {
  5393. android.Manifest.permission.MODIFY_AUDIO_ROUTING,
  5394. android.Manifest.permission.QUERY_AUDIO_STATE
  5395. })
  5396. public boolean isFullVolumeDevice() {
  5397. final AudioAttributes attributes = new AudioAttributes.Builder()
  5398. .setUsage(AudioAttributes.USAGE_MEDIA)
  5399. .build();
  5400. final List<AudioDeviceAttributes> devices = getDevicesForAttributes(attributes);
  5401. for (AudioDeviceAttributes device : devices) {
  5402. if (getDeviceVolumeBehavior(device) == DEVICE_VOLUME_BEHAVIOR_FULL) {
  5403. return true;
  5404. }
  5405. }
  5406. return false;
  5407. }
  5408. /**
  5409. * Indicate wired accessory connection state change.
  5410. * @param device type of device connected/disconnected (AudioManager.DEVICE_OUT_xxx)
  5411. * @param state new connection state: 1 connected, 0 disconnected
  5412. * @param name device name
  5413. * {@hide}
  5414. */
  5415. @UnsupportedAppUsage
  5416. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  5417. public void setWiredDeviceConnectionState(int type, int state, String address, String name) {
  5418. final IAudioService service = getService();
  5419. try {
  5420. service.setWiredDeviceConnectionState(type, state, address, name,
  5421. mApplicationContext.getOpPackageName());
  5422. } catch (RemoteException e) {
  5423. throw e.rethrowFromSystemServer();
  5424. }
  5425. }
  5426. /**
  5427. * Indicate Hearing Aid connection state change and eventually suppress
  5428. * the {@link AudioManager.ACTION_AUDIO_BECOMING_NOISY} intent.
  5429. * This operation is asynchronous but its execution will still be sequentially scheduled
  5430. * relative to calls to {@link #setBluetoothA2dpDeviceConnectionStateSuppressNoisyIntent(
  5431. * * BluetoothDevice, int, int, boolean, int)} and
  5432. * and {@link #handleBluetoothA2dpDeviceConfigChange(BluetoothDevice)}.
  5433. * @param device Bluetooth device connected/disconnected
  5434. * @param state new connection state (BluetoothProfile.STATE_xxx)
  5435. * @param musicDevice Default get system volume for the connecting device.
  5436. * (either {@link android.bluetooth.BluetoothProfile.hearingaid} or
  5437. * {@link android.bluetooth.BluetoothProfile.HEARING_AID})
  5438. * @param suppressNoisyIntent if true the
  5439. * {@link AudioManager.ACTION_AUDIO_BECOMING_NOISY} intent will not be sent.
  5440. * {@hide}
  5441. */
  5442. public void setBluetoothHearingAidDeviceConnectionState(
  5443. BluetoothDevice device, int state, boolean suppressNoisyIntent,
  5444. int musicDevice) {
  5445. final IAudioService service = getService();
  5446. try {
  5447. service.setBluetoothHearingAidDeviceConnectionState(device,
  5448. state, suppressNoisyIntent, musicDevice);
  5449. } catch (RemoteException e) {
  5450. throw e.rethrowFromSystemServer();
  5451. }
  5452. }
  5453. /**
  5454. * Indicate Le Audio output device connection state change and eventually suppress
  5455. * the {@link AudioManager.ACTION_AUDIO_BECOMING_NOISY} intent.
  5456. * @param device Bluetooth device connected/disconnected
  5457. * @param state new connection state (BluetoothProfile.STATE_xxx)
  5458. * @param suppressNoisyIntent if true the
  5459. * {@link AudioManager.ACTION_AUDIO_BECOMING_NOISY} intent will not be sent.
  5460. * {@hide}
  5461. */
  5462. public void setBluetoothLeAudioOutDeviceConnectionState(BluetoothDevice device, int state,
  5463. boolean suppressNoisyIntent) {
  5464. final IAudioService service = getService();
  5465. try {
  5466. service.setBluetoothLeAudioOutDeviceConnectionState(device, state, suppressNoisyIntent);
  5467. } catch (RemoteException e) {
  5468. throw e.rethrowFromSystemServer();
  5469. }
  5470. }
  5471. /**
  5472. * Indicate Le Audio input connection state change.
  5473. * @param device Bluetooth device connected/disconnected
  5474. * @param state new connection state (BluetoothProfile.STATE_xxx)
  5475. * {@hide}
  5476. */
  5477. public void setBluetoothLeAudioInDeviceConnectionState(BluetoothDevice device, int state) {
  5478. final IAudioService service = getService();
  5479. try {
  5480. service.setBluetoothLeAudioInDeviceConnectionState(device, state);
  5481. } catch (RemoteException e) {
  5482. throw e.rethrowFromSystemServer();
  5483. }
  5484. }
  5485. /**
  5486. * Indicate A2DP source or sink connection state change and eventually suppress
  5487. * the {@link AudioManager.ACTION_AUDIO_BECOMING_NOISY} intent.
  5488. * This operation is asynchronous but its execution will still be sequentially scheduled
  5489. * relative to calls to {@link #setBluetoothHearingAidDeviceConnectionState(BluetoothDevice,
  5490. * int, boolean, int)} and
  5491. * {@link #handleBluetoothA2dpDeviceConfigChange(BluetoothDevice)}.
  5492. * @param device Bluetooth device connected/disconnected
  5493. * @param state new connection state, {@link BluetoothProfile#STATE_CONNECTED}
  5494. * or {@link BluetoothProfile#STATE_DISCONNECTED}
  5495. * @param profile profile for the A2DP device
  5496. * @param a2dpVolume New volume for the connecting device. Does nothing if disconnecting.
  5497. * (either {@link android.bluetooth.BluetoothProfile.A2DP} or
  5498. * {@link android.bluetooth.BluetoothProfile.A2DP_SINK})
  5499. * @param suppressNoisyIntent if true the
  5500. * {@link AudioManager.ACTION_AUDIO_BECOMING_NOISY} intent will not be sent.
  5501. * {@hide}
  5502. */
  5503. public void setBluetoothA2dpDeviceConnectionStateSuppressNoisyIntent(
  5504. BluetoothDevice device, int state,
  5505. int profile, boolean suppressNoisyIntent, int a2dpVolume) {
  5506. final IAudioService service = getService();
  5507. try {
  5508. service.setBluetoothA2dpDeviceConnectionStateSuppressNoisyIntent(device,
  5509. state, profile, suppressNoisyIntent, a2dpVolume);
  5510. } catch (RemoteException e) {
  5511. throw e.rethrowFromSystemServer();
  5512. }
  5513. }
  5514. /**
  5515. * Indicate A2DP device configuration has changed.
  5516. * This operation is asynchronous but its execution will still be sequentially scheduled
  5517. * relative to calls to
  5518. * {@link #setBluetoothA2dpDeviceConnectionStateSuppressNoisyIntent(BluetoothDevice, int, int,
  5519. * boolean, int)} and
  5520. * {@link #setBluetoothHearingAidDeviceConnectionState(BluetoothDevice, int, boolean, int)}
  5521. * @param device Bluetooth device whose configuration has changed.
  5522. * {@hide}
  5523. */
  5524. public void handleBluetoothA2dpDeviceConfigChange(BluetoothDevice device) {
  5525. final IAudioService service = getService();
  5526. try {
  5527. service.handleBluetoothA2dpDeviceConfigChange(device);
  5528. } catch (RemoteException e) {
  5529. throw e.rethrowFromSystemServer();
  5530. }
  5531. }
  5532. /** {@hide} */
  5533. public IRingtonePlayer getRingtonePlayer() {
  5534. try {
  5535. return getService().getRingtonePlayer();
  5536. } catch (RemoteException e) {
  5537. throw e.rethrowFromSystemServer();
  5538. }
  5539. }
  5540. /**
  5541. * Used as a key for {@link #getProperty} to request the native or optimal output sample rate
  5542. * for this device's low latency output stream, in decimal Hz. Latency-sensitive apps
  5543. * should use this value as a default, and offer the user the option to override it.
  5544. * The low latency output stream is typically either the device's primary output stream,
  5545. * or another output stream with smaller buffers.
  5546. */
  5547. // FIXME Deprecate
  5548. public static final String PROPERTY_OUTPUT_SAMPLE_RATE =
  5549. "android.media.property.OUTPUT_SAMPLE_RATE";
  5550. /**
  5551. * Used as a key for {@link #getProperty} to request the native or optimal output buffer size
  5552. * for this device's low latency output stream, in decimal PCM frames. Latency-sensitive apps
  5553. * should use this value as a minimum, and offer the user the option to override it.
  5554. * The low latency output stream is typically either the device's primary output stream,
  5555. * or another output stream with smaller buffers.
  5556. */
  5557. // FIXME Deprecate
  5558. public static final String PROPERTY_OUTPUT_FRAMES_PER_BUFFER =
  5559. "android.media.property.OUTPUT_FRAMES_PER_BUFFER";
  5560. /**
  5561. * Used as a key for {@link #getProperty} to determine if the default microphone audio source
  5562. * supports near-ultrasound frequencies (range of 18 - 21 kHz).
  5563. */
  5564. public static final String PROPERTY_SUPPORT_MIC_NEAR_ULTRASOUND =
  5565. "android.media.property.SUPPORT_MIC_NEAR_ULTRASOUND";
  5566. /**
  5567. * Used as a key for {@link #getProperty} to determine if the default speaker audio path
  5568. * supports near-ultrasound frequencies (range of 18 - 21 kHz).
  5569. */
  5570. public static final String PROPERTY_SUPPORT_SPEAKER_NEAR_ULTRASOUND =
  5571. "android.media.property.SUPPORT_SPEAKER_NEAR_ULTRASOUND";
  5572. /**
  5573. * Used as a key for {@link #getProperty} to determine if the unprocessed audio source is
  5574. * available and supported with the expected frequency range and level response.
  5575. */
  5576. public static final String PROPERTY_SUPPORT_AUDIO_SOURCE_UNPROCESSED =
  5577. "android.media.property.SUPPORT_AUDIO_SOURCE_UNPROCESSED";
  5578. /**
  5579. * Returns the value of the property with the specified key.
  5580. * @param key One of the strings corresponding to a property key: either
  5581. * {@link #PROPERTY_OUTPUT_SAMPLE_RATE},
  5582. * {@link #PROPERTY_OUTPUT_FRAMES_PER_BUFFER},
  5583. * {@link #PROPERTY_SUPPORT_MIC_NEAR_ULTRASOUND},
  5584. * {@link #PROPERTY_SUPPORT_SPEAKER_NEAR_ULTRASOUND}, or
  5585. * {@link #PROPERTY_SUPPORT_AUDIO_SOURCE_UNPROCESSED}.
  5586. * @return A string representing the associated value for that property key,
  5587. * or null if there is no value for that key.
  5588. */
  5589. public String getProperty(String key) {
  5590. if (PROPERTY_OUTPUT_SAMPLE_RATE.equals(key)) {
  5591. int outputSampleRate = AudioSystem.getPrimaryOutputSamplingRate();
  5592. return outputSampleRate > 0 ? Integer.toString(outputSampleRate) : null;
  5593. } else if (PROPERTY_OUTPUT_FRAMES_PER_BUFFER.equals(key)) {
  5594. int outputFramesPerBuffer = AudioSystem.getPrimaryOutputFrameCount();
  5595. return outputFramesPerBuffer > 0 ? Integer.toString(outputFramesPerBuffer) : null;
  5596. } else if (PROPERTY_SUPPORT_MIC_NEAR_ULTRASOUND.equals(key)) {
  5597. // Will throw a RuntimeException Resources.NotFoundException if this config value is
  5598. // not found.
  5599. return String.valueOf(getContext().getResources().getBoolean(
  5600. com.android.internal.R.bool.config_supportMicNearUltrasound));
  5601. } else if (PROPERTY_SUPPORT_SPEAKER_NEAR_ULTRASOUND.equals(key)) {
  5602. return String.valueOf(getContext().getResources().getBoolean(
  5603. com.android.internal.R.bool.config_supportSpeakerNearUltrasound));
  5604. } else if (PROPERTY_SUPPORT_AUDIO_SOURCE_UNPROCESSED.equals(key)) {
  5605. return String.valueOf(getContext().getResources().getBoolean(
  5606. com.android.internal.R.bool.config_supportAudioSourceUnprocessed));
  5607. } else {
  5608. // null or unknown key
  5609. return null;
  5610. }
  5611. }
  5612. /**
  5613. * @hide
  5614. * Sets an additional audio output device delay in milliseconds.
  5615. *
  5616. * The additional output delay is a request to the output device to
  5617. * delay audio presentation (generally with respect to video presentation for better
  5618. * synchronization).
  5619. * It may not be supported by all output devices,
  5620. * and typically increases the audio latency by the amount of additional
  5621. * audio delay requested.
  5622. *
  5623. * If additional audio delay is supported by an audio output device,
  5624. * it is expected to be supported for all output streams (and configurations)
  5625. * opened on that device.
  5626. *
  5627. * @param device an instance of {@link AudioDeviceInfo} returned from {@link getDevices()}.
  5628. * @param delayMillis delay in milliseconds desired. This should be in range of {@code 0}
  5629. * to the value returned by {@link #getMaxAdditionalOutputDeviceDelay()}.
  5630. * @return true if successful, false if the device does not support output device delay
  5631. * or the delay is not in range of {@link #getMaxAdditionalOutputDeviceDelay()}.
  5632. */
  5633. @SystemApi
  5634. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  5635. public boolean setAdditionalOutputDeviceDelay(
  5636. @NonNull AudioDeviceInfo device, @IntRange(from = 0) long delayMillis) {
  5637. Objects.requireNonNull(device);
  5638. try {
  5639. return getService().setAdditionalOutputDeviceDelay(
  5640. new AudioDeviceAttributes(device), delayMillis);
  5641. } catch (RemoteException e) {
  5642. throw e.rethrowFromSystemServer();
  5643. }
  5644. }
  5645. /**
  5646. * @hide
  5647. * Returns the current additional audio output device delay in milliseconds.
  5648. *
  5649. * @param device an instance of {@link AudioDeviceInfo} returned from {@link getDevices()}.
  5650. * @return the additional output device delay. This is a non-negative number.
  5651. * {@code 0} is returned if unsupported.
  5652. */
  5653. @SystemApi
  5654. @IntRange(from = 0)
  5655. public long getAdditionalOutputDeviceDelay(@NonNull AudioDeviceInfo device) {
  5656. Objects.requireNonNull(device);
  5657. try {
  5658. return getService().getAdditionalOutputDeviceDelay(new AudioDeviceAttributes(device));
  5659. } catch (RemoteException e) {
  5660. throw e.rethrowFromSystemServer();
  5661. }
  5662. }
  5663. /**
  5664. * @hide
  5665. * Returns the maximum additional audio output device delay in milliseconds.
  5666. *
  5667. * @param device an instance of {@link AudioDeviceInfo} returned from {@link getDevices()}.
  5668. * @return the maximum output device delay in milliseconds that can be set.
  5669. * This is a non-negative number
  5670. * representing the additional audio delay supported for the device.
  5671. * {@code 0} is returned if unsupported.
  5672. */
  5673. @SystemApi
  5674. @IntRange(from = 0)
  5675. public long getMaxAdditionalOutputDeviceDelay(@NonNull AudioDeviceInfo device) {
  5676. Objects.requireNonNull(device);
  5677. try {
  5678. return getService().getMaxAdditionalOutputDeviceDelay(
  5679. new AudioDeviceAttributes(device));
  5680. } catch (RemoteException e) {
  5681. throw e.rethrowFromSystemServer();
  5682. }
  5683. }
  5684. /**
  5685. * Returns the estimated latency for the given stream type in milliseconds.
  5686. *
  5687. * DO NOT UNHIDE. The existing approach for doing A/V sync has too many problems. We need
  5688. * a better solution.
  5689. * @hide
  5690. */
  5691. @UnsupportedAppUsage
  5692. public int getOutputLatency(int streamType) {
  5693. return AudioSystem.getOutputLatency(streamType);
  5694. }
  5695. /**
  5696. * Registers a global volume controller interface. Currently limited to SystemUI.
  5697. *
  5698. * @hide
  5699. */
  5700. public void setVolumeController(IVolumeController controller) {
  5701. try {
  5702. getService().setVolumeController(controller);
  5703. } catch (RemoteException e) {
  5704. throw e.rethrowFromSystemServer();
  5705. }
  5706. }
  5707. /**
  5708. * Notify audio manager about volume controller visibility changes.
  5709. * Currently limited to SystemUI.
  5710. *
  5711. * @hide
  5712. */
  5713. public void notifyVolumeControllerVisible(IVolumeController controller, boolean visible) {
  5714. try {
  5715. getService().notifyVolumeControllerVisible(controller, visible);
  5716. } catch (RemoteException e) {
  5717. throw e.rethrowFromSystemServer();
  5718. }
  5719. }
  5720. /**
  5721. * Only useful for volume controllers.
  5722. * @hide
  5723. */
  5724. public boolean isStreamAffectedByRingerMode(int streamType) {
  5725. try {
  5726. return getService().isStreamAffectedByRingerMode(streamType);
  5727. } catch (RemoteException e) {
  5728. throw e.rethrowFromSystemServer();
  5729. }
  5730. }
  5731. /**
  5732. * Only useful for volume controllers.
  5733. * @hide
  5734. */
  5735. public boolean isStreamAffectedByMute(int streamType) {
  5736. try {
  5737. return getService().isStreamAffectedByMute(streamType);
  5738. } catch (RemoteException e) {
  5739. throw e.rethrowFromSystemServer();
  5740. }
  5741. }
  5742. /**
  5743. * Only useful for volume controllers.
  5744. * @hide
  5745. */
  5746. public void disableSafeMediaVolume() {
  5747. try {
  5748. getService().disableSafeMediaVolume(mApplicationContext.getOpPackageName());
  5749. } catch (RemoteException e) {
  5750. throw e.rethrowFromSystemServer();
  5751. }
  5752. }
  5753. /**
  5754. * Only useful for volume controllers.
  5755. * @hide
  5756. */
  5757. @UnsupportedAppUsage
  5758. public void setRingerModeInternal(int ringerMode) {
  5759. try {
  5760. getService().setRingerModeInternal(ringerMode, getContext().getOpPackageName());
  5761. } catch (RemoteException e) {
  5762. throw e.rethrowFromSystemServer();
  5763. }
  5764. }
  5765. /**
  5766. * Only useful for volume controllers.
  5767. * @hide
  5768. */
  5769. @UnsupportedAppUsage
  5770. public int getRingerModeInternal() {
  5771. try {
  5772. return getService().getRingerModeInternal();
  5773. } catch (RemoteException e) {
  5774. throw e.rethrowFromSystemServer();
  5775. }
  5776. }
  5777. /**
  5778. * Only useful for volume controllers.
  5779. * @hide
  5780. */
  5781. public void setVolumePolicy(VolumePolicy policy) {
  5782. try {
  5783. getService().setVolumePolicy(policy);
  5784. } catch (RemoteException e) {
  5785. throw e.rethrowFromSystemServer();
  5786. }
  5787. }
  5788. /**
  5789. * Set Hdmi Cec system audio mode.
  5790. *
  5791. * @param on whether to be on system audio mode
  5792. * @return output device type. 0 (DEVICE_NONE) if failed to set device.
  5793. * @hide
  5794. */
  5795. public int setHdmiSystemAudioSupported(boolean on) {
  5796. try {
  5797. return getService().setHdmiSystemAudioSupported(on);
  5798. } catch (RemoteException e) {
  5799. throw e.rethrowFromSystemServer();
  5800. }
  5801. }
  5802. /**
  5803. * Returns true if Hdmi Cec system audio mode is supported.
  5804. *
  5805. * @hide
  5806. */
  5807. @SystemApi
  5808. @SuppressLint("RequiresPermission") // FIXME is this still used?
  5809. public boolean isHdmiSystemAudioSupported() {
  5810. try {
  5811. return getService().isHdmiSystemAudioSupported();
  5812. } catch (RemoteException e) {
  5813. throw e.rethrowFromSystemServer();
  5814. }
  5815. }
  5816. /**
  5817. * Return codes for listAudioPorts(), createAudioPatch() ...
  5818. */
  5819. /** @hide */
  5820. @SystemApi
  5821. public static final int SUCCESS = AudioSystem.SUCCESS;
  5822. /**
  5823. * A default error code.
  5824. */
  5825. public static final int ERROR = AudioSystem.ERROR;
  5826. /** @hide
  5827. * CANDIDATE FOR PUBLIC API
  5828. */
  5829. public static final int ERROR_BAD_VALUE = AudioSystem.BAD_VALUE;
  5830. /** @hide
  5831. */
  5832. public static final int ERROR_INVALID_OPERATION = AudioSystem.INVALID_OPERATION;
  5833. /** @hide
  5834. */
  5835. public static final int ERROR_PERMISSION_DENIED = AudioSystem.PERMISSION_DENIED;
  5836. /** @hide
  5837. */
  5838. public static final int ERROR_NO_INIT = AudioSystem.NO_INIT;
  5839. /**
  5840. * An error code indicating that the object reporting it is no longer valid and needs to
  5841. * be recreated.
  5842. */
  5843. public static final int ERROR_DEAD_OBJECT = AudioSystem.DEAD_OBJECT;
  5844. /**
  5845. * Returns a list of descriptors for all audio ports managed by the audio framework.
  5846. * Audio ports are nodes in the audio framework or audio hardware that can be configured
  5847. * or connected and disconnected with createAudioPatch() or releaseAudioPatch().
  5848. * See AudioPort for a list of attributes of each audio port.
  5849. * @param ports An AudioPort ArrayList where the list will be returned.
  5850. * @hide
  5851. */
  5852. @UnsupportedAppUsage
  5853. public static int listAudioPorts(ArrayList<AudioPort> ports) {
  5854. return updateAudioPortCache(ports, null, null);
  5855. }
  5856. /**
  5857. * Returns a list of descriptors for all audio ports managed by the audio framework as
  5858. * it was before the last update calback.
  5859. * @param ports An AudioPort ArrayList where the list will be returned.
  5860. * @hide
  5861. */
  5862. public static int listPreviousAudioPorts(ArrayList<AudioPort> ports) {
  5863. return updateAudioPortCache(null, null, ports);
  5864. }
  5865. /**
  5866. * Specialized version of listAudioPorts() listing only audio devices (AudioDevicePort)
  5867. * @see listAudioPorts(ArrayList<AudioPort>)
  5868. * @hide
  5869. */
  5870. public static int listAudioDevicePorts(ArrayList<AudioDevicePort> devices) {
  5871. if (devices == null) {
  5872. return ERROR_BAD_VALUE;
  5873. }
  5874. ArrayList<AudioPort> ports = new ArrayList<AudioPort>();
  5875. int status = updateAudioPortCache(ports, null, null);
  5876. if (status == SUCCESS) {
  5877. filterDevicePorts(ports, devices);
  5878. }
  5879. return status;
  5880. }
  5881. /**
  5882. * Specialized version of listPreviousAudioPorts() listing only audio devices (AudioDevicePort)
  5883. * @see listPreviousAudioPorts(ArrayList<AudioPort>)
  5884. * @hide
  5885. */
  5886. public static int listPreviousAudioDevicePorts(ArrayList<AudioDevicePort> devices) {
  5887. if (devices == null) {
  5888. return ERROR_BAD_VALUE;
  5889. }
  5890. ArrayList<AudioPort> ports = new ArrayList<AudioPort>();
  5891. int status = updateAudioPortCache(null, null, ports);
  5892. if (status == SUCCESS) {
  5893. filterDevicePorts(ports, devices);
  5894. }
  5895. return status;
  5896. }
  5897. private static void filterDevicePorts(ArrayList<AudioPort> ports,
  5898. ArrayList<AudioDevicePort> devices) {
  5899. devices.clear();
  5900. for (int i = 0; i < ports.size(); i++) {
  5901. if (ports.get(i) instanceof AudioDevicePort) {
  5902. devices.add((AudioDevicePort)ports.get(i));
  5903. }
  5904. }
  5905. }
  5906. /**
  5907. * Create a connection between two or more devices. The framework will reject the request if
  5908. * device types are not compatible or the implementation does not support the requested
  5909. * configuration.
  5910. * NOTE: current implementation is limited to one source and one sink per patch.
  5911. * @param patch AudioPatch array where the newly created patch will be returned.
  5912. * As input, if patch[0] is not null, the specified patch will be replaced by the
  5913. * new patch created. This avoids calling releaseAudioPatch() when modifying a
  5914. * patch and allows the implementation to optimize transitions.
  5915. * @param sources List of source audio ports. All must be AudioPort.ROLE_SOURCE.
  5916. * @param sinks List of sink audio ports. All must be AudioPort.ROLE_SINK.
  5917. *
  5918. * @return - {@link #SUCCESS} if connection is successful.
  5919. * - {@link #ERROR_BAD_VALUE} if incompatible device types are passed.
  5920. * - {@link #ERROR_INVALID_OPERATION} if the requested connection is not supported.
  5921. * - {@link #ERROR_PERMISSION_DENIED} if the client does not have permission to create
  5922. * a patch.
  5923. * - {@link #ERROR_DEAD_OBJECT} if the server process is dead
  5924. * - {@link #ERROR} if patch cannot be connected for any other reason.
  5925. *
  5926. * patch[0] contains the newly created patch
  5927. * @hide
  5928. */
  5929. @UnsupportedAppUsage
  5930. public static int createAudioPatch(AudioPatch[] patch,
  5931. AudioPortConfig[] sources,
  5932. AudioPortConfig[] sinks) {
  5933. return AudioSystem.createAudioPatch(patch, sources, sinks);
  5934. }
  5935. /**
  5936. * Releases an existing audio patch connection.
  5937. * @param patch The audio patch to disconnect.
  5938. * @return - {@link #SUCCESS} if disconnection is successful.
  5939. * - {@link #ERROR_BAD_VALUE} if the specified patch does not exist.
  5940. * - {@link #ERROR_PERMISSION_DENIED} if the client does not have permission to release
  5941. * a patch.
  5942. * - {@link #ERROR_DEAD_OBJECT} if the server process is dead
  5943. * - {@link #ERROR} if patch cannot be released for any other reason.
  5944. * @hide
  5945. */
  5946. @UnsupportedAppUsage
  5947. public static int releaseAudioPatch(AudioPatch patch) {
  5948. return AudioSystem.releaseAudioPatch(patch);
  5949. }
  5950. /**
  5951. * List all existing connections between audio ports.
  5952. * @param patches An AudioPatch array where the list will be returned.
  5953. * @hide
  5954. */
  5955. @UnsupportedAppUsage
  5956. public static int listAudioPatches(ArrayList<AudioPatch> patches) {
  5957. return updateAudioPortCache(null, patches, null);
  5958. }
  5959. /**
  5960. * Set the gain on the specified AudioPort. The AudioGainConfig config is build by
  5961. * AudioGain.buildConfig()
  5962. * @hide
  5963. */
  5964. public static int setAudioPortGain(AudioPort port, AudioGainConfig gain) {
  5965. if (port == null || gain == null) {
  5966. return ERROR_BAD_VALUE;
  5967. }
  5968. AudioPortConfig activeConfig = port.activeConfig();
  5969. AudioPortConfig config = new AudioPortConfig(port, activeConfig.samplingRate(),
  5970. activeConfig.channelMask(), activeConfig.format(), gain);
  5971. config.mConfigMask = AudioPortConfig.GAIN;
  5972. return AudioSystem.setAudioPortConfig(config);
  5973. }
  5974. /**
  5975. * Listener registered by client to be notified upon new audio port connections,
  5976. * disconnections or attributes update.
  5977. * @hide
  5978. */
  5979. public interface OnAudioPortUpdateListener {
  5980. /**
  5981. * Callback method called upon audio port list update.
  5982. * @param portList the updated list of audio ports
  5983. */
  5984. public void onAudioPortListUpdate(AudioPort[] portList);
  5985. /**
  5986. * Callback method called upon audio patch list update.
  5987. * @param patchList the updated list of audio patches
  5988. */
  5989. public void onAudioPatchListUpdate(AudioPatch[] patchList);
  5990. /**
  5991. * Callback method called when the mediaserver dies
  5992. */
  5993. public void onServiceDied();
  5994. }
  5995. /**
  5996. * Register an audio port list update listener.
  5997. * @hide
  5998. */
  5999. @UnsupportedAppUsage
  6000. public void registerAudioPortUpdateListener(OnAudioPortUpdateListener l) {
  6001. sAudioPortEventHandler.init();
  6002. sAudioPortEventHandler.registerListener(l);
  6003. }
  6004. /**
  6005. * Unregister an audio port list update listener.
  6006. * @hide
  6007. */
  6008. @UnsupportedAppUsage
  6009. public void unregisterAudioPortUpdateListener(OnAudioPortUpdateListener l) {
  6010. sAudioPortEventHandler.unregisterListener(l);
  6011. }
  6012. //
  6013. // AudioPort implementation
  6014. //
  6015. static final int AUDIOPORT_GENERATION_INIT = 0;
  6016. static Integer sAudioPortGeneration = new Integer(AUDIOPORT_GENERATION_INIT);
  6017. static ArrayList<AudioPort> sAudioPortsCached = new ArrayList<AudioPort>();
  6018. static ArrayList<AudioPort> sPreviousAudioPortsCached = new ArrayList<AudioPort>();
  6019. static ArrayList<AudioPatch> sAudioPatchesCached = new ArrayList<AudioPatch>();
  6020. static int resetAudioPortGeneration() {
  6021. int generation;
  6022. synchronized (sAudioPortGeneration) {
  6023. generation = sAudioPortGeneration;
  6024. sAudioPortGeneration = AUDIOPORT_GENERATION_INIT;
  6025. }
  6026. return generation;
  6027. }
  6028. static int updateAudioPortCache(ArrayList<AudioPort> ports, ArrayList<AudioPatch> patches,
  6029. ArrayList<AudioPort> previousPorts) {
  6030. sAudioPortEventHandler.init();
  6031. synchronized (sAudioPortGeneration) {
  6032. if (sAudioPortGeneration == AUDIOPORT_GENERATION_INIT) {
  6033. int[] patchGeneration = new int[1];
  6034. int[] portGeneration = new int[1];
  6035. int status;
  6036. ArrayList<AudioPort> newPorts = new ArrayList<AudioPort>();
  6037. ArrayList<AudioPatch> newPatches = new ArrayList<AudioPatch>();
  6038. do {
  6039. newPorts.clear();
  6040. status = AudioSystem.listAudioPorts(newPorts, portGeneration);
  6041. if (status != SUCCESS) {
  6042. Log.w(TAG, "updateAudioPortCache: listAudioPorts failed");
  6043. return status;
  6044. }
  6045. newPatches.clear();
  6046. status = AudioSystem.listAudioPatches(newPatches, patchGeneration);
  6047. if (status != SUCCESS) {
  6048. Log.w(TAG, "updateAudioPortCache: listAudioPatches failed");
  6049. return status;
  6050. }
  6051. // Loop until patch generation is the same as port generation unless audio ports
  6052. // and audio patches are not null.
  6053. } while (patchGeneration[0] != portGeneration[0]
  6054. && (ports == null || patches == null));
  6055. // If the patch generation doesn't equal port generation, return ERROR here in case
  6056. // of mismatch between audio ports and audio patches.
  6057. if (patchGeneration[0] != portGeneration[0]) {
  6058. return ERROR;
  6059. }
  6060. for (int i = 0; i < newPatches.size(); i++) {
  6061. for (int j = 0; j < newPatches.get(i).sources().length; j++) {
  6062. AudioPortConfig portCfg = updatePortConfig(newPatches.get(i).sources()[j],
  6063. newPorts);
  6064. newPatches.get(i).sources()[j] = portCfg;
  6065. }
  6066. for (int j = 0; j < newPatches.get(i).sinks().length; j++) {
  6067. AudioPortConfig portCfg = updatePortConfig(newPatches.get(i).sinks()[j],
  6068. newPorts);
  6069. newPatches.get(i).sinks()[j] = portCfg;
  6070. }
  6071. }
  6072. for (Iterator<AudioPatch> i = newPatches.iterator(); i.hasNext(); ) {
  6073. AudioPatch newPatch = i.next();
  6074. boolean hasInvalidPort = false;
  6075. for (AudioPortConfig portCfg : newPatch.sources()) {
  6076. if (portCfg == null) {
  6077. hasInvalidPort = true;
  6078. break;
  6079. }
  6080. }
  6081. for (AudioPortConfig portCfg : newPatch.sinks()) {
  6082. if (portCfg == null) {
  6083. hasInvalidPort = true;
  6084. break;
  6085. }
  6086. }
  6087. if (hasInvalidPort) {
  6088. // Temporarily remove patches with invalid ports. One who created the patch
  6089. // is responsible for dealing with the port change.
  6090. i.remove();
  6091. }
  6092. }
  6093. sPreviousAudioPortsCached = sAudioPortsCached;
  6094. sAudioPortsCached = newPorts;
  6095. sAudioPatchesCached = newPatches;
  6096. sAudioPortGeneration = portGeneration[0];
  6097. }
  6098. if (ports != null) {
  6099. ports.clear();
  6100. ports.addAll(sAudioPortsCached);
  6101. }
  6102. if (patches != null) {
  6103. patches.clear();
  6104. patches.addAll(sAudioPatchesCached);
  6105. }
  6106. if (previousPorts != null) {
  6107. previousPorts.clear();
  6108. previousPorts.addAll(sPreviousAudioPortsCached);
  6109. }
  6110. }
  6111. return SUCCESS;
  6112. }
  6113. static AudioPortConfig updatePortConfig(AudioPortConfig portCfg, ArrayList<AudioPort> ports) {
  6114. AudioPort port = portCfg.port();
  6115. int k;
  6116. for (k = 0; k < ports.size(); k++) {
  6117. // compare handles because the port returned by JNI is not of the correct
  6118. // subclass
  6119. if (ports.get(k).handle().equals(port.handle())) {
  6120. port = ports.get(k);
  6121. break;
  6122. }
  6123. }
  6124. if (k == ports.size()) {
  6125. // this hould never happen
  6126. Log.e(TAG, "updatePortConfig port not found for handle: "+port.handle().id());
  6127. return null;
  6128. }
  6129. AudioGainConfig gainCfg = portCfg.gain();
  6130. if (gainCfg != null) {
  6131. AudioGain gain = port.gain(gainCfg.index());
  6132. gainCfg = gain.buildConfig(gainCfg.mode(),
  6133. gainCfg.channelMask(),
  6134. gainCfg.values(),
  6135. gainCfg.rampDurationMs());
  6136. }
  6137. return port.buildConfig(portCfg.samplingRate(),
  6138. portCfg.channelMask(),
  6139. portCfg.format(),
  6140. gainCfg);
  6141. }
  6142. private OnAmPortUpdateListener mPortListener = null;
  6143. /**
  6144. * The message sent to apps when the contents of the device list changes if they provide
  6145. * a {@link Handler} object to addOnAudioDeviceConnectionListener().
  6146. */
  6147. private final static int MSG_DEVICES_CALLBACK_REGISTERED = 0;
  6148. private final static int MSG_DEVICES_DEVICES_ADDED = 1;
  6149. private final static int MSG_DEVICES_DEVICES_REMOVED = 2;
  6150. /**
  6151. * The list of {@link AudioDeviceCallback} objects to receive add/remove notifications.
  6152. */
  6153. private final ArrayMap<AudioDeviceCallback, NativeEventHandlerDelegate> mDeviceCallbacks =
  6154. new ArrayMap<AudioDeviceCallback, NativeEventHandlerDelegate>();
  6155. /**
  6156. * The following are flags to allow users of {@link AudioManager#getDevices(int)} to filter
  6157. * the results list to only those device types they are interested in.
  6158. */
  6159. /**
  6160. * Specifies to the {@link AudioManager#getDevices(int)} method to include
  6161. * source (i.e. input) audio devices.
  6162. */
  6163. public static final int GET_DEVICES_INPUTS = 0x0001;
  6164. /**
  6165. * Specifies to the {@link AudioManager#getDevices(int)} method to include
  6166. * sink (i.e. output) audio devices.
  6167. */
  6168. public static final int GET_DEVICES_OUTPUTS = 0x0002;
  6169. /** @hide */
  6170. @IntDef(flag = true, prefix = "GET_DEVICES", value = {
  6171. GET_DEVICES_INPUTS,
  6172. GET_DEVICES_OUTPUTS }
  6173. )
  6174. @Retention(RetentionPolicy.SOURCE)
  6175. public @interface AudioDeviceRole {}
  6176. /**
  6177. * Specifies to the {@link AudioManager#getDevices(int)} method to include both
  6178. * source and sink devices.
  6179. */
  6180. public static final int GET_DEVICES_ALL = GET_DEVICES_OUTPUTS | GET_DEVICES_INPUTS;
  6181. /**
  6182. * Determines if a given AudioDevicePort meets the specified filter criteria.
  6183. * @param port The port to test.
  6184. * @param flags A set of bitflags specifying the criteria to test.
  6185. * @see {@link GET_DEVICES_OUTPUTS} and {@link GET_DEVICES_INPUTS}
  6186. **/
  6187. private static boolean checkFlags(AudioDevicePort port, int flags) {
  6188. return port.role() == AudioPort.ROLE_SINK && (flags & GET_DEVICES_OUTPUTS) != 0 ||
  6189. port.role() == AudioPort.ROLE_SOURCE && (flags & GET_DEVICES_INPUTS) != 0;
  6190. }
  6191. private static boolean checkTypes(AudioDevicePort port) {
  6192. return AudioDeviceInfo.convertInternalDeviceToDeviceType(port.type()) !=
  6193. AudioDeviceInfo.TYPE_UNKNOWN;
  6194. }
  6195. /**
  6196. * Returns an array of {@link AudioDeviceInfo} objects corresponding to the audio devices
  6197. * currently connected to the system and meeting the criteria specified in the
  6198. * <code>flags</code> parameter.
  6199. * @param flags A set of bitflags specifying the criteria to test.
  6200. * @see #GET_DEVICES_OUTPUTS
  6201. * @see #GET_DEVICES_INPUTS
  6202. * @see #GET_DEVICES_ALL
  6203. * @return A (possibly zero-length) array of AudioDeviceInfo objects.
  6204. */
  6205. public AudioDeviceInfo[] getDevices(@AudioDeviceRole int flags) {
  6206. return getDevicesStatic(flags);
  6207. }
  6208. /**
  6209. * Does the actual computation to generate an array of (externally-visible) AudioDeviceInfo
  6210. * objects from the current (internal) AudioDevicePort list.
  6211. */
  6212. private static AudioDeviceInfo[]
  6213. infoListFromPortList(ArrayList<AudioDevicePort> ports, int flags) {
  6214. // figure out how many AudioDeviceInfo we need space for...
  6215. int numRecs = 0;
  6216. for (AudioDevicePort port : ports) {
  6217. if (checkTypes(port) && checkFlags(port, flags)) {
  6218. numRecs++;
  6219. }
  6220. }
  6221. // Now load them up...
  6222. AudioDeviceInfo[] deviceList = new AudioDeviceInfo[numRecs];
  6223. int slot = 0;
  6224. for (AudioDevicePort port : ports) {
  6225. if (checkTypes(port) && checkFlags(port, flags)) {
  6226. deviceList[slot++] = new AudioDeviceInfo(port);
  6227. }
  6228. }
  6229. return deviceList;
  6230. }
  6231. /*
  6232. * Calculate the list of ports that are in ports_B, but not in ports_A. This is used by
  6233. * the add/remove callback mechanism to provide a list of the newly added or removed devices
  6234. * rather than the whole list and make the app figure it out.
  6235. * Note that calling this method with:
  6236. * ports_A == PREVIOUS_ports and ports_B == CURRENT_ports will calculated ADDED ports.
  6237. * ports_A == CURRENT_ports and ports_B == PREVIOUS_ports will calculated REMOVED ports.
  6238. */
  6239. private static AudioDeviceInfo[] calcListDeltas(
  6240. ArrayList<AudioDevicePort> ports_A, ArrayList<AudioDevicePort> ports_B, int flags) {
  6241. ArrayList<AudioDevicePort> delta_ports = new ArrayList<AudioDevicePort>();
  6242. AudioDevicePort cur_port = null;
  6243. for (int cur_index = 0; cur_index < ports_B.size(); cur_index++) {
  6244. boolean cur_port_found = false;
  6245. cur_port = ports_B.get(cur_index);
  6246. for (int prev_index = 0;
  6247. prev_index < ports_A.size() && !cur_port_found;
  6248. prev_index++) {
  6249. cur_port_found = (cur_port.id() == ports_A.get(prev_index).id());
  6250. }
  6251. if (!cur_port_found) {
  6252. delta_ports.add(cur_port);
  6253. }
  6254. }
  6255. return infoListFromPortList(delta_ports, flags);
  6256. }
  6257. /**
  6258. * Generates a list of AudioDeviceInfo objects corresponding to the audio devices currently
  6259. * connected to the system and meeting the criteria specified in the <code>flags</code>
  6260. * parameter.
  6261. * This is an internal function. The public API front is getDevices(int).
  6262. * @param flags A set of bitflags specifying the criteria to test.
  6263. * @see #GET_DEVICES_OUTPUTS
  6264. * @see #GET_DEVICES_INPUTS
  6265. * @see #GET_DEVICES_ALL
  6266. * @return A (possibly zero-length) array of AudioDeviceInfo objects.
  6267. * @hide
  6268. */
  6269. public static AudioDeviceInfo[] getDevicesStatic(int flags) {
  6270. ArrayList<AudioDevicePort> ports = new ArrayList<AudioDevicePort>();
  6271. int status = AudioManager.listAudioDevicePorts(ports);
  6272. if (status != AudioManager.SUCCESS) {
  6273. // fail and bail!
  6274. return new AudioDeviceInfo[0]; // Always return an array.
  6275. }
  6276. return infoListFromPortList(ports, flags);
  6277. }
  6278. /**
  6279. * Returns an {@link AudioDeviceInfo} corresponding to the specified {@link AudioPort} ID.
  6280. * @param portId The audio port ID to look up for.
  6281. * @param flags A set of bitflags specifying the criteria to test.
  6282. * @see #GET_DEVICES_OUTPUTS
  6283. * @see #GET_DEVICES_INPUTS
  6284. * @see #GET_DEVICES_ALL
  6285. * @return An AudioDeviceInfo or null if no device with matching port ID is found.
  6286. * @hide
  6287. */
  6288. public static AudioDeviceInfo getDeviceForPortId(int portId, int flags) {
  6289. if (portId == 0) {
  6290. return null;
  6291. }
  6292. AudioDeviceInfo[] devices = getDevicesStatic(flags);
  6293. for (AudioDeviceInfo device : devices) {
  6294. if (device.getId() == portId) {
  6295. return device;
  6296. }
  6297. }
  6298. return null;
  6299. }
  6300. /**
  6301. * Registers an {@link AudioDeviceCallback} object to receive notifications of changes
  6302. * to the set of connected audio devices.
  6303. * @param callback The {@link AudioDeviceCallback} object to receive connect/disconnect
  6304. * notifications.
  6305. * @param handler Specifies the {@link Handler} object for the thread on which to execute
  6306. * the callback. If <code>null</code>, the {@link Handler} associated with the main
  6307. * {@link Looper} will be used.
  6308. */
  6309. public void registerAudioDeviceCallback(AudioDeviceCallback callback,
  6310. @Nullable Handler handler) {
  6311. synchronized (mDeviceCallbacks) {
  6312. if (callback != null && !mDeviceCallbacks.containsKey(callback)) {
  6313. if (mDeviceCallbacks.size() == 0) {
  6314. if (mPortListener == null) {
  6315. mPortListener = new OnAmPortUpdateListener();
  6316. }
  6317. registerAudioPortUpdateListener(mPortListener);
  6318. }
  6319. NativeEventHandlerDelegate delegate =
  6320. new NativeEventHandlerDelegate(callback, handler);
  6321. mDeviceCallbacks.put(callback, delegate);
  6322. broadcastDeviceListChange_sync(delegate.getHandler());
  6323. }
  6324. }
  6325. }
  6326. /**
  6327. * Unregisters an {@link AudioDeviceCallback} object which has been previously registered
  6328. * to receive notifications of changes to the set of connected audio devices.
  6329. * @param callback The {@link AudioDeviceCallback} object that was previously registered
  6330. * with {@link AudioManager#registerAudioDeviceCallback} to be unregistered.
  6331. */
  6332. public void unregisterAudioDeviceCallback(AudioDeviceCallback callback) {
  6333. synchronized (mDeviceCallbacks) {
  6334. if (mDeviceCallbacks.containsKey(callback)) {
  6335. mDeviceCallbacks.remove(callback);
  6336. if (mDeviceCallbacks.size() == 0) {
  6337. unregisterAudioPortUpdateListener(mPortListener);
  6338. }
  6339. }
  6340. }
  6341. }
  6342. /**
  6343. * Set port id for microphones by matching device type and address.
  6344. * @hide
  6345. */
  6346. public static void setPortIdForMicrophones(ArrayList<MicrophoneInfo> microphones) {
  6347. AudioDeviceInfo[] devices = getDevicesStatic(AudioManager.GET_DEVICES_INPUTS);
  6348. for (int i = microphones.size() - 1; i >= 0; i--) {
  6349. boolean foundPortId = false;
  6350. for (AudioDeviceInfo device : devices) {
  6351. if (device.getPort().type() == microphones.get(i).getInternalDeviceType()
  6352. && TextUtils.equals(device.getAddress(), microphones.get(i).getAddress())) {
  6353. microphones.get(i).setId(device.getId());
  6354. foundPortId = true;
  6355. break;
  6356. }
  6357. }
  6358. if (!foundPortId) {
  6359. Log.i(TAG, "Failed to find port id for device with type:"
  6360. + microphones.get(i).getType() + " address:"
  6361. + microphones.get(i).getAddress());
  6362. microphones.remove(i);
  6363. }
  6364. }
  6365. }
  6366. /**
  6367. * Convert {@link AudioDeviceInfo} to {@link MicrophoneInfo}.
  6368. * @hide
  6369. */
  6370. public static MicrophoneInfo microphoneInfoFromAudioDeviceInfo(AudioDeviceInfo deviceInfo) {
  6371. int deviceType = deviceInfo.getType();
  6372. int micLocation = (deviceType == AudioDeviceInfo.TYPE_BUILTIN_MIC
  6373. || deviceType == AudioDeviceInfo.TYPE_TELEPHONY) ? MicrophoneInfo.LOCATION_MAINBODY
  6374. : deviceType == AudioDeviceInfo.TYPE_UNKNOWN ? MicrophoneInfo.LOCATION_UNKNOWN
  6375. : MicrophoneInfo.LOCATION_PERIPHERAL;
  6376. MicrophoneInfo microphone = new MicrophoneInfo(
  6377. deviceInfo.getPort().name() + deviceInfo.getId(),
  6378. deviceInfo.getPort().type(), deviceInfo.getAddress(), micLocation,
  6379. MicrophoneInfo.GROUP_UNKNOWN, MicrophoneInfo.INDEX_IN_THE_GROUP_UNKNOWN,
  6380. MicrophoneInfo.POSITION_UNKNOWN, MicrophoneInfo.ORIENTATION_UNKNOWN,
  6381. new ArrayList<Pair<Float, Float>>(), new ArrayList<Pair<Integer, Integer>>(),
  6382. MicrophoneInfo.SENSITIVITY_UNKNOWN, MicrophoneInfo.SPL_UNKNOWN,
  6383. MicrophoneInfo.SPL_UNKNOWN, MicrophoneInfo.DIRECTIONALITY_UNKNOWN);
  6384. microphone.setId(deviceInfo.getId());
  6385. return microphone;
  6386. }
  6387. /**
  6388. * Add {@link MicrophoneInfo} by device information while filtering certain types.
  6389. */
  6390. private void addMicrophonesFromAudioDeviceInfo(ArrayList<MicrophoneInfo> microphones,
  6391. HashSet<Integer> filterTypes) {
  6392. AudioDeviceInfo[] devices = getDevicesStatic(GET_DEVICES_INPUTS);
  6393. for (AudioDeviceInfo device : devices) {
  6394. if (filterTypes.contains(device.getType())) {
  6395. continue;
  6396. }
  6397. MicrophoneInfo microphone = microphoneInfoFromAudioDeviceInfo(device);
  6398. microphones.add(microphone);
  6399. }
  6400. }
  6401. /**
  6402. * Returns a list of {@link MicrophoneInfo} that corresponds to the characteristics
  6403. * of all available microphones. The list is empty when no microphones are available
  6404. * on the device. An error during the query will result in an IOException being thrown.
  6405. *
  6406. * @return a list that contains all microphones' characteristics
  6407. * @throws IOException if an error occurs.
  6408. */
  6409. public List<MicrophoneInfo> getMicrophones() throws IOException {
  6410. ArrayList<MicrophoneInfo> microphones = new ArrayList<MicrophoneInfo>();
  6411. int status = AudioSystem.getMicrophones(microphones);
  6412. HashSet<Integer> filterTypes = new HashSet<>();
  6413. filterTypes.add(AudioDeviceInfo.TYPE_TELEPHONY);
  6414. if (status != AudioManager.SUCCESS) {
  6415. // fail and populate microphones with unknown characteristics by device information.
  6416. if (status != AudioManager.ERROR_INVALID_OPERATION) {
  6417. Log.e(TAG, "getMicrophones failed:" + status);
  6418. }
  6419. Log.i(TAG, "fallback on device info");
  6420. addMicrophonesFromAudioDeviceInfo(microphones, filterTypes);
  6421. return microphones;
  6422. }
  6423. setPortIdForMicrophones(microphones);
  6424. filterTypes.add(AudioDeviceInfo.TYPE_BUILTIN_MIC);
  6425. addMicrophonesFromAudioDeviceInfo(microphones, filterTypes);
  6426. return microphones;
  6427. }
  6428. /**
  6429. * Returns a list of audio formats that corresponds to encoding formats
  6430. * supported on offload path for A2DP playback.
  6431. *
  6432. * @return a list of {@link BluetoothCodecConfig} objects containing encoding formats
  6433. * supported for offload A2DP playback
  6434. * @hide
  6435. */
  6436. public List<BluetoothCodecConfig> getHwOffloadEncodingFormatsSupportedForA2DP() {
  6437. ArrayList<Integer> formatsList = new ArrayList<Integer>();
  6438. ArrayList<BluetoothCodecConfig> codecConfigList = new ArrayList<BluetoothCodecConfig>();
  6439. int status = AudioSystem.getHwOffloadEncodingFormatsSupportedForA2DP(formatsList);
  6440. if (status != AudioManager.SUCCESS) {
  6441. Log.e(TAG, "getHwOffloadEncodingFormatsSupportedForA2DP failed:" + status);
  6442. return codecConfigList;
  6443. }
  6444. for (Integer format : formatsList) {
  6445. int btSourceCodec = AudioSystem.audioFormatToBluetoothSourceCodec(format);
  6446. if (btSourceCodec
  6447. != BluetoothCodecConfig.SOURCE_CODEC_TYPE_INVALID) {
  6448. codecConfigList.add(new BluetoothCodecConfig(btSourceCodec));
  6449. }
  6450. }
  6451. return codecConfigList;
  6452. }
  6453. // Since we need to calculate the changes since THE LAST NOTIFICATION, and not since the
  6454. // (unpredictable) last time updateAudioPortCache() was called by someone, keep a list
  6455. // of the ports that exist at the time of the last notification.
  6456. private ArrayList<AudioDevicePort> mPreviousPorts = new ArrayList<AudioDevicePort>();
  6457. /**
  6458. * Internal method to compute and generate add/remove messages and then send to any
  6459. * registered callbacks. Must be called synchronized on mDeviceCallbacks.
  6460. */
  6461. private void broadcastDeviceListChange_sync(Handler handler) {
  6462. int status;
  6463. // Get the new current set of ports
  6464. ArrayList<AudioDevicePort> current_ports = new ArrayList<AudioDevicePort>();
  6465. status = AudioManager.listAudioDevicePorts(current_ports);
  6466. if (status != AudioManager.SUCCESS) {
  6467. return;
  6468. }
  6469. if (handler != null) {
  6470. // This is the callback for the registration, so send the current list
  6471. AudioDeviceInfo[] deviceList =
  6472. infoListFromPortList(current_ports, GET_DEVICES_ALL);
  6473. handler.sendMessage(
  6474. Message.obtain(handler, MSG_DEVICES_CALLBACK_REGISTERED, deviceList));
  6475. } else {
  6476. AudioDeviceInfo[] added_devices =
  6477. calcListDeltas(mPreviousPorts, current_ports, GET_DEVICES_ALL);
  6478. AudioDeviceInfo[] removed_devices =
  6479. calcListDeltas(current_ports, mPreviousPorts, GET_DEVICES_ALL);
  6480. if (added_devices.length != 0 || removed_devices.length != 0) {
  6481. for (int i = 0; i < mDeviceCallbacks.size(); i++) {
  6482. handler = mDeviceCallbacks.valueAt(i).getHandler();
  6483. if (handler != null) {
  6484. if (removed_devices.length != 0) {
  6485. handler.sendMessage(Message.obtain(handler,
  6486. MSG_DEVICES_DEVICES_REMOVED,
  6487. removed_devices));
  6488. }
  6489. if (added_devices.length != 0) {
  6490. handler.sendMessage(Message.obtain(handler,
  6491. MSG_DEVICES_DEVICES_ADDED,
  6492. added_devices));
  6493. }
  6494. }
  6495. }
  6496. }
  6497. }
  6498. mPreviousPorts = current_ports;
  6499. }
  6500. /**
  6501. * Handles Port list update notifications from the AudioManager
  6502. */
  6503. private class OnAmPortUpdateListener implements AudioManager.OnAudioPortUpdateListener {
  6504. static final String TAG = "OnAmPortUpdateListener";
  6505. public void onAudioPortListUpdate(AudioPort[] portList) {
  6506. synchronized (mDeviceCallbacks) {
  6507. broadcastDeviceListChange_sync(null);
  6508. }
  6509. }
  6510. /**
  6511. * Callback method called upon audio patch list update.
  6512. * Note: We don't do anything with Patches at this time, so ignore this notification.
  6513. * @param patchList the updated list of audio patches.
  6514. */
  6515. public void onAudioPatchListUpdate(AudioPatch[] patchList) {}
  6516. /**
  6517. * Callback method called when the mediaserver dies
  6518. */
  6519. public void onServiceDied() {
  6520. synchronized (mDeviceCallbacks) {
  6521. broadcastDeviceListChange_sync(null);
  6522. }
  6523. }
  6524. }
  6525. /**
  6526. * @hide
  6527. * Abstract class to receive event notification about audioserver process state.
  6528. */
  6529. @SystemApi
  6530. public abstract static class AudioServerStateCallback {
  6531. public void onAudioServerDown() { }
  6532. public void onAudioServerUp() { }
  6533. }
  6534. private Executor mAudioServerStateExec;
  6535. private AudioServerStateCallback mAudioServerStateCb;
  6536. private final Object mAudioServerStateCbLock = new Object();
  6537. private final IAudioServerStateDispatcher mAudioServerStateDispatcher =
  6538. new IAudioServerStateDispatcher.Stub() {
  6539. @Override
  6540. public void dispatchAudioServerStateChange(boolean state) {
  6541. Executor exec;
  6542. AudioServerStateCallback cb;
  6543. synchronized (mAudioServerStateCbLock) {
  6544. exec = mAudioServerStateExec;
  6545. cb = mAudioServerStateCb;
  6546. }
  6547. if ((exec == null) || (cb == null)) {
  6548. return;
  6549. }
  6550. if (state) {
  6551. exec.execute(() -> cb.onAudioServerUp());
  6552. } else {
  6553. exec.execute(() -> cb.onAudioServerDown());
  6554. }
  6555. }
  6556. };
  6557. /**
  6558. * @hide
  6559. * Registers a callback for notification of audio server state changes.
  6560. * @param executor {@link Executor} to handle the callbacks
  6561. * @param stateCallback the callback to receive the audio server state changes
  6562. * To remove the callabck, pass a null reference for both executor and stateCallback.
  6563. */
  6564. @SystemApi
  6565. public void setAudioServerStateCallback(@NonNull Executor executor,
  6566. @NonNull AudioServerStateCallback stateCallback) {
  6567. if (stateCallback == null) {
  6568. throw new IllegalArgumentException("Illegal null AudioServerStateCallback");
  6569. }
  6570. if (executor == null) {
  6571. throw new IllegalArgumentException(
  6572. "Illegal null Executor for the AudioServerStateCallback");
  6573. }
  6574. synchronized (mAudioServerStateCbLock) {
  6575. if (mAudioServerStateCb != null) {
  6576. throw new IllegalStateException(
  6577. "setAudioServerStateCallback called with already registered callabck");
  6578. }
  6579. final IAudioService service = getService();
  6580. try {
  6581. service.registerAudioServerStateDispatcher(mAudioServerStateDispatcher);
  6582. } catch (RemoteException e) {
  6583. throw e.rethrowFromSystemServer();
  6584. }
  6585. mAudioServerStateExec = executor;
  6586. mAudioServerStateCb = stateCallback;
  6587. }
  6588. }
  6589. /**
  6590. * @hide
  6591. * Unregisters the callback for notification of audio server state changes.
  6592. */
  6593. @SystemApi
  6594. public void clearAudioServerStateCallback() {
  6595. synchronized (mAudioServerStateCbLock) {
  6596. if (mAudioServerStateCb != null) {
  6597. final IAudioService service = getService();
  6598. try {
  6599. service.unregisterAudioServerStateDispatcher(
  6600. mAudioServerStateDispatcher);
  6601. } catch (RemoteException e) {
  6602. throw e.rethrowFromSystemServer();
  6603. }
  6604. }
  6605. mAudioServerStateExec = null;
  6606. mAudioServerStateCb = null;
  6607. }
  6608. }
  6609. /**
  6610. * @hide
  6611. * Checks if native audioservice is running or not.
  6612. * @return true if native audioservice runs, false otherwise.
  6613. */
  6614. @SystemApi
  6615. public boolean isAudioServerRunning() {
  6616. final IAudioService service = getService();
  6617. try {
  6618. return service.isAudioServerRunning();
  6619. } catch (RemoteException e) {
  6620. throw e.rethrowFromSystemServer();
  6621. }
  6622. }
  6623. /**
  6624. * Sets the surround sound mode.
  6625. *
  6626. * @return true if successful, otherwise false
  6627. */
  6628. @RequiresPermission(android.Manifest.permission.WRITE_SETTINGS)
  6629. public boolean setEncodedSurroundMode(@EncodedSurroundOutputMode int mode) {
  6630. try {
  6631. return getService().setEncodedSurroundMode(mode);
  6632. } catch (RemoteException e) {
  6633. throw e.rethrowFromSystemServer();
  6634. }
  6635. }
  6636. /**
  6637. * Gets the surround sound mode.
  6638. *
  6639. * @return true if successful, otherwise false
  6640. */
  6641. public @EncodedSurroundOutputMode int getEncodedSurroundMode() {
  6642. try {
  6643. return getService().getEncodedSurroundMode(
  6644. getContext().getApplicationInfo().targetSdkVersion);
  6645. } catch (RemoteException e) {
  6646. throw e.rethrowFromSystemServer();
  6647. }
  6648. }
  6649. /**
  6650. * @hide
  6651. * Returns all surround formats.
  6652. * @return a map where the key is a surround format and
  6653. * the value indicates the surround format is enabled or not
  6654. */
  6655. @TestApi
  6656. @NonNull
  6657. public Map<Integer, Boolean> getSurroundFormats() {
  6658. try {
  6659. return getService().getSurroundFormats();
  6660. } catch (RemoteException e) {
  6661. throw e.rethrowFromSystemServer();
  6662. }
  6663. }
  6664. /**
  6665. * Sets and persists a certain surround format as enabled or not.
  6666. * <p>
  6667. * This API is called by TvSettings surround sound menu when user enables or disables a
  6668. * surround sound format. This setting is persisted as global user setting.
  6669. * Applications should revert their changes to surround sound settings unless they intend to
  6670. * modify the global user settings across all apps. The framework does not auto-revert an
  6671. * application's settings after a lifecycle event. Audio focus is not required to apply these
  6672. * settings.
  6673. *
  6674. * @param enabled the required surround format state, true for enabled, false for disabled
  6675. * @return true if successful, otherwise false
  6676. */
  6677. @RequiresPermission(android.Manifest.permission.WRITE_SETTINGS)
  6678. public boolean setSurroundFormatEnabled(
  6679. @AudioFormat.SurroundSoundEncoding int audioFormat, boolean enabled) {
  6680. try {
  6681. return getService().setSurroundFormatEnabled(audioFormat, enabled);
  6682. } catch (RemoteException e) {
  6683. throw e.rethrowFromSystemServer();
  6684. }
  6685. }
  6686. /**
  6687. * Gets whether a certain surround format is enabled or not.
  6688. * @param audioFormat a surround format
  6689. *
  6690. * @return whether the required surround format is enabled
  6691. */
  6692. public boolean isSurroundFormatEnabled(@AudioFormat.SurroundSoundEncoding int audioFormat) {
  6693. try {
  6694. return getService().isSurroundFormatEnabled(audioFormat);
  6695. } catch (RemoteException e) {
  6696. throw e.rethrowFromSystemServer();
  6697. }
  6698. }
  6699. /**
  6700. * @hide
  6701. * Returns all surround formats that are reported by the connected HDMI device.
  6702. * The return values are not affected by calling setSurroundFormatEnabled.
  6703. *
  6704. * @return a list of surround formats
  6705. */
  6706. @TestApi
  6707. @NonNull
  6708. public List<Integer> getReportedSurroundFormats() {
  6709. try {
  6710. return getService().getReportedSurroundFormats();
  6711. } catch (RemoteException e) {
  6712. throw e.rethrowFromSystemServer();
  6713. }
  6714. }
  6715. /**
  6716. * Return if audio haptic coupled playback is supported or not.
  6717. *
  6718. * @return whether audio haptic playback supported.
  6719. */
  6720. public static boolean isHapticPlaybackSupported() {
  6721. return AudioSystem.isHapticPlaybackSupported();
  6722. }
  6723. /**
  6724. * @hide
  6725. * Introspection API to retrieve audio product strategies.
  6726. * When implementing {Car|Oem}AudioManager, use this method to retrieve the collection of
  6727. * audio product strategies, which is indexed by a weakly typed index in order to be extended
  6728. * by OEM without any needs of AOSP patches.
  6729. * The {Car|Oem}AudioManager can expose API to build {@link AudioAttributes} for a given product
  6730. * strategy refered either by its index or human readable string. It will allow clients
  6731. * application to start streaming data using these {@link AudioAttributes} on the selected
  6732. * device by Audio Policy Engine.
  6733. * @return a (possibly zero-length) array of
  6734. * {@see android.media.audiopolicy.AudioProductStrategy} objects.
  6735. */
  6736. @SystemApi
  6737. @NonNull
  6738. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  6739. public static List<AudioProductStrategy> getAudioProductStrategies() {
  6740. final IAudioService service = getService();
  6741. try {
  6742. return service.getAudioProductStrategies();
  6743. } catch (RemoteException e) {
  6744. throw e.rethrowFromSystemServer();
  6745. }
  6746. }
  6747. /**
  6748. * @hide
  6749. * Introspection API to retrieve audio volume groups.
  6750. * When implementing {Car|Oem}AudioManager, use this method to retrieve the collection of
  6751. * audio volume groups.
  6752. * @return a (possibly zero-length) List of
  6753. * {@see android.media.audiopolicy.AudioVolumeGroup} objects.
  6754. */
  6755. @SystemApi
  6756. @NonNull
  6757. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  6758. public static List<AudioVolumeGroup> getAudioVolumeGroups() {
  6759. final IAudioService service = getService();
  6760. try {
  6761. return service.getAudioVolumeGroups();
  6762. } catch (RemoteException e) {
  6763. throw e.rethrowFromSystemServer();
  6764. }
  6765. }
  6766. /**
  6767. * @hide
  6768. * Callback registered by client to be notified upon volume group change.
  6769. */
  6770. @SystemApi
  6771. public abstract static class VolumeGroupCallback {
  6772. /**
  6773. * Callback method called upon audio volume group change.
  6774. * @param group the group for which the volume has changed
  6775. */
  6776. public void onAudioVolumeGroupChanged(int group, int flags) {}
  6777. }
  6778. /**
  6779. * @hide
  6780. * Register an audio volume group change listener.
  6781. * @param callback the {@link VolumeGroupCallback} to register
  6782. */
  6783. @SystemApi
  6784. public void registerVolumeGroupCallback(
  6785. @NonNull Executor executor,
  6786. @NonNull VolumeGroupCallback callback) {
  6787. Preconditions.checkNotNull(executor, "executor must not be null");
  6788. Preconditions.checkNotNull(callback, "volume group change cb must not be null");
  6789. sAudioAudioVolumeGroupChangedHandler.init();
  6790. // TODO: make use of executor
  6791. sAudioAudioVolumeGroupChangedHandler.registerListener(callback);
  6792. }
  6793. /**
  6794. * @hide
  6795. * Unregister an audio volume group change listener.
  6796. * @param callback the {@link VolumeGroupCallback} to unregister
  6797. */
  6798. @SystemApi
  6799. public void unregisterVolumeGroupCallback(
  6800. @NonNull VolumeGroupCallback callback) {
  6801. Preconditions.checkNotNull(callback, "volume group change cb must not be null");
  6802. sAudioAudioVolumeGroupChangedHandler.unregisterListener(callback);
  6803. }
  6804. /**
  6805. * Return if an asset contains haptic channels or not.
  6806. *
  6807. * @param context the {@link Context} to resolve the uri.
  6808. * @param uri the {@link Uri} of the asset.
  6809. * @return true if the assert contains haptic channels.
  6810. * @hide
  6811. */
  6812. public static boolean hasHapticChannelsImpl(@NonNull Context context, @NonNull Uri uri) {
  6813. MediaExtractor extractor = new MediaExtractor();
  6814. try {
  6815. extractor.setDataSource(context, uri, null);
  6816. for (int i = 0; i < extractor.getTrackCount(); i++) {
  6817. MediaFormat format = extractor.getTrackFormat(i);
  6818. if (format.containsKey(MediaFormat.KEY_HAPTIC_CHANNEL_COUNT)
  6819. && format.getInteger(MediaFormat.KEY_HAPTIC_CHANNEL_COUNT) > 0) {
  6820. return true;
  6821. }
  6822. }
  6823. } catch (IOException e) {
  6824. Log.e(TAG, "hasHapticChannels failure:" + e);
  6825. }
  6826. return false;
  6827. }
  6828. /**
  6829. * Return if an asset contains haptic channels or not.
  6830. *
  6831. * @param context the {@link Context} to resolve the uri.
  6832. * @param uri the {@link Uri} of the asset.
  6833. * @return true if the assert contains haptic channels.
  6834. * @hide
  6835. */
  6836. public static boolean hasHapticChannels(@Nullable Context context, @NonNull Uri uri) {
  6837. Objects.requireNonNull(uri);
  6838. if (context != null) {
  6839. return hasHapticChannelsImpl(context, uri);
  6840. }
  6841. Context cachedContext = sContext.get();
  6842. if (cachedContext != null) {
  6843. if (DEBUG) {
  6844. Log.d(TAG, "Try to use static context to query if having haptic channels");
  6845. }
  6846. return hasHapticChannelsImpl(cachedContext, uri);
  6847. }
  6848. // Try with audio service context, this may fail to get correct result.
  6849. if (DEBUG) {
  6850. Log.d(TAG, "Try to use audio service context to query if having haptic channels");
  6851. }
  6852. try {
  6853. return getService().hasHapticChannels(uri);
  6854. } catch (RemoteException e) {
  6855. throw e.rethrowFromSystemServer();
  6856. }
  6857. }
  6858. /**
  6859. * Set whether or not there is an active RTT call.
  6860. * This method should be called by Telecom service.
  6861. * @hide
  6862. * TODO: make this a @SystemApi
  6863. */
  6864. public static void setRttEnabled(boolean rttEnabled) {
  6865. try {
  6866. getService().setRttEnabled(rttEnabled);
  6867. } catch (RemoteException e) {
  6868. throw e.rethrowFromSystemServer();
  6869. }
  6870. }
  6871. /**
  6872. * Adjusts the volume of the most relevant stream, or the given fallback
  6873. * stream.
  6874. * <p>
  6875. * This method should only be used by applications that replace the
  6876. * platform-wide management of audio settings or the main telephony
  6877. * application.
  6878. * <p>
  6879. * This method has no effect if the device implements a fixed volume policy
  6880. * as indicated by {@link #isVolumeFixed()}.
  6881. * <p>This API checks if the caller has the necessary permissions based on the provided
  6882. * component name, uid, and pid values.
  6883. * See {@link #adjustSuggestedStreamVolume(int, int, int)}.
  6884. *
  6885. * @param suggestedStreamType The stream type that will be used if there
  6886. * isn't a relevant stream. {@link #USE_DEFAULT_STREAM_TYPE} is
  6887. * valid here.
  6888. * @param direction The direction to adjust the volume. One of
  6889. * {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE},
  6890. * {@link #ADJUST_SAME}, {@link #ADJUST_MUTE},
  6891. * {@link #ADJUST_UNMUTE}, or {@link #ADJUST_TOGGLE_MUTE}.
  6892. * @param flags One or more flags.
  6893. * @param packageName the package name of client application
  6894. * @param uid the uid of client application
  6895. * @param pid the pid of client application
  6896. * @param targetSdkVersion the target sdk version of client application
  6897. * @see #adjustVolume(int, int)
  6898. * @see #adjustStreamVolume(int, int, int)
  6899. * @see #setStreamVolume(int, int, int)
  6900. * @see #isVolumeFixed()
  6901. *
  6902. * @hide
  6903. */
  6904. @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
  6905. public void adjustSuggestedStreamVolumeForUid(int suggestedStreamType, int direction, int flags,
  6906. @NonNull String packageName, int uid, int pid, int targetSdkVersion) {
  6907. try {
  6908. getService().adjustSuggestedStreamVolumeForUid(suggestedStreamType, direction, flags,
  6909. packageName, uid, pid, UserHandle.getUserHandleForUid(uid), targetSdkVersion);
  6910. } catch (RemoteException e) {
  6911. throw e.rethrowFromSystemServer();
  6912. }
  6913. }
  6914. /**
  6915. * Adjusts the volume of a particular stream by one step in a direction.
  6916. * <p>
  6917. * This method should only be used by applications that replace the platform-wide
  6918. * management of audio settings or the main telephony application.
  6919. * <p>This method has no effect if the device implements a fixed volume policy
  6920. * as indicated by {@link #isVolumeFixed()}.
  6921. * <p>From N onward, ringer mode adjustments that would toggle Do Not Disturb are not allowed
  6922. * unless the app has been granted Do Not Disturb Access.
  6923. * See {@link NotificationManager#isNotificationPolicyAccessGranted()}.
  6924. * <p>This API checks if the caller has the necessary permissions based on the provided
  6925. * component name, uid, and pid values.
  6926. * See {@link #adjustStreamVolume(int, int, int)}.
  6927. *
  6928. * @param streamType The stream type to adjust. One of {@link #STREAM_VOICE_CALL},
  6929. * {@link #STREAM_SYSTEM}, {@link #STREAM_RING}, {@link #STREAM_MUSIC},
  6930. * {@link #STREAM_ALARM} or {@link #STREAM_ACCESSIBILITY}.
  6931. * @param direction The direction to adjust the volume. One of
  6932. * {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
  6933. * {@link #ADJUST_SAME}.
  6934. * @param flags One or more flags.
  6935. * @param packageName the package name of client application
  6936. * @param uid the uid of client application
  6937. * @param pid the pid of client application
  6938. * @param targetSdkVersion the target sdk version of client application
  6939. * @see #adjustVolume(int, int)
  6940. * @see #setStreamVolume(int, int, int)
  6941. * @throws SecurityException if the adjustment triggers a Do Not Disturb change
  6942. * and the caller is not granted notification policy access.
  6943. *
  6944. * @hide
  6945. */
  6946. @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
  6947. public void adjustStreamVolumeForUid(int streamType, int direction, int flags,
  6948. @NonNull String packageName, int uid, int pid, int targetSdkVersion) {
  6949. try {
  6950. getService().adjustStreamVolumeForUid(streamType, direction, flags, packageName, uid,
  6951. pid, UserHandle.getUserHandleForUid(uid), targetSdkVersion);
  6952. } catch (RemoteException e) {
  6953. throw e.rethrowFromSystemServer();
  6954. }
  6955. }
  6956. /**
  6957. * Sets the volume index for a particular stream.
  6958. * <p>This method has no effect if the device implements a fixed volume policy
  6959. * as indicated by {@link #isVolumeFixed()}.
  6960. * <p>From N onward, volume adjustments that would toggle Do Not Disturb are not allowed unless
  6961. * the app has been granted Do Not Disturb Access.
  6962. * See {@link NotificationManager#isNotificationPolicyAccessGranted()}.
  6963. * <p>This API checks if the caller has the necessary permissions based on the provided
  6964. * component name, uid, and pid values.
  6965. * See {@link #setStreamVolume(int, int, int)}.
  6966. *
  6967. * @param streamType The stream whose volume index should be set.
  6968. * @param index The volume index to set. See
  6969. * {@link #getStreamMaxVolume(int)} for the largest valid value.
  6970. * @param flags One or more flags.
  6971. * @param packageName the package name of client application
  6972. * @param uid the uid of client application
  6973. * @param pid the pid of client application
  6974. * @param targetSdkVersion the target sdk version of client application
  6975. * @see #getStreamMaxVolume(int)
  6976. * @see #getStreamVolume(int)
  6977. * @see #isVolumeFixed()
  6978. * @throws SecurityException if the volume change triggers a Do Not Disturb change
  6979. * and the caller is not granted notification policy access.
  6980. *
  6981. * @hide
  6982. */
  6983. @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
  6984. public void setStreamVolumeForUid(int streamType, int index, int flags,
  6985. @NonNull String packageName, int uid, int pid, int targetSdkVersion) {
  6986. try {
  6987. getService().setStreamVolumeForUid(streamType, index, flags, packageName, uid, pid,
  6988. UserHandle.getUserHandleForUid(uid), targetSdkVersion);
  6989. } catch (RemoteException e) {
  6990. throw e.rethrowFromSystemServer();
  6991. }
  6992. }
  6993. /** @hide
  6994. * TODO: make this a @SystemApi */
  6995. @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
  6996. public void setMultiAudioFocusEnabled(boolean enabled) {
  6997. try {
  6998. getService().setMultiAudioFocusEnabled(enabled);
  6999. } catch (RemoteException e) {
  7000. throw e.rethrowFromSystemServer();
  7001. }
  7002. }
  7003. /**
  7004. * Retrieves the Hardware A/V synchronization ID corresponding to the given audio session ID.
  7005. * For more details on Hardware A/V synchronization please refer to
  7006. * <a href="https://source.android.com/devices/tv/multimedia-tunneling/">
  7007. * media tunneling documentation</a>.
  7008. * @param sessionId the audio session ID for which the HW A/V sync ID is retrieved.
  7009. * @return the HW A/V sync ID for this audio session (an integer different from 0).
  7010. * @throws UnsupportedOperationException if HW A/V synchronization is not supported.
  7011. */
  7012. public int getAudioHwSyncForSession(int sessionId) {
  7013. int hwSyncId = AudioSystem.getAudioHwSyncForSession(sessionId);
  7014. if (hwSyncId == AudioSystem.AUDIO_HW_SYNC_INVALID) {
  7015. throw new UnsupportedOperationException("HW A/V synchronization is not supported.");
  7016. }
  7017. return hwSyncId;
  7018. }
  7019. /**
  7020. * Selects the audio device that should be used for communication use cases, for instance voice
  7021. * or video calls. This method can be used by voice or video chat applications to select a
  7022. * different audio device than the one selected by default by the platform.
  7023. * <p>The device selection is expressed as an {@link AudioDeviceInfo} among devices returned by
  7024. * {@link #getAvailableCommunicationDevices()}.
  7025. * The selection is active as long as the requesting application process lives, until
  7026. * {@link #clearCommunicationDevice} is called or until the device is disconnected.
  7027. * It is therefore important for applications to clear the request when a call ends or the
  7028. * the requesting activity or service is stopped or destroyed.
  7029. * <p>In case of simultaneous requests by multiple applications the priority is given to the
  7030. * application currently controlling the audio mode (see {@link #setMode(int)}). This is the
  7031. * latest application having selected mode {@link #MODE_IN_COMMUNICATION} or mode
  7032. * {@link #MODE_IN_CALL}. Note that <code>MODE_IN_CALL</code> can only be selected by the main
  7033. * telephony application with permission
  7034. * {@link android.Manifest.permission#MODIFY_PHONE_STATE}.
  7035. * <p> If the requested devices is not currently available, the request will be rejected and
  7036. * the method will return false.
  7037. * <p>This API replaces the following deprecated APIs:
  7038. * <ul>
  7039. * <li> {@link #startBluetoothSco()}
  7040. * <li> {@link #stopBluetoothSco()}
  7041. * <li> {@link #setSpeakerphoneOn(boolean)}
  7042. * </ul>
  7043. * <h4>Example</h4>
  7044. * <p>The example below shows how to enable and disable speakerphone mode.
  7045. * <pre class="prettyprint">
  7046. * // Get an AudioManager instance
  7047. * AudioManager audioManager = Context.getSystemService(AudioManager.class);
  7048. * AudioDeviceInfo speakerDevice = null;
  7049. * List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();
  7050. * for (AudioDeviceInfo device : devices) {
  7051. * if (device.getType() == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER) {
  7052. * speakerDevice = device;
  7053. * break;
  7054. * }
  7055. * }
  7056. * if (speakerDevice != null) {
  7057. * // Turn speakerphone ON.
  7058. * boolean result = audioManager.setCommunicationDevice(speakerDevice);
  7059. * if (!result) {
  7060. * // Handle error.
  7061. * }
  7062. * // Turn speakerphone OFF.
  7063. * audioManager.clearCommunicationDevice();
  7064. * }
  7065. * </pre>
  7066. * @param device the requested audio device.
  7067. * @return <code>true</code> if the request was accepted, <code>false</code> otherwise.
  7068. * @throws IllegalArgumentException If an invalid device is specified.
  7069. */
  7070. public boolean setCommunicationDevice(@NonNull AudioDeviceInfo device) {
  7071. Objects.requireNonNull(device);
  7072. try {
  7073. if (device.getId() == 0) {
  7074. throw new IllegalArgumentException("In valid device: " + device);
  7075. }
  7076. return getService().setCommunicationDevice(mICallBack, device.getId());
  7077. } catch (RemoteException e) {
  7078. throw e.rethrowFromSystemServer();
  7079. }
  7080. }
  7081. /**
  7082. * Cancels previous communication device selection made with
  7083. * {@link #setCommunicationDevice(AudioDeviceInfo)}.
  7084. */
  7085. public void clearCommunicationDevice() {
  7086. try {
  7087. getService().setCommunicationDevice(mICallBack, 0);
  7088. } catch (RemoteException e) {
  7089. throw e.rethrowFromSystemServer();
  7090. }
  7091. }
  7092. /**
  7093. * Returns currently selected audio device for communication.
  7094. * <p>This API replaces the following deprecated APIs:
  7095. * <ul>
  7096. * <li> {@link #isBluetoothScoOn()}
  7097. * <li> {@link #isSpeakerphoneOn()}
  7098. * </ul>
  7099. * @return an {@link AudioDeviceInfo} indicating which audio device is
  7100. * currently selected for communication use cases. Can be null on platforms
  7101. * not supporting {@link android.content.pm.PackageManager#FEATURE_TELEPHONY}.
  7102. * is used.
  7103. */
  7104. @Nullable
  7105. public AudioDeviceInfo getCommunicationDevice() {
  7106. try {
  7107. return getDeviceForPortId(
  7108. getService().getCommunicationDevice(), GET_DEVICES_OUTPUTS);
  7109. } catch (RemoteException e) {
  7110. throw e.rethrowFromSystemServer();
  7111. }
  7112. }
  7113. /**
  7114. * Returns a list of audio devices that can be selected for communication use cases via
  7115. * {@link #setCommunicationDevice(AudioDeviceInfo)}.
  7116. * @return a list of {@link AudioDeviceInfo} suitable for use with setCommunicationDevice().
  7117. */
  7118. @NonNull
  7119. public List<AudioDeviceInfo> getAvailableCommunicationDevices() {
  7120. try {
  7121. ArrayList<AudioDeviceInfo> devices = new ArrayList<>();
  7122. int[] portIds = getService().getAvailableCommunicationDeviceIds();
  7123. for (int portId : portIds) {
  7124. AudioDeviceInfo device = getDeviceForPortId(portId, GET_DEVICES_OUTPUTS);
  7125. if (device == null) {
  7126. continue;
  7127. }
  7128. devices.add(device);
  7129. }
  7130. return devices;
  7131. } catch (RemoteException e) {
  7132. throw e.rethrowFromSystemServer();
  7133. }
  7134. }
  7135. /**
  7136. * @hide
  7137. * Returns an {@link AudioDeviceInfo} corresponding to a connected device of the type provided.
  7138. * The type must be a valid output type defined in <code>AudioDeviceInfo</code> class,
  7139. * for instance {@link AudioDeviceInfo#TYPE_BUILTIN_SPEAKER}.
  7140. * The method will return null if no device of the provided type is connected.
  7141. * If more than one device of the provided type is connected, an object corresponding to the
  7142. * first device encountered in the enumeration list will be returned.
  7143. * @param deviceType The device device for which an <code>AudioDeviceInfo</code>
  7144. * object is queried.
  7145. * @return An AudioDeviceInfo object or null if no device with the requested type is connected.
  7146. * @throws IllegalArgumentException If an invalid device type is specified.
  7147. */
  7148. @TestApi
  7149. @Nullable
  7150. public static AudioDeviceInfo getDeviceInfoFromType(
  7151. @AudioDeviceInfo.AudioDeviceTypeOut int deviceType) {
  7152. return getDeviceInfoFromTypeAndAddress(deviceType, null);
  7153. }
  7154. /**
  7155. * @hide
  7156. * Returns an {@link AudioDeviceInfo} corresponding to a connected device of the type and
  7157. * address provided.
  7158. * The type must be a valid output type defined in <code>AudioDeviceInfo</code> class,
  7159. * for instance {@link AudioDeviceInfo#TYPE_BUILTIN_SPEAKER}.
  7160. * If a null address is provided, the matching will happen on the type only.
  7161. * The method will return null if no device of the provided type and address is connected.
  7162. * If more than one device of the provided type is connected, an object corresponding to the
  7163. * first device encountered in the enumeration list will be returned.
  7164. * @param type The device device for which an <code>AudioDeviceInfo</code>
  7165. * object is queried.
  7166. * @param address The device address for which an <code>AudioDeviceInfo</code>
  7167. * object is queried or null if requesting match on type only.
  7168. * @return An AudioDeviceInfo object or null if no matching device is connected.
  7169. * @throws IllegalArgumentException If an invalid device type is specified.
  7170. */
  7171. @Nullable
  7172. public static AudioDeviceInfo getDeviceInfoFromTypeAndAddress(
  7173. @AudioDeviceInfo.AudioDeviceTypeOut int type, @Nullable String address) {
  7174. AudioDeviceInfo[] devices = getDevicesStatic(GET_DEVICES_OUTPUTS);
  7175. AudioDeviceInfo deviceForType = null;
  7176. for (AudioDeviceInfo device : devices) {
  7177. if (device.getType() == type) {
  7178. deviceForType = device;
  7179. if (address == null || address.equals(device.getAddress())) {
  7180. return device;
  7181. }
  7182. }
  7183. }
  7184. return deviceForType;
  7185. }
  7186. /**
  7187. * Listener registered by client to be notified upon communication audio device change.
  7188. * See {@link #setCommunicationDevice(AudioDeviceInfo)}.
  7189. */
  7190. public interface OnCommunicationDeviceChangedListener {
  7191. /**
  7192. * Callback method called upon communication audio device change.
  7193. * @param device the audio device requested for communication use cases.
  7194. * Can be null on platforms not supporting
  7195. * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY}.
  7196. */
  7197. void onCommunicationDeviceChanged(@Nullable AudioDeviceInfo device);
  7198. }
  7199. /**
  7200. * Adds a listener for being notified of changes to the communication audio device.
  7201. * See {@link #setCommunicationDevice(AudioDeviceInfo)}.
  7202. * @param executor
  7203. * @param listener
  7204. */
  7205. public void addOnCommunicationDeviceChangedListener(
  7206. @NonNull @CallbackExecutor Executor executor,
  7207. @NonNull OnCommunicationDeviceChangedListener listener) {
  7208. Objects.requireNonNull(executor);
  7209. Objects.requireNonNull(listener);
  7210. synchronized (mCommDevListenerLock) {
  7211. if (hasCommDevListener(listener)) {
  7212. throw new IllegalArgumentException(
  7213. "attempt to call addOnCommunicationDeviceChangedListener() "
  7214. + "on a previously registered listener");
  7215. }
  7216. // lazy initialization of the list of strategy-preferred device listener
  7217. if (mCommDevListeners == null) {
  7218. mCommDevListeners = new ArrayList<>();
  7219. }
  7220. final int oldCbCount = mCommDevListeners.size();
  7221. mCommDevListeners.add(new CommDevListenerInfo(listener, executor));
  7222. if (oldCbCount == 0 && mCommDevListeners.size() > 0) {
  7223. // register binder for callbacks
  7224. if (mCommDevDispatcherStub == null) {
  7225. mCommDevDispatcherStub = new CommunicationDeviceDispatcherStub();
  7226. }
  7227. try {
  7228. getService().registerCommunicationDeviceDispatcher(mCommDevDispatcherStub);
  7229. } catch (RemoteException e) {
  7230. throw e.rethrowFromSystemServer();
  7231. }
  7232. }
  7233. }
  7234. }
  7235. /**
  7236. * Removes a previously added listener of changes to the communication audio device.
  7237. * See {@link #setCommunicationDevice(AudioDeviceInfo)}.
  7238. * @param listener
  7239. */
  7240. public void removeOnCommunicationDeviceChangedListener(
  7241. @NonNull OnCommunicationDeviceChangedListener listener) {
  7242. Objects.requireNonNull(listener);
  7243. synchronized (mCommDevListenerLock) {
  7244. if (!removeCommDevListener(listener)) {
  7245. throw new IllegalArgumentException(
  7246. "attempt to call removeOnCommunicationDeviceChangedListener() "
  7247. + "on an unregistered listener");
  7248. }
  7249. if (mCommDevListeners.size() == 0) {
  7250. // unregister binder for callbacks
  7251. try {
  7252. getService().unregisterCommunicationDeviceDispatcher(
  7253. mCommDevDispatcherStub);
  7254. } catch (RemoteException e) {
  7255. throw e.rethrowFromSystemServer();
  7256. } finally {
  7257. mCommDevDispatcherStub = null;
  7258. mCommDevListeners = null;
  7259. }
  7260. }
  7261. }
  7262. }
  7263. private final Object mCommDevListenerLock = new Object();
  7264. /**
  7265. * List of listeners for preferred device for strategy and their associated Executor.
  7266. * List is lazy-initialized on first registration
  7267. */
  7268. @GuardedBy("mCommDevListenerLock")
  7269. private @Nullable ArrayList<CommDevListenerInfo> mCommDevListeners;
  7270. private static class CommDevListenerInfo {
  7271. final @NonNull OnCommunicationDeviceChangedListener mListener;
  7272. final @NonNull Executor mExecutor;
  7273. CommDevListenerInfo(OnCommunicationDeviceChangedListener listener, Executor exe) {
  7274. mListener = listener;
  7275. mExecutor = exe;
  7276. }
  7277. }
  7278. @GuardedBy("mCommDevListenerLock")
  7279. private CommunicationDeviceDispatcherStub mCommDevDispatcherStub;
  7280. private final class CommunicationDeviceDispatcherStub
  7281. extends ICommunicationDeviceDispatcher.Stub {
  7282. @Override
  7283. public void dispatchCommunicationDeviceChanged(int portId) {
  7284. // make a shallow copy of listeners so callback is not executed under lock
  7285. final ArrayList<CommDevListenerInfo> commDevListeners;
  7286. synchronized (mCommDevListenerLock) {
  7287. if (mCommDevListeners == null || mCommDevListeners.size() == 0) {
  7288. return;
  7289. }
  7290. commDevListeners = (ArrayList<CommDevListenerInfo>) mCommDevListeners.clone();
  7291. }
  7292. AudioDeviceInfo device = getDeviceForPortId(portId, GET_DEVICES_OUTPUTS);
  7293. final long ident = Binder.clearCallingIdentity();
  7294. try {
  7295. for (CommDevListenerInfo info : commDevListeners) {
  7296. info.mExecutor.execute(() ->
  7297. info.mListener.onCommunicationDeviceChanged(device));
  7298. }
  7299. } finally {
  7300. Binder.restoreCallingIdentity(ident);
  7301. }
  7302. }
  7303. }
  7304. @GuardedBy("mCommDevListenerLock")
  7305. private @Nullable CommDevListenerInfo getCommDevListenerInfo(
  7306. OnCommunicationDeviceChangedListener listener) {
  7307. if (mCommDevListeners == null) {
  7308. return null;
  7309. }
  7310. for (CommDevListenerInfo info : mCommDevListeners) {
  7311. if (info.mListener == listener) {
  7312. return info;
  7313. }
  7314. }
  7315. return null;
  7316. }
  7317. @GuardedBy("mCommDevListenerLock")
  7318. private boolean hasCommDevListener(OnCommunicationDeviceChangedListener listener) {
  7319. return getCommDevListenerInfo(listener) != null;
  7320. }
  7321. @GuardedBy("mCommDevListenerLock")
  7322. /**
  7323. * @return true if the listener was removed from the list
  7324. */
  7325. private boolean removeCommDevListener(OnCommunicationDeviceChangedListener listener) {
  7326. final CommDevListenerInfo infoToRemove = getCommDevListenerInfo(listener);
  7327. if (infoToRemove != null) {
  7328. mCommDevListeners.remove(infoToRemove);
  7329. return true;
  7330. }
  7331. return false;
  7332. }
  7333. //---------------------------------------------------------
  7334. // Inner classes
  7335. //--------------------
  7336. /**
  7337. * Helper class to handle the forwarding of native events to the appropriate listener
  7338. * (potentially) handled in a different thread.
  7339. */
  7340. private class NativeEventHandlerDelegate {
  7341. private final Handler mHandler;
  7342. NativeEventHandlerDelegate(final AudioDeviceCallback callback,
  7343. Handler handler) {
  7344. // find the looper for our new event handler
  7345. Looper looper;
  7346. if (handler != null) {
  7347. looper = handler.getLooper();
  7348. } else {
  7349. // no given handler, use the looper the addListener call was called in
  7350. looper = Looper.getMainLooper();
  7351. }
  7352. // construct the event handler with this looper
  7353. if (looper != null) {
  7354. // implement the event handler delegate
  7355. mHandler = new Handler(looper) {
  7356. @Override
  7357. public void handleMessage(Message msg) {
  7358. switch(msg.what) {
  7359. case MSG_DEVICES_CALLBACK_REGISTERED:
  7360. case MSG_DEVICES_DEVICES_ADDED:
  7361. if (callback != null) {
  7362. callback.onAudioDevicesAdded((AudioDeviceInfo[])msg.obj);
  7363. }
  7364. break;
  7365. case MSG_DEVICES_DEVICES_REMOVED:
  7366. if (callback != null) {
  7367. callback.onAudioDevicesRemoved((AudioDeviceInfo[])msg.obj);
  7368. }
  7369. break;
  7370. default:
  7371. Log.e(TAG, "Unknown native event type: " + msg.what);
  7372. break;
  7373. }
  7374. }
  7375. };
  7376. } else {
  7377. mHandler = null;
  7378. }
  7379. }
  7380. Handler getHandler() {
  7381. return mHandler;
  7382. }
  7383. }
  7384. }