MediaService.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * Copyright (C) 2016 ownCloud Inc.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2,
  9. * as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.owncloud.android.media;
  20. import android.accounts.Account;
  21. import android.app.NotificationManager;
  22. import android.app.PendingIntent;
  23. import android.app.Service;
  24. import android.content.Context;
  25. import android.content.Intent;
  26. import android.media.AudioManager;
  27. import android.media.MediaPlayer;
  28. import android.media.MediaPlayer.OnCompletionListener;
  29. import android.media.MediaPlayer.OnErrorListener;
  30. import android.media.MediaPlayer.OnPreparedListener;
  31. import android.net.wifi.WifiManager;
  32. import android.net.wifi.WifiManager.WifiLock;
  33. import android.os.IBinder;
  34. import android.os.PowerManager;
  35. import android.support.v4.app.NotificationCompat;
  36. import android.widget.Toast;
  37. import com.owncloud.android.R;
  38. import com.owncloud.android.datamodel.OCFile;
  39. import com.owncloud.android.lib.common.utils.Log_OC;
  40. import com.owncloud.android.ui.activity.FileActivity;
  41. import com.owncloud.android.ui.activity.FileDisplayActivity;
  42. import com.owncloud.android.ui.notifications.NotificationUtils;
  43. import com.owncloud.android.utils.ThemeUtils;
  44. import java.io.IOException;
  45. /**
  46. * Service that handles media playback, both audio and video.
  47. *
  48. * Waits for Intents which signal the service to perform specific operations: Play, Pause,
  49. * Rewind, etc.
  50. */
  51. public class MediaService extends Service implements OnCompletionListener, OnPreparedListener,
  52. OnErrorListener, AudioManager.OnAudioFocusChangeListener {
  53. private static final String TAG = MediaService.class.getSimpleName();
  54. private static final String MY_PACKAGE = MediaService.class.getPackage() != null ?
  55. MediaService.class.getPackage().getName() : "com.owncloud.android.media";
  56. /// Intent actions that we are prepared to handle
  57. public static final String ACTION_PLAY_FILE = MY_PACKAGE + ".action.PLAY_FILE";
  58. public static final String ACTION_STOP_ALL = MY_PACKAGE + ".action.STOP_ALL";
  59. /// PreferenceKeys to add extras to the action
  60. public static final String EXTRA_FILE = MY_PACKAGE + ".extra.FILE";
  61. public static final String EXTRA_ACCOUNT = MY_PACKAGE + ".extra.ACCOUNT";
  62. public static final String EXTRA_START_POSITION = MY_PACKAGE + ".extra.START_POSITION";
  63. public static final String EXTRA_PLAY_ON_LOAD = MY_PACKAGE + ".extra.PLAY_ON_LOAD";
  64. /** Error code for specific messages - see regular error codes at {@link MediaPlayer} */
  65. public static final int OC_MEDIA_ERROR = 0;
  66. /** Time To keep the control panel visible when the user does not use it */
  67. public static final int MEDIA_CONTROL_SHORT_LIFE = 4000;
  68. /** Time To keep the control panel visible when the user does not use it */
  69. public static final int MEDIA_CONTROL_PERMANENT = 0;
  70. /** Volume to set when audio focus is lost and ducking is allowed */
  71. private static final float DUCK_VOLUME = 0.1f;
  72. /** Media player instance */
  73. private MediaPlayer mPlayer = null;
  74. /** Reference to the system AudioManager */
  75. private AudioManager mAudioManager = null;
  76. /** Values to indicate the state of the service */
  77. enum State {
  78. STOPPED,
  79. PREPARING,
  80. PLAYING,
  81. PAUSED
  82. }
  83. /** Current state */
  84. private State mState = State.STOPPED;
  85. /** Possible focus values */
  86. enum AudioFocus {
  87. NO_FOCUS,
  88. NO_FOCUS_CAN_DUCK,
  89. FOCUS
  90. }
  91. /** Current focus state */
  92. private AudioFocus mAudioFocus = AudioFocus.NO_FOCUS;
  93. /** Wifi lock kept to prevents the device from shutting off the radio when streaming a file. */
  94. private WifiLock mWifiLock;
  95. private static final String MEDIA_WIFI_LOCK_TAG = MY_PACKAGE + ".WIFI_LOCK";
  96. /** Notification to keep in the notification bar while a song is playing */
  97. private NotificationManager mNotificationManager;
  98. /** File being played */
  99. private OCFile mFile;
  100. /** Account holding the file being played */
  101. private Account mAccount;
  102. /** Flag signaling if the audio should be played immediately when the file is prepared */
  103. protected boolean mPlayOnPrepared;
  104. /** Position, in milliseconds, where the audio should be started */
  105. private int mStartPosition;
  106. /** Interface to access the service through binding */
  107. private IBinder mBinder;
  108. /** Control panel shown to the user to control the playback, to register through binding */
  109. private MediaControlView mMediaController;
  110. /** Notification builder to create notifications, new reuse way since Android 6 */
  111. private NotificationCompat.Builder mNotificationBuilder;
  112. /**
  113. * Helper method to get an error message suitable to show to users for errors occurred in media playback,
  114. *
  115. * @param context A context to access string resources.
  116. * @param what See {@link MediaPlayer.OnErrorListener#onError(MediaPlayer, int, int)
  117. * @param extra See {@link MediaPlayer.OnErrorListener#onError(MediaPlayer, int, int)
  118. * @return Message suitable to users.
  119. */
  120. public static String getMessageForMediaError(Context context, int what, int extra) {
  121. int messageId;
  122. if (what == OC_MEDIA_ERROR) {
  123. messageId = extra;
  124. } else if (extra == MediaPlayer.MEDIA_ERROR_UNSUPPORTED) {
  125. /* Added in API level 17
  126. Bitstream is conforming to the related coding standard or file spec,
  127. but the media framework does not support the feature.
  128. Constant Value: -1010 (0xfffffc0e)
  129. */
  130. messageId = R.string.media_err_unsupported;
  131. } else if (extra == MediaPlayer.MEDIA_ERROR_IO) {
  132. /* Added in API level 17
  133. File or network related operation errors.
  134. Constant Value: -1004 (0xfffffc14)
  135. */
  136. messageId = R.string.media_err_io;
  137. } else if (extra == MediaPlayer.MEDIA_ERROR_MALFORMED) {
  138. /* Added in API level 17
  139. Bitstream is not conforming to the related coding standard or file spec.
  140. Constant Value: -1007 (0xfffffc11)
  141. */
  142. messageId = R.string.media_err_malformed;
  143. } else if (extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT) {
  144. /* Added in API level 17
  145. Some operation takes too long to complete, usually more than 3-5 seconds.
  146. Constant Value: -110 (0xffffff92)
  147. */
  148. messageId = R.string.media_err_timeout;
  149. } else if (what == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
  150. /* Added in API level 3
  151. The video is streamed and its container is not valid for progressive playback i.e the video's index
  152. (e.g moov atom) is not at the start of the file.
  153. Constant Value: 200 (0x000000c8)
  154. */
  155. messageId = R.string.media_err_invalid_progressive_playback;
  156. } else {
  157. /* MediaPlayer.MEDIA_ERROR_UNKNOWN
  158. Added in API level 1
  159. Unspecified media player error.
  160. Constant Value: 1 (0x00000001)
  161. */
  162. /* MediaPlayer.MEDIA_ERROR_SERVER_DIED)
  163. Added in API level 1
  164. Media server died. In this case, the application must release the MediaPlayer
  165. object and instantiate a new one.
  166. Constant Value: 100 (0x00000064)
  167. */
  168. messageId = R.string.media_err_unknown;
  169. }
  170. return context.getString(messageId);
  171. }
  172. /**
  173. * Initialize a service instance
  174. *
  175. * {@inheritDoc}
  176. */
  177. @Override
  178. public void onCreate() {
  179. super.onCreate();
  180. Log_OC.d(TAG, "Creating ownCloud media service");
  181. mWifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE)).
  182. createWifiLock(WifiManager.WIFI_MODE_FULL, MEDIA_WIFI_LOCK_TAG);
  183. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  184. mNotificationBuilder = new NotificationCompat.Builder(this);
  185. mNotificationBuilder.setColor(ThemeUtils.primaryColor(this));
  186. mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
  187. mBinder = new MediaServiceBinder(this);
  188. }
  189. /**
  190. * Entry point for Intents requesting actions, sent here via startService.
  191. *
  192. * {@inheritDoc}
  193. */
  194. @Override
  195. public int onStartCommand(Intent intent, int flags, int startId) {
  196. String action = intent.getAction();
  197. if (action.equals(ACTION_PLAY_FILE)) {
  198. processPlayFileRequest(intent);
  199. } else if (action.equals(ACTION_STOP_ALL)) {
  200. processStopRequest(true);
  201. }
  202. return START_NOT_STICKY; // don't want it to restart in case it's killed.
  203. }
  204. /**
  205. * Processes a request to play a media file received as a parameter
  206. *
  207. * TODO If a new request is received when a file is being prepared, it is ignored. Is this what we want?
  208. *
  209. * @param intent Intent received in the request with the data to identify the file to play.
  210. */
  211. private void processPlayFileRequest(Intent intent) {
  212. if (mState != State.PREPARING) {
  213. mFile = intent.getExtras().getParcelable(EXTRA_FILE);
  214. mAccount = intent.getExtras().getParcelable(EXTRA_ACCOUNT);
  215. mPlayOnPrepared = intent.getExtras().getBoolean(EXTRA_PLAY_ON_LOAD, false);
  216. mStartPosition = intent.getExtras().getInt(EXTRA_START_POSITION, 0);
  217. tryToGetAudioFocus();
  218. playMedia();
  219. }
  220. }
  221. /**
  222. * Processes a request to play a media file.
  223. */
  224. protected void processPlayRequest() {
  225. // request audio focus
  226. tryToGetAudioFocus();
  227. // actually play the song
  228. if (mState == State.STOPPED) {
  229. // (re)start playback
  230. playMedia();
  231. } else if (mState == State.PAUSED) {
  232. // continue playback
  233. mState = State.PLAYING;
  234. setUpAsForeground(String.format(getString(R.string.media_state_playing), mFile.getFileName()));
  235. configAndStartMediaPlayer();
  236. }
  237. }
  238. /**
  239. * Makes sure the media player exists and has been reset. This will create the media player
  240. * if needed. reset the existing media player if one already exists.
  241. */
  242. protected void createMediaPlayerIfNeeded() {
  243. if (mPlayer == null) {
  244. mPlayer = new MediaPlayer();
  245. // make sure the CPU won't go to sleep while media is playing
  246. mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
  247. // the media player will notify the service when it's ready preparing, and when it's done playing
  248. mPlayer.setOnPreparedListener(this);
  249. mPlayer.setOnCompletionListener(this);
  250. mPlayer.setOnErrorListener(this);
  251. } else {
  252. mPlayer.reset();
  253. }
  254. }
  255. /**
  256. * Processes a request to pause the current playback
  257. */
  258. protected void processPauseRequest() {
  259. if (mState == State.PLAYING) {
  260. mState = State.PAUSED;
  261. mPlayer.pause();
  262. releaseResources(false); // retain media player in pause
  263. // TODO polite audio focus, instead of keep it owned; or not?
  264. }
  265. }
  266. /**
  267. * Processes a request to stop the playback.
  268. *
  269. * @param force When 'true', the playback is stopped no matter the value of mState
  270. */
  271. protected void processStopRequest(boolean force) {
  272. if (mState != State.PREPARING || force) {
  273. mState = State.STOPPED;
  274. mFile = null;
  275. mAccount = null;
  276. releaseResources(true);
  277. giveUpAudioFocus();
  278. stopSelf(); // service is no longer necessary
  279. }
  280. }
  281. /**
  282. * Releases resources used by the service for playback. This includes the "foreground service"
  283. * status and notification, the wake locks and possibly the MediaPlayer.
  284. *
  285. * @param releaseMediaPlayer Indicates whether the Media Player should also be released or not
  286. */
  287. protected void releaseResources(boolean releaseMediaPlayer) {
  288. // stop being a foreground service
  289. stopForeground(true);
  290. // stop and release the Media Player, if it's available
  291. if (releaseMediaPlayer && mPlayer != null) {
  292. mPlayer.reset();
  293. mPlayer.release();
  294. mPlayer = null;
  295. }
  296. // release the Wifi lock, if holding it
  297. if (mWifiLock.isHeld()) {
  298. mWifiLock.release();
  299. }
  300. }
  301. /**
  302. * Fully releases the audio focus.
  303. */
  304. private void giveUpAudioFocus() {
  305. if (mAudioFocus == AudioFocus.FOCUS
  306. && mAudioManager != null
  307. && AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.abandonAudioFocus(this)) {
  308. mAudioFocus = AudioFocus.NO_FOCUS;
  309. }
  310. }
  311. /**
  312. * Reconfigures MediaPlayer according to audio focus settings and starts/restarts it.
  313. */
  314. protected void configAndStartMediaPlayer() {
  315. if (mPlayer == null) {
  316. throw new IllegalStateException("mPlayer is NULL");
  317. }
  318. if (mAudioFocus == AudioFocus.NO_FOCUS) {
  319. if (mPlayer.isPlaying()) {
  320. mPlayer.pause(); // have to be polite; but mState is not changed, to resume when focus is received again
  321. }
  322. } else {
  323. if (mAudioFocus == AudioFocus.NO_FOCUS_CAN_DUCK) {
  324. mPlayer.setVolume(DUCK_VOLUME, DUCK_VOLUME);
  325. } else {
  326. mPlayer.setVolume(1.0f, 1.0f); // full volume
  327. }
  328. if (!mPlayer.isPlaying()) {
  329. mPlayer.start();
  330. }
  331. }
  332. }
  333. /**
  334. * Requests the audio focus to the Audio Manager
  335. */
  336. private void tryToGetAudioFocus() {
  337. if (mAudioFocus != AudioFocus.FOCUS
  338. && mAudioManager != null
  339. && (AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.requestAudioFocus(this,
  340. AudioManager.STREAM_MUSIC,
  341. AudioManager.AUDIOFOCUS_GAIN))
  342. ) {
  343. mAudioFocus = AudioFocus.FOCUS;
  344. }
  345. }
  346. /**
  347. * Starts playing the current media file.
  348. */
  349. protected void playMedia() {
  350. mState = State.STOPPED;
  351. releaseResources(false); // release everything except MediaPlayer
  352. try {
  353. if (mFile == null) {
  354. Toast.makeText(this, R.string.media_err_nothing_to_play, Toast.LENGTH_LONG).show();
  355. processStopRequest(true);
  356. return;
  357. } else if (mAccount == null) {
  358. Toast.makeText(this, R.string.media_err_not_in_owncloud, Toast.LENGTH_LONG).show();
  359. processStopRequest(true);
  360. return;
  361. }
  362. createMediaPlayerIfNeeded();
  363. mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  364. String url = mFile.getStoragePath();
  365. /* Streaming is not possible right now
  366. if (url == null || url.length() <= 0) {
  367. url = AccountUtils.constructFullURLForAccount(this, mAccount) + mFile.getRemotePath();
  368. }
  369. mIsStreaming = url.startsWith("http:") || url.startsWith("https:");
  370. */
  371. //mIsStreaming = false;
  372. mPlayer.setDataSource(url);
  373. mState = State.PREPARING;
  374. setUpAsForeground(String.format(getString(R.string.media_state_loading), mFile.getFileName()));
  375. // starts preparing the media player in background
  376. mPlayer.prepareAsync();
  377. // prevent the Wifi from going to sleep when streaming
  378. /*
  379. if (mIsStreaming) {
  380. mWifiLock.acquire();
  381. } else
  382. */
  383. if (mWifiLock.isHeld()) {
  384. mWifiLock.release();
  385. }
  386. } catch (SecurityException | IOException | IllegalStateException | IllegalArgumentException e) {
  387. Log_OC.e(TAG, e.getClass().getSimpleName() + " playing " + mAccount.name + mFile.getRemotePath(), e);
  388. Toast.makeText(this, String.format(getString(R.string.media_err_security_ex), mFile.getFileName()),
  389. Toast.LENGTH_LONG).show();
  390. processStopRequest(true);
  391. }
  392. }
  393. /** Called when media player is done playing current song. */
  394. public void onCompletion(MediaPlayer player) {
  395. Toast.makeText(this, String.format(getString(R.string.media_event_done), mFile.getFileName()), Toast.LENGTH_LONG).show();
  396. if (mMediaController != null) {
  397. // somebody is still bound to the service
  398. player.seekTo(0);
  399. processPauseRequest();
  400. mMediaController.updatePausePlay();
  401. } else {
  402. // nobody is bound
  403. processStopRequest(true);
  404. }
  405. }
  406. /**
  407. * Called when media player is done preparing.
  408. *
  409. * Time to start.
  410. */
  411. public void onPrepared(MediaPlayer player) {
  412. mState = State.PLAYING;
  413. updateNotification(String.format(getString(R.string.media_state_playing), mFile.getFileName()));
  414. if (mMediaController != null) {
  415. mMediaController.setEnabled(true);
  416. }
  417. player.seekTo(mStartPosition);
  418. configAndStartMediaPlayer();
  419. if (!mPlayOnPrepared) {
  420. processPauseRequest();
  421. }
  422. if (mMediaController != null) {
  423. mMediaController.updatePausePlay();
  424. }
  425. }
  426. /**
  427. * Updates the status notification
  428. */
  429. private void updateNotification(String content) {
  430. String ticker = String.format(getString(R.string.media_notif_ticker), getString(R.string.app_name));
  431. // TODO check if updating the Intent is really necessary
  432. Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
  433. showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, mFile);
  434. showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, mAccount);
  435. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  436. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),
  437. (int) System.currentTimeMillis(),
  438. showDetailsIntent,
  439. PendingIntent.FLAG_UPDATE_CURRENT));
  440. mNotificationBuilder.setWhen(System.currentTimeMillis());
  441. mNotificationBuilder.setTicker(ticker);
  442. mNotificationBuilder.setContentTitle(ticker);
  443. mNotificationBuilder.setContentText(content);
  444. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
  445. mNotificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_MEDIA);
  446. }
  447. mNotificationManager.notify(R.string.media_notif_ticker, mNotificationBuilder.build());
  448. }
  449. /**
  450. * Configures the service as a foreground service.
  451. *
  452. * The system will avoid finishing the service as much as possible when resources as low.
  453. *
  454. * A notification must be created to keep the user aware of the existence of the service.
  455. */
  456. private void setUpAsForeground(String content) {
  457. String ticker = String.format(getString(R.string.media_notif_ticker), getString(R.string.app_name));
  458. /// creates status notification
  459. // TODO put a progress bar to follow the playback progress
  460. mNotificationBuilder.setSmallIcon(R.drawable.ic_play_arrow);
  461. //mNotification.tickerText = text;
  462. mNotificationBuilder.setWhen(System.currentTimeMillis());
  463. mNotificationBuilder.setOngoing(true);
  464. /// includes a pending intent in the notification showing the details view of the file
  465. Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
  466. showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, mFile);
  467. showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, mAccount);
  468. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  469. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),
  470. (int) System.currentTimeMillis(),
  471. showDetailsIntent,
  472. PendingIntent.FLAG_UPDATE_CURRENT));
  473. mNotificationBuilder.setContentTitle(ticker);
  474. mNotificationBuilder.setContentText(content);
  475. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
  476. mNotificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_MEDIA);
  477. }
  478. startForeground(R.string.media_notif_ticker, mNotificationBuilder.build());
  479. }
  480. /**
  481. * Called when there's an error playing media.
  482. *
  483. * Warns the user about the error and resets the media player.
  484. */
  485. public boolean onError(MediaPlayer mp, int what, int extra) {
  486. Log_OC.e(TAG, "Error in audio playback, what = " + what + ", extra = " + extra);
  487. String message = getMessageForMediaError(this, what, extra);
  488. Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
  489. processStopRequest(true);
  490. return true;
  491. }
  492. /**
  493. * Called by the system when another app tries to play some sound.
  494. *
  495. * {@inheritDoc}
  496. */
  497. @Override
  498. public void onAudioFocusChange(int focusChange) {
  499. if (focusChange > 0) {
  500. // focus gain; check AudioManager.AUDIOFOCUS_* values
  501. mAudioFocus = AudioFocus.FOCUS;
  502. // restart media player with new focus settings
  503. if (mState == State.PLAYING) {
  504. configAndStartMediaPlayer();
  505. }
  506. } else if (focusChange < 0) {
  507. // focus loss; check AudioManager.AUDIOFOCUS_* values
  508. boolean canDuck = AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK == focusChange;
  509. mAudioFocus = canDuck ? AudioFocus.NO_FOCUS_CAN_DUCK : AudioFocus.NO_FOCUS;
  510. // start/restart/pause media player with new focus settings
  511. if (mPlayer != null && mPlayer.isPlaying()) {
  512. configAndStartMediaPlayer();
  513. }
  514. }
  515. }
  516. /**
  517. * Called when the service is finished for final clean-up.
  518. *
  519. * {@inheritDoc}
  520. */
  521. @Override
  522. public void onDestroy() {
  523. mState = State.STOPPED;
  524. releaseResources(true);
  525. giveUpAudioFocus();
  526. stopForeground(true);
  527. super.onDestroy();
  528. }
  529. /**
  530. * Provides a binder object that clients can use to perform operations on the MediaPlayer managed by the MediaService.
  531. */
  532. @Override
  533. public IBinder onBind(Intent arg) {
  534. return mBinder;
  535. }
  536. /**
  537. * Called when ALL the bound clients were onbound.
  538. *
  539. * The service is destroyed if playback stopped or paused
  540. */
  541. @Override
  542. public boolean onUnbind(Intent intent) {
  543. if (mState == State.PAUSED || mState == State.STOPPED) {
  544. processStopRequest(false);
  545. }
  546. return false; // not accepting rebinding (default behaviour)
  547. }
  548. /**
  549. * Accesses the current MediaPlayer instance in the service.
  550. *
  551. * To be handled carefully. Visibility is protected to be accessed only
  552. *
  553. * @return Current MediaPlayer instance handled by MediaService.
  554. */
  555. protected MediaPlayer getPlayer() {
  556. return mPlayer;
  557. }
  558. /**
  559. * Accesses the current OCFile loaded in the service.
  560. *
  561. * @return The current OCFile loaded in the service.
  562. */
  563. protected OCFile getCurrentFile() {
  564. return mFile;
  565. }
  566. /**
  567. * Accesses the current {@link State} of the MediaService.
  568. *
  569. * @return The current {@link State} of the MediaService.
  570. */
  571. protected State getState() {
  572. return mState;
  573. }
  574. protected void setMediaContoller(MediaControlView mediaController) {
  575. mMediaController = mediaController;
  576. }
  577. protected MediaControlView getMediaController() {
  578. return mMediaController;
  579. }
  580. }