PageRenderTime 34ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/services/java/com/android/server/NotificationPlayer.java

https://github.com/sandy-slin/android_frameworks_base
Java | 344 lines | 232 code | 28 blank | 84 comment | 53 complexity | 729c529cd10f3d7a7e2c1c87befb2d0b MD5 | raw file
  1. /*
  2. * Copyright (C) 2008 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 com.android.server;
  17. import android.content.Context;
  18. import android.media.AudioManager;
  19. import android.media.MediaPlayer;
  20. import android.media.MediaPlayer.OnCompletionListener;
  21. import android.net.Uri;
  22. import android.os.Handler;
  23. import android.os.Looper;
  24. import android.os.Message;
  25. import android.os.PowerManager;
  26. import android.os.SystemClock;
  27. import android.provider.Settings;
  28. import android.util.Log;
  29. import java.io.IOException;
  30. import java.lang.IllegalStateException;
  31. import java.lang.Thread;
  32. import java.util.LinkedList;
  33. /**
  34. * @hide
  35. * This class is provides the same interface and functionality as android.media.AsyncPlayer
  36. * with the following differences:
  37. * - whenever audio is played, audio focus is requested,
  38. * - whenever audio playback is stopped or the playback completed, audio focus is abandoned.
  39. */
  40. public class NotificationPlayer implements OnCompletionListener {
  41. private static final int PLAY = 1;
  42. private static final int STOP = 2;
  43. private static final boolean mDebug = false;
  44. private static final class Command {
  45. int code;
  46. Context context;
  47. Uri uri;
  48. boolean looping;
  49. int stream;
  50. long requestTime;
  51. public String toString() {
  52. return "{ code=" + code + " looping=" + looping + " stream=" + stream
  53. + " uri=" + uri + " }";
  54. }
  55. }
  56. private LinkedList<Command> mCmdQueue = new LinkedList();
  57. private Looper mLooper;
  58. /*
  59. * Besides the use of audio focus, the only implementation difference between AsyncPlayer and
  60. * NotificationPlayer resides in the creation of the MediaPlayer. For the completion callback,
  61. * OnCompletionListener, to be called at the end of the playback, the MediaPlayer needs to
  62. * be created with a looper running so its event handler is not null.
  63. */
  64. private final class CreationAndCompletionThread extends Thread {
  65. public Command mCmd;
  66. public CreationAndCompletionThread(Command cmd) {
  67. super();
  68. mCmd = cmd;
  69. }
  70. public void run() {
  71. Looper.prepare();
  72. mLooper = Looper.myLooper();
  73. synchronized(this) {
  74. AudioManager audioManager =
  75. (AudioManager) mCmd.context.getSystemService(Context.AUDIO_SERVICE);
  76. try {
  77. MediaPlayer player = new MediaPlayer();
  78. player.setAudioStreamType(mCmd.stream);
  79. player.setDataSource(mCmd.context, mCmd.uri);
  80. player.setLooping(mCmd.looping);
  81. player.prepare();
  82. boolean requestFocus = Settings.System.getInt(mCmd.context.getContentResolver(),
  83. Settings.System.NOTIFICATIONS_AUDIO_FOCUS, 1) != 0;
  84. if (requestFocus && (mCmd.uri != null) && (mCmd.uri.getEncodedPath() != null)
  85. && (mCmd.uri.getEncodedPath().length() > 0)) {
  86. if (mCmd.looping) {
  87. audioManager.requestAudioFocus(null, mCmd.stream,
  88. AudioManager.AUDIOFOCUS_GAIN);
  89. } else {
  90. audioManager.requestAudioFocus(null, mCmd.stream,
  91. AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
  92. }
  93. }
  94. player.setOnCompletionListener(NotificationPlayer.this);
  95. player.start();
  96. if (mPlayer != null) {
  97. mPlayer.release();
  98. }
  99. mPlayer = player;
  100. }
  101. catch (Exception e) {
  102. Log.w(mTag, "error loading sound for " + mCmd.uri, e);
  103. }
  104. mAudioManager = audioManager;
  105. this.notify();
  106. }
  107. Looper.loop();
  108. }
  109. };
  110. private void startSound(Command cmd) {
  111. // Preparing can be slow, so if there is something else
  112. // is playing, let it continue until we're done, so there
  113. // is less of a glitch.
  114. try {
  115. if (mDebug) Log.d(mTag, "Starting playback");
  116. //-----------------------------------
  117. // This is were we deviate from the AsyncPlayer implementation and create the
  118. // MediaPlayer in a new thread with which we're synchronized
  119. synchronized(mCompletionHandlingLock) {
  120. // if another sound was already playing, it doesn't matter we won't get notified
  121. // of the completion, since only the completion notification of the last sound
  122. // matters
  123. if((mLooper != null)
  124. && (mLooper.getThread().getState() != Thread.State.TERMINATED)) {
  125. mLooper.quit();
  126. }
  127. mCompletionThread = new CreationAndCompletionThread(cmd);
  128. synchronized(mCompletionThread) {
  129. mCompletionThread.start();
  130. mCompletionThread.wait();
  131. }
  132. }
  133. //-----------------------------------
  134. long delay = SystemClock.uptimeMillis() - cmd.requestTime;
  135. if (delay > 1000) {
  136. Log.w(mTag, "Notification sound delayed by " + delay + "msecs");
  137. }
  138. }
  139. catch (Exception e) {
  140. Log.w(mTag, "error loading sound for " + cmd.uri, e);
  141. }
  142. }
  143. private final class CmdThread extends java.lang.Thread {
  144. CmdThread() {
  145. super("NotificationPlayer-" + mTag);
  146. }
  147. public void run() {
  148. while (true) {
  149. Command cmd = null;
  150. synchronized (mCmdQueue) {
  151. if (mDebug) Log.d(mTag, "RemoveFirst");
  152. cmd = mCmdQueue.removeFirst();
  153. }
  154. switch (cmd.code) {
  155. case PLAY:
  156. if (mDebug) Log.d(mTag, "PLAY");
  157. startSound(cmd);
  158. break;
  159. case STOP:
  160. if (mDebug) Log.d(mTag, "STOP");
  161. if (mPlayer != null) {
  162. long delay = SystemClock.uptimeMillis() - cmd.requestTime;
  163. if (delay > 1000) {
  164. Log.w(mTag, "Notification stop delayed by " + delay + "msecs");
  165. }
  166. mPlayer.stop();
  167. mPlayer.release();
  168. mPlayer = null;
  169. mAudioManager.abandonAudioFocus(null);
  170. mAudioManager = null;
  171. if((mLooper != null)
  172. && (mLooper.getThread().getState() != Thread.State.TERMINATED)) {
  173. mLooper.quit();
  174. }
  175. } else {
  176. Log.w(mTag, "STOP command without a player");
  177. }
  178. break;
  179. }
  180. synchronized (mCmdQueue) {
  181. if (mCmdQueue.size() == 0) {
  182. // nothing left to do, quit
  183. // doing this check after we're done prevents the case where they
  184. // added it during the operation from spawning two threads and
  185. // trying to do them in parallel.
  186. mThread = null;
  187. releaseWakeLock();
  188. return;
  189. }
  190. }
  191. }
  192. }
  193. }
  194. public void onCompletion(MediaPlayer mp) {
  195. if (mAudioManager != null) {
  196. mAudioManager.abandonAudioFocus(null);
  197. }
  198. // if there are no more sounds to play, end the Looper to listen for media completion
  199. synchronized (mCmdQueue) {
  200. if (mCmdQueue.size() == 0) {
  201. synchronized(mCompletionHandlingLock) {
  202. if(mLooper != null) {
  203. mLooper.quit();
  204. }
  205. mCompletionThread = null;
  206. }
  207. }
  208. }
  209. }
  210. private String mTag;
  211. private CmdThread mThread;
  212. private CreationAndCompletionThread mCompletionThread;
  213. private final Object mCompletionHandlingLock = new Object();
  214. private MediaPlayer mPlayer;
  215. private PowerManager.WakeLock mWakeLock;
  216. private AudioManager mAudioManager;
  217. // The current state according to the caller. Reality lags behind
  218. // because of the asynchronous nature of this class.
  219. private int mState = STOP;
  220. /**
  221. * Construct a NotificationPlayer object.
  222. *
  223. * @param tag a string to use for debugging
  224. */
  225. public NotificationPlayer(String tag) {
  226. if (tag != null) {
  227. mTag = tag;
  228. } else {
  229. mTag = "NotificationPlayer";
  230. }
  231. }
  232. /**
  233. * Start playing the sound. It will actually start playing at some
  234. * point in the future. There are no guarantees about latency here.
  235. * Calling this before another audio file is done playing will stop
  236. * that one and start the new one.
  237. *
  238. * @param context Your application's context.
  239. * @param uri The URI to play. (see {@link MediaPlayer#setDataSource(Context, Uri)})
  240. * @param looping Whether the audio should loop forever.
  241. * (see {@link MediaPlayer#setLooping(boolean)})
  242. * @param stream the AudioStream to use.
  243. * (see {@link MediaPlayer#setAudioStreamType(int)})
  244. */
  245. public void play(Context context, Uri uri, boolean looping, int stream) {
  246. Command cmd = new Command();
  247. cmd.requestTime = SystemClock.uptimeMillis();
  248. cmd.code = PLAY;
  249. cmd.context = context;
  250. cmd.uri = uri;
  251. cmd.looping = looping;
  252. cmd.stream = stream;
  253. synchronized (mCmdQueue) {
  254. enqueueLocked(cmd);
  255. mState = PLAY;
  256. }
  257. }
  258. /**
  259. * Stop a previously played sound. It can't be played again or unpaused
  260. * at this point. Calling this multiple times has no ill effects.
  261. */
  262. public void stop() {
  263. synchronized (mCmdQueue) {
  264. // This check allows stop to be called multiple times without starting
  265. // a thread that ends up doing nothing.
  266. if (mState != STOP) {
  267. Command cmd = new Command();
  268. cmd.requestTime = SystemClock.uptimeMillis();
  269. cmd.code = STOP;
  270. enqueueLocked(cmd);
  271. mState = STOP;
  272. }
  273. }
  274. }
  275. private void enqueueLocked(Command cmd) {
  276. mCmdQueue.add(cmd);
  277. if (mThread == null) {
  278. acquireWakeLock();
  279. mThread = new CmdThread();
  280. mThread.start();
  281. }
  282. }
  283. /**
  284. * We want to hold a wake lock while we do the prepare and play. The stop probably is
  285. * optional, but it won't hurt to have it too. The problem is that if you start a sound
  286. * while you're holding a wake lock (e.g. an alarm starting a notification), you want the
  287. * sound to play, but if the CPU turns off before mThread gets to work, it won't. The
  288. * simplest way to deal with this is to make it so there is a wake lock held while the
  289. * thread is starting or running. You're going to need the WAKE_LOCK permission if you're
  290. * going to call this.
  291. *
  292. * This must be called before the first time play is called.
  293. *
  294. * @hide
  295. */
  296. public void setUsesWakeLock(Context context) {
  297. if (mWakeLock != null || mThread != null) {
  298. // if either of these has happened, we've already played something.
  299. // and our releases will be out of sync.
  300. throw new RuntimeException("assertion failed mWakeLock=" + mWakeLock
  301. + " mThread=" + mThread);
  302. }
  303. PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
  304. mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, mTag);
  305. }
  306. private void acquireWakeLock() {
  307. if (mWakeLock != null) {
  308. mWakeLock.acquire();
  309. }
  310. }
  311. private void releaseWakeLock() {
  312. if (mWakeLock != null) {
  313. mWakeLock.release();
  314. }
  315. }
  316. }