PageRenderTime 158ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://github.com/Redux/android_packages_apps_Music
Java | 1975 lines | 1504 code | 158 blank | 313 comment | 355 complexity | 0948063859b91084b4a9f143743e6299 MD5 | raw file

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

Large files files are truncated, but you can click here to view the full file