PageRenderTime 50ms CodeModel.GetById 6ms RepoModel.GetById 3ms app.codeStats 1ms

/src/com/android/music/MediaPlaybackService.java

https://github.com/ldnladiesman217/android_packages_apps_StockMusic
Java | 1283 lines | 954 code | 104 blank | 225 comment | 263 complexity | 565c187e2d77105c3191be45d49fa5cd 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 com.android.music;
  17. import android.app.Notification;
  18. import android.app.PendingIntent;
  19. import android.app.Service;
  20. import android.appwidget.AppWidgetManager;
  21. import android.content.ComponentName;
  22. import android.content.ContentResolver;
  23. import android.content.ContentUris;
  24. import android.content.ContentValues;
  25. import android.content.Context;
  26. import android.content.Intent;
  27. import android.content.IntentFilter;
  28. import android.content.BroadcastReceiver;
  29. import android.content.SharedPreferences;
  30. import android.content.SharedPreferences.Editor;
  31. import android.database.Cursor;
  32. import android.database.sqlite.SQLiteException;
  33. import android.media.AudioManager;
  34. import android.media.AudioManager.OnAudioFocusChangeListener;
  35. import android.media.MediaPlayer;
  36. import android.net.Uri;
  37. import android.os.Handler;
  38. import android.os.IBinder;
  39. import android.os.Message;
  40. import android.os.PowerManager;
  41. import android.os.SystemClock;
  42. import android.os.PowerManager.WakeLock;
  43. import android.provider.MediaStore;
  44. import android.telephony.PhoneStateListener;
  45. import android.telephony.TelephonyManager;
  46. import android.util.Log;
  47. import android.widget.RemoteViews;
  48. import android.widget.Toast;
  49. import java.io.FileDescriptor;
  50. import java.io.IOException;
  51. import java.io.PrintWriter;
  52. import java.lang.ref.WeakReference;
  53. import java.util.Random;
  54. import java.util.Vector;
  55. /**
  56. * Provides "background" audio playback capabilities, allowing the
  57. * user to switch between activities without stopping playback.
  58. */
  59. public class MediaPlaybackService extends Service {
  60. /** used to specify whether enqueue() should start playing
  61. * the new list of files right away, next or once all the currently
  62. * queued files have been played
  63. */
  64. public static final int NOW = 1;
  65. public static final int NEXT = 2;
  66. public static final int LAST = 3;
  67. public static final int PLAYBACKSERVICE_STATUS = 1;
  68. public static final int SHUFFLE_NONE = 0;
  69. public static final int SHUFFLE_NORMAL = 1;
  70. public static final int SHUFFLE_AUTO = 2;
  71. public static final int REPEAT_NONE = 0;
  72. public static final int REPEAT_CURRENT = 1;
  73. public static final int REPEAT_ALL = 2;
  74. public static final String PLAYSTATE_CHANGED = "com.android.music.playstatechanged";
  75. public static final String META_CHANGED = "com.android.music.metachanged";
  76. public static final String QUEUE_CHANGED = "com.android.music.queuechanged";
  77. public static final String PLAYBACK_COMPLETE = "com.android.music.playbackcomplete";
  78. public static final String ASYNC_OPEN_COMPLETE = "com.android.music.asyncopencomplete";
  79. public static final String SERVICECMD = "com.android.music.musicservicecommand";
  80. public static final String CMDNAME = "command";
  81. public static final String CMDTOGGLEPAUSE = "togglepause";
  82. public static final String CMDSTOP = "stop";
  83. public static final String CMDPAUSE = "pause";
  84. public static final String CMDPREVIOUS = "previous";
  85. public static final String CMDNEXT = "next";
  86. public static final String TOGGLEPAUSE_ACTION = "com.android.music.musicservicecommand.togglepause";
  87. public static final String PAUSE_ACTION = "com.android.music.musicservicecommand.pause";
  88. public static final String PREVIOUS_ACTION = "com.android.music.musicservicecommand.previous";
  89. public static final String NEXT_ACTION = "com.android.music.musicservicecommand.next";
  90. private static final int TRACK_ENDED = 1;
  91. private static final int RELEASE_WAKELOCK = 2;
  92. private static final int SERVER_DIED = 3;
  93. private static final int FADEIN = 4;
  94. private static final int MAX_HISTORY_SIZE = 100;
  95. private MultiPlayer mPlayer;
  96. private String mFileToPlay;
  97. private int mShuffleMode = SHUFFLE_NONE;
  98. private int mRepeatMode = REPEAT_NONE;
  99. private int mMediaMountedCount = 0;
  100. private long [] mAutoShuffleList = null;
  101. private boolean mOneShot;
  102. private long [] mPlayList = null;
  103. private int mPlayListLen = 0;
  104. private Vector<Integer> mHistory = new Vector<Integer>(MAX_HISTORY_SIZE);
  105. private Cursor mCursor;
  106. private int mPlayPos = -1;
  107. private static final String LOGTAG = "MediaPlaybackService";
  108. private final Shuffler mRand = new Shuffler();
  109. private int mOpenFailedCounter = 0;
  110. String[] mCursorCols = new String[] {
  111. "audio._id AS _id", // index must match IDCOLIDX below
  112. MediaStore.Audio.Media.ARTIST,
  113. MediaStore.Audio.Media.ALBUM,
  114. MediaStore.Audio.Media.TITLE,
  115. MediaStore.Audio.Media.DATA,
  116. MediaStore.Audio.Media.MIME_TYPE,
  117. MediaStore.Audio.Media.ALBUM_ID,
  118. MediaStore.Audio.Media.ARTIST_ID,
  119. MediaStore.Audio.Media.IS_PODCAST, // index must match PODCASTCOLIDX below
  120. MediaStore.Audio.Media.BOOKMARK // index must match BOOKMARKCOLIDX below
  121. };
  122. private final static int IDCOLIDX = 0;
  123. private final static int PODCASTCOLIDX = 8;
  124. private final static int BOOKMARKCOLIDX = 9;
  125. private BroadcastReceiver mUnmountReceiver = null;
  126. private WakeLock mWakeLock;
  127. private int mServiceStartId = -1;
  128. private boolean mServiceInUse = false;
  129. private boolean mIsSupposedToBePlaying = false;
  130. private boolean mQuietMode = false;
  131. private AudioManager mAudioManager;
  132. // used to track what type of audio focus loss caused the playback to pause
  133. private boolean mPausedByTransientLossOfFocus = false;
  134. private SharedPreferences mPreferences;
  135. // We use this to distinguish between different cards when saving/restoring playlists.
  136. // This will have to change if we want to support multiple simultaneous cards.
  137. private int mCardId;
  138. private MediaAppWidgetProvider mAppWidgetProvider = MediaAppWidgetProvider.getInstance();
  139. // interval after which we stop the service when idle
  140. private static final int IDLE_DELAY = 60000;
  141. private void startAndFadeIn() {
  142. mMediaplayerHandler.sendEmptyMessageDelayed(FADEIN, 10);
  143. }
  144. private Handler mMediaplayerHandler = new Handler() {
  145. float mCurrentVolume = 1.0f;
  146. @Override
  147. public void handleMessage(Message msg) {
  148. MusicUtils.debugLog("mMediaplayerHandler.handleMessage " + msg.what);
  149. switch (msg.what) {
  150. case FADEIN:
  151. if (!isPlaying()) {
  152. mCurrentVolume = 0f;
  153. mPlayer.setVolume(mCurrentVolume);
  154. play();
  155. mMediaplayerHandler.sendEmptyMessageDelayed(FADEIN, 10);
  156. } else {
  157. mCurrentVolume += 0.01f;
  158. if (mCurrentVolume < 1.0f) {
  159. mMediaplayerHandler.sendEmptyMessageDelayed(FADEIN, 10);
  160. } else {
  161. mCurrentVolume = 1.0f;
  162. }
  163. mPlayer.setVolume(mCurrentVolume);
  164. }
  165. break;
  166. case SERVER_DIED:
  167. if (mIsSupposedToBePlaying) {
  168. next(true);
  169. } else {
  170. // the server died when we were idle, so just
  171. // reopen the same song (it will start again
  172. // from the beginning though when the user
  173. // restarts)
  174. openCurrent();
  175. }
  176. break;
  177. case TRACK_ENDED:
  178. if (mRepeatMode == REPEAT_CURRENT) {
  179. seek(0);
  180. play();
  181. } else if (!mOneShot) {
  182. next(false);
  183. } else {
  184. notifyChange(PLAYBACK_COMPLETE);
  185. mIsSupposedToBePlaying = false;
  186. }
  187. break;
  188. case RELEASE_WAKELOCK:
  189. mWakeLock.release();
  190. break;
  191. default:
  192. break;
  193. }
  194. }
  195. };
  196. private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
  197. @Override
  198. public void onReceive(Context context, Intent intent) {
  199. String action = intent.getAction();
  200. String cmd = intent.getStringExtra("command");
  201. MusicUtils.debugLog("mIntentReceiver.onReceive " + action + " / " + cmd);
  202. if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
  203. next(true);
  204. } else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
  205. prev();
  206. } else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
  207. if (isPlaying()) {
  208. pause();
  209. mPausedByTransientLossOfFocus = false;
  210. } else {
  211. play();
  212. }
  213. } else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
  214. pause();
  215. mPausedByTransientLossOfFocus = false;
  216. } else if (CMDSTOP.equals(cmd)) {
  217. pause();
  218. mPausedByTransientLossOfFocus = false;
  219. seek(0);
  220. } else if (MediaAppWidgetProvider.CMDAPPWIDGETUPDATE.equals(cmd)) {
  221. // Someone asked us to refresh a set of specific widgets, probably
  222. // because they were just added.
  223. int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
  224. mAppWidgetProvider.performUpdate(MediaPlaybackService.this, appWidgetIds);
  225. }
  226. }
  227. };
  228. private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
  229. public void onAudioFocusChange(int focusChange) {
  230. // AudioFocus is a new feature: focus updates are made verbose on purpose
  231. switch (focusChange) {
  232. case AudioManager.AUDIOFOCUS_LOSS:
  233. Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS");
  234. if(isPlaying()) {
  235. mPausedByTransientLossOfFocus = false;
  236. pause();
  237. }
  238. break;
  239. case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
  240. case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
  241. Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT");
  242. if(isPlaying()) {
  243. mPausedByTransientLossOfFocus = true;
  244. pause();
  245. }
  246. break;
  247. case AudioManager.AUDIOFOCUS_GAIN:
  248. Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_GAIN");
  249. if(!isPlaying() && mPausedByTransientLossOfFocus) {
  250. mPausedByTransientLossOfFocus = false;
  251. startAndFadeIn();
  252. }
  253. break;
  254. default:
  255. Log.e(LOGTAG, "Unknown audio focus change code");
  256. }
  257. }
  258. };
  259. public MediaPlaybackService() {
  260. }
  261. @Override
  262. public void onCreate() {
  263. super.onCreate();
  264. mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  265. mAudioManager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(),
  266. MediaButtonIntentReceiver.class.getName()));
  267. mPreferences = getSharedPreferences("Music", MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
  268. mCardId = MusicUtils.getCardId(this);
  269. registerExternalStorageListener();
  270. // Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
  271. mPlayer = new MultiPlayer();
  272. mPlayer.setHandler(mMediaplayerHandler);
  273. reloadQueue();
  274. IntentFilter commandFilter = new IntentFilter();
  275. commandFilter.addAction(SERVICECMD);
  276. commandFilter.addAction(TOGGLEPAUSE_ACTION);
  277. commandFilter.addAction(PAUSE_ACTION);
  278. commandFilter.addAction(NEXT_ACTION);
  279. commandFilter.addAction(PREVIOUS_ACTION);
  280. registerReceiver(mIntentReceiver, commandFilter);
  281. PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
  282. mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
  283. mWakeLock.setReferenceCounted(false);
  284. // If the service was idle, but got killed before it stopped itself, the
  285. // system will relaunch it. Make sure it gets stopped again in that case.
  286. Message msg = mDelayedStopHandler.obtainMessage();
  287. mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
  288. }
  289. @Override
  290. public void onDestroy() {
  291. // Check that we're not being destroyed while something is still playing.
  292. if (isPlaying()) {
  293. Log.e(LOGTAG, "Service being destroyed while still playing.");
  294. }
  295. // release all MediaPlayer resources, including the native player and wakelocks
  296. mPlayer.release();
  297. mPlayer = null;
  298. mAudioManager.abandonAudioFocus(mAudioFocusListener);
  299. // make sure there aren't any other messages coming
  300. mDelayedStopHandler.removeCallbacksAndMessages(null);
  301. mMediaplayerHandler.removeCallbacksAndMessages(null);
  302. if (mCursor != null) {
  303. mCursor.close();
  304. mCursor = null;
  305. }
  306. unregisterReceiver(mIntentReceiver);
  307. if (mUnmountReceiver != null) {
  308. unregisterReceiver(mUnmountReceiver);
  309. mUnmountReceiver = null;
  310. }
  311. mWakeLock.release();
  312. super.onDestroy();
  313. }
  314. private final char hexdigits [] = new char [] {
  315. '0', '1', '2', '3',
  316. '4', '5', '6', '7',
  317. '8', '9', 'a', 'b',
  318. 'c', 'd', 'e', 'f'
  319. };
  320. private void saveQueue(boolean full) {
  321. if (mOneShot) {
  322. return;
  323. }
  324. Editor ed = mPreferences.edit();
  325. //long start = System.currentTimeMillis();
  326. if (full) {
  327. StringBuilder q = new StringBuilder();
  328. // The current playlist is saved as a list of "reverse hexadecimal"
  329. // numbers, which we can generate faster than normal decimal or
  330. // hexadecimal numbers, which in turn allows us to save the playlist
  331. // more often without worrying too much about performance.
  332. // (saving the full state takes about 40 ms under no-load conditions
  333. // on the phone)
  334. int len = mPlayListLen;
  335. for (int i = 0; i < len; i++) {
  336. long n = mPlayList[i];
  337. if (n == 0) {
  338. q.append("0;");
  339. } else {
  340. while (n != 0) {
  341. int digit = (int)(n & 0xf);
  342. n >>= 4;
  343. q.append(hexdigits[digit]);
  344. }
  345. q.append(";");
  346. }
  347. }
  348. //Log.i("@@@@ service", "created queue string in " + (System.currentTimeMillis() - start) + " ms");
  349. ed.putString("queue", q.toString());
  350. ed.putInt("cardid", mCardId);
  351. if (mShuffleMode != SHUFFLE_NONE) {
  352. // In shuffle mode we need to save the history too
  353. len = mHistory.size();
  354. q.setLength(0);
  355. for (int i = 0; i < len; i++) {
  356. int n = mHistory.get(i);
  357. if (n == 0) {
  358. q.append("0;");
  359. } else {
  360. while (n != 0) {
  361. int digit = (n & 0xf);
  362. n >>= 4;
  363. q.append(hexdigits[digit]);
  364. }
  365. q.append(";");
  366. }
  367. }
  368. ed.putString("history", q.toString());
  369. }
  370. }
  371. ed.putInt("curpos", mPlayPos);
  372. if (mPlayer.isInitialized()) {
  373. ed.putLong("seekpos", mPlayer.position());
  374. }
  375. ed.putInt("repeatmode", mRepeatMode);
  376. ed.putInt("shufflemode", mShuffleMode);
  377. ed.commit();
  378. //Log.i("@@@@ service", "saved state in " + (System.currentTimeMillis() - start) + " ms");
  379. }
  380. private void reloadQueue() {
  381. String q = null;
  382. boolean newstyle = false;
  383. int id = mCardId;
  384. if (mPreferences.contains("cardid")) {
  385. newstyle = true;
  386. id = mPreferences.getInt("cardid", ~mCardId);
  387. }
  388. if (id == mCardId) {
  389. // Only restore the saved playlist if the card is still
  390. // the same one as when the playlist was saved
  391. q = mPreferences.getString("queue", "");
  392. }
  393. int qlen = q != null ? q.length() : 0;
  394. if (qlen > 1) {
  395. //Log.i("@@@@ service", "loaded queue: " + q);
  396. int plen = 0;
  397. int n = 0;
  398. int shift = 0;
  399. for (int i = 0; i < qlen; i++) {
  400. char c = q.charAt(i);
  401. if (c == ';') {
  402. ensurePlayListCapacity(plen + 1);
  403. mPlayList[plen] = n;
  404. plen++;
  405. n = 0;
  406. shift = 0;
  407. } else {
  408. if (c >= '0' && c <= '9') {
  409. n += ((c - '0') << shift);
  410. } else if (c >= 'a' && c <= 'f') {
  411. n += ((10 + c - 'a') << shift);
  412. } else {
  413. // bogus playlist data
  414. plen = 0;
  415. break;
  416. }
  417. shift += 4;
  418. }
  419. }
  420. mPlayListLen = plen;
  421. int pos = mPreferences.getInt("curpos", 0);
  422. if (pos < 0 || pos >= mPlayListLen) {
  423. // The saved playlist is bogus, discard it
  424. mPlayListLen = 0;
  425. return;
  426. }
  427. mPlayPos = pos;
  428. // When reloadQueue is called in response to a card-insertion,
  429. // we might not be able to query the media provider right away.
  430. // To deal with this, try querying for the current file, and if
  431. // that fails, wait a while and try again. If that too fails,
  432. // assume there is a problem and don't restore the state.
  433. Cursor crsr = MusicUtils.query(this,
  434. MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
  435. new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
  436. if (crsr == null || crsr.getCount() == 0) {
  437. // wait a bit and try again
  438. SystemClock.sleep(3000);
  439. crsr = getContentResolver().query(
  440. MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
  441. mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
  442. }
  443. if (crsr != null) {
  444. crsr.close();
  445. }
  446. // Make sure we don't auto-skip to the next song, since that
  447. // also starts playback. What could happen in that case is:
  448. // - music is paused
  449. // - go to UMS and delete some files, including the currently playing one
  450. // - come back from UMS
  451. // (time passes)
  452. // - music app is killed for some reason (out of memory)
  453. // - music service is restarted, service restores state, doesn't find
  454. // the "current" file, goes to the next and: playback starts on its
  455. // own, potentially at some random inconvenient time.
  456. mOpenFailedCounter = 20;
  457. mQuietMode = true;
  458. openCurrent();
  459. mQuietMode = false;
  460. if (!mPlayer.isInitialized()) {
  461. // couldn't restore the saved state
  462. mPlayListLen = 0;
  463. return;
  464. }
  465. long seekpos = mPreferences.getLong("seekpos", 0);
  466. seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
  467. Log.d(LOGTAG, "restored queue, currently at position "
  468. + position() + "/" + duration()
  469. + " (requested " + seekpos + ")");
  470. int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
  471. if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
  472. repmode = REPEAT_NONE;
  473. }
  474. mRepeatMode = repmode;
  475. int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
  476. if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
  477. shufmode = SHUFFLE_NONE;
  478. }
  479. if (shufmode != SHUFFLE_NONE) {
  480. // in shuffle mode we need to restore the history too
  481. q = mPreferences.getString("history", "");
  482. qlen = q != null ? q.length() : 0;
  483. if (qlen > 1) {
  484. plen = 0;
  485. n = 0;
  486. shift = 0;
  487. mHistory.clear();
  488. for (int i = 0; i < qlen; i++) {
  489. char c = q.charAt(i);
  490. if (c == ';') {
  491. if (n >= mPlayListLen) {
  492. // bogus history data
  493. mHistory.clear();
  494. break;
  495. }
  496. mHistory.add(n);
  497. n = 0;
  498. shift = 0;
  499. } else {
  500. if (c >= '0' && c <= '9') {
  501. n += ((c - '0') << shift);
  502. } else if (c >= 'a' && c <= 'f') {
  503. n += ((10 + c - 'a') << shift);
  504. } else {
  505. // bogus history data
  506. mHistory.clear();
  507. break;
  508. }
  509. shift += 4;
  510. }
  511. }
  512. }
  513. }
  514. if (shufmode == SHUFFLE_AUTO) {
  515. if (! makeAutoShuffleList()) {
  516. shufmode = SHUFFLE_NONE;
  517. }
  518. }
  519. mShuffleMode = shufmode;
  520. }
  521. }
  522. @Override
  523. public IBinder onBind(Intent intent) {
  524. mDelayedStopHandler.removeCallbacksAndMessages(null);
  525. mServiceInUse = true;
  526. return mBinder;
  527. }
  528. @Override
  529. public void onRebind(Intent intent) {
  530. mDelayedStopHandler.removeCallbacksAndMessages(null);
  531. mServiceInUse = true;
  532. }
  533. @Override
  534. public int onStartCommand(Intent intent, int flags, int startId) {
  535. mServiceStartId = startId;
  536. mDelayedStopHandler.removeCallbacksAndMessages(null);
  537. if (intent != null) {
  538. String action = intent.getAction();
  539. String cmd = intent.getStringExtra("command");
  540. MusicUtils.debugLog("onStartCommand " + action + " / " + cmd);
  541. if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
  542. next(true);
  543. } else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
  544. if (position() < 2000) {
  545. prev();
  546. } else {
  547. seek(0);
  548. play();
  549. }
  550. } else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
  551. if (isPlaying()) {
  552. pause();
  553. mPausedByTransientLossOfFocus = false;
  554. } else {
  555. play();
  556. }
  557. } else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
  558. pause();
  559. mPausedByTransientLossOfFocus = false;
  560. } else if (CMDSTOP.equals(cmd)) {
  561. pause();
  562. mPausedByTransientLossOfFocus = false;
  563. seek(0);
  564. }
  565. }
  566. // make sure the service will shut down on its own if it was
  567. // just started but not bound to and nothing is playing
  568. mDelayedStopHandler.removeCallbacksAndMessages(null);
  569. Message msg = mDelayedStopHandler.obtainMessage();
  570. mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
  571. return START_STICKY;
  572. }
  573. @Override
  574. public boolean onUnbind(Intent intent) {
  575. mServiceInUse = false;
  576. // Take a snapshot of the current playlist
  577. saveQueue(true);
  578. if (isPlaying() || mPausedByTransientLossOfFocus) {
  579. // something is currently playing, or will be playing once
  580. // an in-progress action requesting audio focus ends, so don't stop the service now.
  581. return true;
  582. }
  583. // If there is a playlist but playback is paused, then wait a while
  584. // before stopping the service, so that pause/resume isn't slow.
  585. // Also delay stopping the service if we're transitioning between tracks.
  586. if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
  587. Message msg = mDelayedStopHandler.obtainMessage();
  588. mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
  589. return true;
  590. }
  591. // No active playlist, OK to stop the service right now
  592. stopSelf(mServiceStartId);
  593. return true;
  594. }
  595. private Handler mDelayedStopHandler = new Handler() {
  596. @Override
  597. public void handleMessage(Message msg) {
  598. // Check again to make sure nothing is playing right now
  599. if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse
  600. || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
  601. return;
  602. }
  603. // save the queue again, because it might have changed
  604. // since the user exited the music app (because of
  605. // party-shuffle or because the play-position changed)
  606. saveQueue(true);
  607. stopSelf(mServiceStartId);
  608. }
  609. };
  610. /**
  611. * Called when we receive a ACTION_MEDIA_EJECT notification.
  612. *
  613. * @param storagePath path to mount point for the removed media
  614. */
  615. public void closeExternalStorageFiles(String storagePath) {
  616. // stop playback and clean up if the SD card is going to be unmounted.
  617. stop(true);
  618. notifyChange(QUEUE_CHANGED);
  619. notifyChange(META_CHANGED);
  620. }
  621. /**
  622. * Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
  623. * The intent will call closeExternalStorageFiles() if the external media
  624. * is going to be ejected, so applications can clean up any files they have open.
  625. */
  626. public void registerExternalStorageListener() {
  627. if (mUnmountReceiver == null) {
  628. mUnmountReceiver = new BroadcastReceiver() {
  629. @Override
  630. public void onReceive(Context context, Intent intent) {
  631. String action = intent.getAction();
  632. if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
  633. saveQueue(true);
  634. mOneShot = true; // This makes us not save the state again later,
  635. // which would be wrong because the song ids and
  636. // card id might not match.
  637. closeExternalStorageFiles(intent.getData().getPath());
  638. } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
  639. mMediaMountedCount++;
  640. mCardId = MusicUtils.getCardId(MediaPlaybackService.this);
  641. reloadQueue();
  642. notifyChange(QUEUE_CHANGED);
  643. notifyChange(META_CHANGED);
  644. }
  645. }
  646. };
  647. IntentFilter iFilter = new IntentFilter();
  648. iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
  649. iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
  650. iFilter.addDataScheme("file");
  651. registerReceiver(mUnmountReceiver, iFilter);
  652. }
  653. }
  654. /**
  655. * Notify the change-receivers that something has changed.
  656. * The intent that is sent contains the following data
  657. * for the currently playing track:
  658. * "id" - Integer: the database row ID
  659. * "artist" - String: the name of the artist
  660. * "album" - String: the name of the album
  661. * "track" - String: the name of the track
  662. * The intent has an action that is one of
  663. * "com.android.music.metachanged"
  664. * "com.android.music.queuechanged",
  665. * "com.android.music.playbackcomplete"
  666. * "com.android.music.playstatechanged"
  667. * respectively indicating that a new track has
  668. * started playing, that the playback queue has
  669. * changed, that playback has stopped because
  670. * the last file in the list has been played,
  671. * or that the play-state changed (paused/resumed).
  672. */
  673. private void notifyChange(String what) {
  674. Intent i = new Intent(what);
  675. i.putExtra("id", Long.valueOf(getAudioId()));
  676. i.putExtra("artist", getArtistName());
  677. i.putExtra("album",getAlbumName());
  678. i.putExtra("track", getTrackName());
  679. sendBroadcast(i);
  680. if (what.equals(QUEUE_CHANGED)) {
  681. saveQueue(true);
  682. } else {
  683. saveQueue(false);
  684. }
  685. // Share this notification directly with our widgets
  686. mAppWidgetProvider.notifyChange(this, what);
  687. }
  688. private void ensurePlayListCapacity(int size) {
  689. if (mPlayList == null || size > mPlayList.length) {
  690. // reallocate at 2x requested size so we don't
  691. // need to grow and copy the array for every
  692. // insert
  693. long [] newlist = new long[size * 2];
  694. int len = mPlayList != null ? mPlayList.length : mPlayListLen;
  695. for (int i = 0; i < len; i++) {
  696. newlist[i] = mPlayList[i];
  697. }
  698. mPlayList = newlist;
  699. }
  700. // FIXME: shrink the array when the needed size is much smaller
  701. // than the allocated size
  702. }
  703. // insert the list of songs at the specified position in the playlist
  704. private void addToPlayList(long [] list, int position) {
  705. int addlen = list.length;
  706. if (position < 0) { // overwrite
  707. mPlayListLen = 0;
  708. position = 0;
  709. }
  710. ensurePlayListCapacity(mPlayListLen + addlen);
  711. if (position > mPlayListLen) {
  712. position = mPlayListLen;
  713. }
  714. // move part of list after insertion point
  715. int tailsize = mPlayListLen - position;
  716. for (int i = tailsize ; i > 0 ; i--) {
  717. mPlayList[position + i] = mPlayList[position + i - addlen];
  718. }
  719. // copy list into playlist
  720. for (int i = 0; i < addlen; i++) {
  721. mPlayList[position + i] = list[i];
  722. }
  723. mPlayListLen += addlen;
  724. }
  725. /**
  726. * Appends a list of tracks to the current playlist.
  727. * If nothing is playing currently, playback will be started at
  728. * the first track.
  729. * If the action is NOW, playback will switch to the first of
  730. * the new tracks immediately.
  731. * @param list The list of tracks to append.
  732. * @param action NOW, NEXT or LAST
  733. */
  734. public void enqueue(long [] list, int action) {
  735. synchronized(this) {
  736. if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
  737. addToPlayList(list, mPlayPos + 1);
  738. notifyChange(QUEUE_CHANGED);
  739. } else {
  740. // action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
  741. addToPlayList(list, Integer.MAX_VALUE);
  742. notifyChange(QUEUE_CHANGED);
  743. if (action == NOW) {
  744. mPlayPos = mPlayListLen - list.length;
  745. openCurrent();
  746. play();
  747. notifyChange(META_CHANGED);
  748. return;
  749. }
  750. }
  751. if (mPlayPos < 0) {
  752. mPlayPos = 0;
  753. openCurrent();
  754. play();
  755. notifyChange(META_CHANGED);
  756. }
  757. }
  758. }
  759. /**
  760. * Replaces the current playlist with a new list,
  761. * and prepares for starting playback at the specified
  762. * position in the list, or a random position if the
  763. * specified position is 0.
  764. * @param list The new list of tracks.
  765. */
  766. public void open(long [] list, int position) {
  767. synchronized (this) {
  768. if (mShuffleMode == SHUFFLE_AUTO) {
  769. mShuffleMode = SHUFFLE_NORMAL;
  770. }
  771. long oldId = getAudioId();
  772. int listlength = list.length;
  773. boolean newlist = true;
  774. if (mPlayListLen == listlength) {
  775. // possible fast path: list might be the same
  776. newlist = false;
  777. for (int i = 0; i < listlength; i++) {
  778. if (list[i] != mPlayList[i]) {
  779. newlist = true;
  780. break;
  781. }
  782. }
  783. }
  784. if (newlist) {
  785. addToPlayList(list, -1);
  786. notifyChange(QUEUE_CHANGED);
  787. }
  788. int oldpos = mPlayPos;
  789. if (position >= 0) {
  790. mPlayPos = position;
  791. } else {
  792. mPlayPos = mRand.nextInt(mPlayListLen);
  793. }
  794. mHistory.clear();
  795. saveBookmarkIfNeeded();
  796. openCurrent();
  797. if (oldId != getAudioId()) {
  798. notifyChange(META_CHANGED);
  799. }
  800. }
  801. }
  802. /**
  803. * Moves the item at index1 to index2.
  804. * @param index1
  805. * @param index2
  806. */
  807. public void moveQueueItem(int index1, int index2) {
  808. synchronized (this) {
  809. if (index1 >= mPlayListLen) {
  810. index1 = mPlayListLen - 1;
  811. }
  812. if (index2 >= mPlayListLen) {
  813. index2 = mPlayListLen - 1;
  814. }
  815. if (index1 < index2) {
  816. long tmp = mPlayList[index1];
  817. for (int i = index1; i < index2; i++) {
  818. mPlayList[i] = mPlayList[i+1];
  819. }
  820. mPlayList[index2] = tmp;
  821. if (mPlayPos == index1) {
  822. mPlayPos = index2;
  823. } else if (mPlayPos >= index1 && mPlayPos <= index2) {
  824. mPlayPos--;
  825. }
  826. } else if (index2 < index1) {
  827. long tmp = mPlayList[index1];
  828. for (int i = index1; i > index2; i--) {
  829. mPlayList[i] = mPlayList[i-1];
  830. }
  831. mPlayList[index2] = tmp;
  832. if (mPlayPos == index1) {
  833. mPlayPos = index2;
  834. } else if (mPlayPos >= index2 && mPlayPos <= index1) {
  835. mPlayPos++;
  836. }
  837. }
  838. notifyChange(QUEUE_CHANGED);
  839. }
  840. }
  841. /**
  842. * Returns the current play list
  843. * @return An array of integers containing the IDs of the tracks in the play list
  844. */
  845. public long [] getQueue() {
  846. synchronized (this) {
  847. int len = mPlayListLen;
  848. long [] list = new long[len];
  849. for (int i = 0; i < len; i++) {
  850. list[i] = mPlayList[i];
  851. }
  852. return list;
  853. }
  854. }
  855. private void openCurrent() {
  856. synchronized (this) {
  857. if (mCursor != null) {
  858. mCursor.close();
  859. mCursor = null;
  860. }
  861. if (mPlayListLen == 0) {
  862. return;
  863. }
  864. stop(false);
  865. String id = String.valueOf(mPlayList[mPlayPos]);
  866. mCursor = getContentResolver().query(
  867. MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
  868. mCursorCols, "_id=" + id , null, null);
  869. if (mCursor != null) {
  870. mCursor.moveToFirst();
  871. open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id, false);
  872. // go to bookmark if needed
  873. if (isPodcast()) {
  874. long bookmark = getBookmark();
  875. // Start playing a little bit before the bookmark,
  876. // so it's easier to get back in to the narrative.
  877. seek(bookmark - 5000);
  878. }
  879. }
  880. }
  881. }
  882. public void openAsync(String path) {
  883. synchronized (this) {
  884. if (path == null) {
  885. return;
  886. }
  887. mRepeatMode = REPEAT_NONE;
  888. ensurePlayListCapacity(1);
  889. mPlayListLen = 1;
  890. mPlayPos = -1;
  891. mFileToPlay = path;
  892. mCursor = null;
  893. mPlayer.setDataSourceAsync(mFileToPlay);
  894. mOneShot = true;
  895. }
  896. }
  897. /**
  898. * Opens the specified file and readies it for playback.
  899. *
  900. * @param path The full path of the file to be opened.
  901. * @param oneshot when set to true, playback will stop after this file completes, instead
  902. * of moving on to the next track in the list
  903. */
  904. public void open(String path, boolean oneshot) {
  905. synchronized (this) {
  906. if (path == null) {
  907. return;
  908. }
  909. if (oneshot) {
  910. mRepeatMode = REPEAT_NONE;
  911. ensurePlayListCapacity(1);
  912. mPlayListLen = 1;
  913. mPlayPos = -1;
  914. }
  915. // if mCursor is null, try to associate path with a database cursor
  916. if (mCursor == null) {
  917. ContentResolver resolver = getContentResolver();
  918. Uri uri;
  919. String where;
  920. String selectionArgs[];
  921. if (path.startsWith("content://media/")) {
  922. uri = Uri.parse(path);
  923. where = null;
  924. selectionArgs = null;
  925. } else {
  926. uri = MediaStore.Audio.Media.getContentUriForPath(path);
  927. where = MediaStore.Audio.Media.DATA + "=?";
  928. selectionArgs = new String[] { path };
  929. }
  930. try {
  931. mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
  932. if (mCursor != null) {
  933. if (mCursor.getCount() == 0) {
  934. mCursor.close();
  935. mCursor = null;
  936. } else {
  937. mCursor.moveToNext();
  938. ensurePlayListCapacity(1);
  939. mPlayListLen = 1;
  940. mPlayList[0] = mCursor.getLong(IDCOLIDX);
  941. mPlayPos = 0;
  942. }
  943. }
  944. } catch (UnsupportedOperationException ex) {
  945. }
  946. }
  947. mFileToPlay = path;
  948. mPlayer.setDataSource(mFileToPlay);
  949. mOneShot = oneshot;
  950. if (! mPlayer.isInitialized()) {
  951. stop(true);
  952. if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
  953. // beware: this ends up being recursive because next() calls open() again.
  954. next(false);
  955. }
  956. if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) {
  957. // need to make sure we only shows this once
  958. mOpenFailedCounter = 0;
  959. if (!mQuietMode) {
  960. Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
  961. }
  962. Log.d(LOGTAG, "Failed to open file for playback");
  963. }
  964. } else {
  965. mOpenFailedCounter = 0;
  966. }
  967. }
  968. }
  969. /**
  970. * Starts playback of a previously opened file.
  971. */
  972. public void play() {
  973. mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
  974. AudioManager.AUDIOFOCUS_GAIN);
  975. mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this.getPackageName(),
  976. MediaButtonIntentReceiver.class.getName()));
  977. if (mPlayer.isInitialized()) {
  978. // if we are at the end of the song, go to the next song first
  979. long duration = mPlayer.duration();
  980. if (mRepeatMode != REPEAT_CURRENT && duration > 2000 &&
  981. mPlayer.position() >= duration - 2000) {
  982. next(true);
  983. }
  984. mPlayer.start();
  985. RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
  986. views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
  987. if (getAudioId() < 0) {
  988. // streaming
  989. views.setTextViewText(R.id.trackname, getPath());
  990. views.setTextViewText(R.id.artistalbum, null);
  991. } else {
  992. String artist = getArtistName();
  993. views.setTextViewText(R.id.trackname, getTrackName());
  994. if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) {
  995. artist = getString(R.string.unknown_artist_name);
  996. }
  997. String album = getAlbumName();
  998. if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) {
  999. album = getString(R.string.unknown_album_name);
  1000. }
  1001. views.setTextViewText(R.id.artistalbum,
  1002. getString(R.string.notification_artist_album, artist, album)
  1003. );
  1004. }
  1005. Notification status = new Notification();
  1006. status.contentView = views;
  1007. status.flags |= Notification.FLAG_ONGOING_EVENT;
  1008. status.icon = R.drawable.stat_notify_musicplayer;
  1009. status.contentIntent = PendingIntent.getActivity(this, 0,
  1010. new Intent("com.android.music.PLAYBACK_VIEWER")
  1011. .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
  1012. startForeground(PLAYBACKSERVICE_STATUS, status);
  1013. if (!mIsSupposedToBePlaying) {
  1014. mIsSupposedToBePlaying = true;
  1015. notifyChange(PLAYSTATE_CHANGED);
  1016. }
  1017. } else if (mPlayListLen <= 0) {
  1018. // This is mostly so that if you press 'play' on a bluetooth headset
  1019. // without every having played anything before, it will still play
  1020. // something.
  1021. setShuffleMode(SHUFFLE_AUTO);
  1022. }
  1023. }
  1024. private void stop(boolean remove_status_icon) {
  1025. if (mPlayer.isInitialized()) {
  1026. mPlayer.stop();
  1027. }
  1028. mFileToPlay = null;
  1029. if (mCursor != null) {
  1030. mCursor.close();
  1031. mCursor = null;
  1032. }
  1033. if (remove_status_icon) {
  1034. gotoIdleState();
  1035. } else {
  1036. stopForeground(false);
  1037. }
  1038. if (remove_status_icon) {
  1039. mIsSupposedToBePlaying = false;
  1040. }
  1041. }
  1042. /**
  1043. * Stops playback.
  1044. */
  1045. public void stop() {
  1046. stop(true);
  1047. }
  1048. /**
  1049. * Pauses playback (call play() to resume)
  1050. */
  1051. public void pause() {
  1052. synchronized(this) {
  1053. if (isPlaying()) {
  1054. mPlayer.pause();
  1055. gotoIdleState();
  1056. mIsSupposedToBePlaying = false;
  1057. notifyChange(PLAYSTATE_CHANGED);
  1058. saveBookmarkIfNeeded();
  1059. }
  1060. }
  1061. }
  1062. /** Returns whether something is currently playing
  1063. *
  1064. * @return true if something is playing (or will be playing shortly, in case
  1065. * we're currently transitioning between tracks), false if not.
  1066. */
  1067. public boolean isPlaying() {
  1068. return mIsSupposedToBePlaying;
  1069. }
  1070. /*
  1071. Desired behavior for prev/next/shuffle:
  1072. - NEXT will move to the next track in the list when not shuffling, and to
  1073. a track randomly picked from the not-yet-played tracks when shuffling.
  1074. If all tracks have already been played, pick from the full set, but
  1075. avoid picking the previously played track if possible.
  1076. - when shuffling, PREV will go to the previously played track. Hitting PREV
  1077. again will go to the track played before that, etc. When the start of the
  1078. history has been reached, PREV is a no-op.
  1079. When not shuffling, PREV will go to the sequentially previous track (the
  1080. difference with the shuffle-case is mainly that when not shuffling, the
  1081. user can back up to tracks that are not in the history).
  1082. Example:
  1083. When playing an album with 10 tracks from the start, and enabling shuffle
  1084. while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
  1085. the final play order might be 1-2-3-4-5-8-10-6-9-7.
  1086. When hitting 'prev' 8 times while playing track 7 in this example, the
  1087. user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
  1088. a random track will be picked again. If at any time user disables shuffling
  1089. the next/previous track will be picked in sequential order again.
  1090. */
  1091. public void prev() {
  1092. synchronized (this) {
  1093. if (mOneShot) {
  1094. // we were playing a specific file not part of a playlist, so there is no 'previous'
  1095. seek(0);
  1096. play();
  1097. return;
  1098. }
  1099. if (mShuffleMode == SHUFFLE_NORMAL) {
  1100. // go to previously-played track and remove it from the history
  1101. int histsize = mHistory.size();
  1102. if (histsize == 0) {
  1103. // prev is a no-op
  1104. return;
  1105. }
  1106. Integer pos = mHistory.remove(histsize - 1);
  1107. mPlayPos = pos.intValue();
  1108. } else {
  1109. if (mPlayPos > 0) {
  1110. mPlayPos--;
  1111. } else {
  1112. mPlayPos = mPlayListLen - 1;
  1113. }
  1114. }
  1115. saveBookmarkIfNeeded();
  1116. stop(false);
  1117. openCurrent();
  1118. play();
  1119. notifyChange(META_CHANGED);
  1120. }
  1121. }
  1122. public void next(boolean force) {
  1123. synchronized (this) {
  1124. if (mOneShot) {
  1125. // we were playing a specific file not part of a playlist, so there is no 'next'
  1126. seek(0);
  1127. play();
  1128. return;
  1129. }
  1130. if (mPlayListLen <= 0) {
  1131. Log.d(LOGTAG, "No play queue");
  1132. return;
  1133. }
  1134. // Store the current file in the history, but keep the history at a
  1135. // reasonable size
  1136. if (mPlayPos >= 0) {
  1137. mHistory.add(Integer.valueOf(mPlayPos));
  1138. }
  1139. if (mHistory.size() > MAX_HISTORY_SIZE) {
  1140. mHistory.removeElementAt(0);
  1141. }
  1142. if (mShuffleMode == SHUFFLE_NORMAL) {
  1143. // Pick random next track from the not-yet-played ones
  1144. // TODO: make it work right after adding/removing items in the queue.
  1145. int numTracks = mPlayListLen;
  1146. int[] tracks = new int[numTracks];
  1147. for (int i=0;i < numTracks; i++) {
  1148. tracks[i] = i;
  1149. }
  1150. int numHistory = mHistory.size();
  1151. int numUnplayed = numTracks;
  1152. for (int i=0;i < numHistory; i++) {
  1153. int idx = mHistory.get(i).intValue();
  1154. if (idx < numTracks && tracks[idx] >= 0) {
  1155. numUnplayed--;
  1156. tracks[idx] = -1;
  1157. }
  1158. }
  1159. // 'numUnplayed' now indicates how many tracks have not yet
  1160. // been played, and 'tracks' contains the indices of those
  1161. // tracks.
  1162. if (numUnplayed <=0) {
  1163. // everything's already been played
  1164. if (mRepeatMode == REPEAT_ALL || force) {
  1165. //pick from full set
  1166. numUnplayed = numTracks;
  1167. for (int i=0;i < numTracks; i++) {
  1168. tracks[i] = i;
  1169. }
  1170. } else {
  1171. // all done
  1172. gotoIdleState();
  1173. if (mIsSupposedToBePlaying) {
  1174. mIsSupposedToBePlaying = false;
  1175. notifyChange(PLAYSTATE_CHANGED);
  1176. }
  1177. return;