2 * ownCloud Android client application
4 * @author David A. Velasco
5 * Copyright (C) 2015 ownCloud Inc.
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.
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.
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/>.
20 package com
.owncloud
.android
.ui
.preview
;
22 import android
.accounts
.Account
;
23 import android
.app
.Activity
;
24 import android
.graphics
.Bitmap
;
25 import android
.graphics
.BitmapFactory
;
26 import android
.media
.MediaMetadataRetriever
;
27 import android
.support
.v7
.app
.AlertDialog
;
28 import android
.content
.ComponentName
;
29 import android
.content
.Context
;
30 import android
.content
.DialogInterface
;
31 import android
.content
.Intent
;
32 import android
.content
.ServiceConnection
;
33 import android
.content
.res
.Configuration
;
34 import android
.content
.res
.Resources
;
35 import android
.media
.MediaPlayer
;
36 import android
.media
.MediaPlayer
.OnCompletionListener
;
37 import android
.media
.MediaPlayer
.OnErrorListener
;
38 import android
.media
.MediaPlayer
.OnPreparedListener
;
39 import android
.net
.Uri
;
40 import android
.os
.Build
;
41 import android
.os
.Bundle
;
42 import android
.os
.IBinder
;
43 import android
.view
.LayoutInflater
;
44 import android
.view
.Menu
;
45 import android
.view
.MenuInflater
;
46 import android
.view
.MenuItem
;
47 import android
.view
.MotionEvent
;
48 import android
.view
.View
;
49 import android
.view
.View
.OnTouchListener
;
50 import android
.view
.ViewGroup
;
51 import android
.widget
.ImageView
;
52 import android
.widget
.LinearLayout
;
53 import android
.widget
.Toast
;
54 import android
.widget
.VideoView
;
56 import com
.owncloud
.android
.R
;
57 import com
.owncloud
.android
.datamodel
.OCFile
;
58 import com
.owncloud
.android
.files
.FileMenuFilter
;
59 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
60 import com
.owncloud
.android
.media
.MediaControlView
;
61 import com
.owncloud
.android
.media
.MediaService
;
62 import com
.owncloud
.android
.media
.MediaServiceBinder
;
63 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
64 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
65 import com
.owncloud
.android
.ui
.dialog
.RemoveFileDialogFragment
;
66 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
70 * This fragment shows a preview of a downloaded media file (audio or video).
72 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will
73 * produce an {@link IllegalStateException}.
75 * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is
76 * generated on instantiation too.
78 public class PreviewMediaFragment
extends FileFragment
implements
81 public static final String EXTRA_FILE
= "FILE";
82 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
83 private static final String EXTRA_PLAY_POSITION
= "PLAY_POSITION";
84 private static final String EXTRA_PLAYING
= "PLAYING";
87 private Account mAccount
;
88 private ImageView mImagePreview
;
89 private VideoView mVideoPreview
;
90 private int mSavedPlaybackPosition
;
92 private MediaServiceBinder mMediaServiceBinder
= null
;
93 private MediaControlView mMediaController
= null
;
94 private MediaServiceConnection mMediaServiceConnection
= null
;
95 private VideoHelper mVideoHelper
;
96 private boolean mAutoplay
;
97 public boolean mPrepared
;
99 private static final String TAG
= PreviewMediaFragment
.class.getSimpleName();
103 * Creates a fragment to preview a file.
105 * When 'fileToDetail' or 'ocAccount' are null
107 * @param fileToDetail An {@link OCFile} to preview in the fragment
108 * @param ocAccount An ownCloud account; needed to start downloads
110 public PreviewMediaFragment(
113 int startPlaybackPosition
,
117 mAccount
= ocAccount
;
118 mSavedPlaybackPosition
= startPlaybackPosition
;
119 mAutoplay
= autoplay
;
124 * Creates an empty fragment for previews.
126 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically
127 * (for instance, when the device is turned a aside).
129 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful
132 public PreviewMediaFragment() {
135 mSavedPlaybackPosition
= 0;
144 public void onCreate(Bundle savedInstanceState
) {
145 super.onCreate(savedInstanceState
);
146 setHasOptionsMenu(true
);
154 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
155 Bundle savedInstanceState
) {
156 super.onCreateView(inflater
, container
, savedInstanceState
);
157 Log_OC
.e(TAG
, "onCreateView");
160 mView
= inflater
.inflate(R
.layout
.file_preview
, container
, false
);
162 mImagePreview
= (ImageView
)mView
.findViewById(R
.id
.image_preview
);
163 mVideoPreview
= (VideoView
)mView
.findViewById(R
.id
.video_preview
);
164 mVideoPreview
.setOnTouchListener(this);
166 mMediaController
= (MediaControlView
)mView
.findViewById(R
.id
.media_controller
);
176 public void onActivityCreated(Bundle savedInstanceState
) {
177 super.onActivityCreated(savedInstanceState
);
178 Log_OC
.e(TAG
, "onActivityCreated");
180 OCFile file
= getFile();
181 if (savedInstanceState
== null
) {
183 throw new IllegalStateException("Instanced with a NULL OCFile");
185 if (mAccount
== null
) {
186 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
188 if (!file
.isDown()) {
189 throw new IllegalStateException("There is no local file to preview");
193 file
= (OCFile
)savedInstanceState
.getParcelable(PreviewMediaFragment
.EXTRA_FILE
);
195 mAccount
= savedInstanceState
.getParcelable(PreviewMediaFragment
.EXTRA_ACCOUNT
);
196 mSavedPlaybackPosition
=
197 savedInstanceState
.getInt(PreviewMediaFragment
.EXTRA_PLAY_POSITION
);
198 mAutoplay
= savedInstanceState
.getBoolean(PreviewMediaFragment
.EXTRA_PLAYING
);
201 if (file
!= null
&& file
.isDown()) {
202 if (file
.isVideo()) {
203 mVideoPreview
.setVisibility(View
.VISIBLE
);
204 mImagePreview
.setVisibility(View
.GONE
);
208 mVideoPreview
.setVisibility(View
.GONE
);
209 mImagePreview
.setVisibility(View
.VISIBLE
);
210 extractAndSetCoverArt(file
);
217 * tries to read the cover art from the audio file and sets it as cover art.
219 * @param file audio file with potential cover art
221 private void extractAndSetCoverArt(OCFile file
) {
222 if (file
.isAudio()) {
224 MediaMetadataRetriever mmr
= new MediaMetadataRetriever();
225 mmr
.setDataSource(file
.getStoragePath());
226 byte[] data
= mmr
.getEmbeddedPicture();
228 Bitmap bitmap
= BitmapFactory
.decodeByteArray(data
, 0, data
.length
);
229 mImagePreview
.setImageBitmap(bitmap
); //associated cover art in bitmap
231 mImagePreview
.setImageResource(R
.drawable
.logo
);
233 } catch (Throwable t
) {
234 mImagePreview
.setImageResource(R
.drawable
.logo
);
244 public void onSaveInstanceState(Bundle outState
) {
245 super.onSaveInstanceState(outState
);
246 Log_OC
.e(TAG
, "onSaveInstanceState");
248 outState
.putParcelable(PreviewMediaFragment
.EXTRA_FILE
, getFile());
249 outState
.putParcelable(PreviewMediaFragment
.EXTRA_ACCOUNT
, mAccount
);
251 if (getFile().isVideo()) {
252 mSavedPlaybackPosition
= mVideoPreview
.getCurrentPosition();
253 mAutoplay
= mVideoPreview
.isPlaying();
254 outState
.putInt(PreviewMediaFragment
.EXTRA_PLAY_POSITION
, mSavedPlaybackPosition
);
255 outState
.putBoolean(PreviewMediaFragment
.EXTRA_PLAYING
, mAutoplay
);
258 PreviewMediaFragment
.EXTRA_PLAY_POSITION
,
259 mMediaServiceBinder
.getCurrentPosition());
261 PreviewMediaFragment
.EXTRA_PLAYING
, mMediaServiceBinder
.isPlaying());
267 public void onStart() {
269 Log_OC
.e(TAG
, "onStart");
271 OCFile file
= getFile();
272 if (file
!= null
&& file
.isDown()) {
273 if (file
.isAudio()) {
276 } else if (file
.isVideo()) {
284 private void stopAudio() {
285 Intent i
= new Intent(getActivity(), MediaService
.class);
286 i
.setAction(MediaService
.ACTION_STOP_ALL
);
287 getActivity().startService(i
);
295 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
296 super.onCreateOptionsMenu(menu
, inflater
);
297 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
305 public void onPrepareOptionsMenu(Menu menu
) {
306 super.onPrepareOptionsMenu(menu
);
308 if (mContainerActivity
.getStorageManager() != null
) {
309 FileMenuFilter mf
= new FileMenuFilter(
311 mContainerActivity
.getStorageManager().getAccount(),
318 // additional restriction for this fragment
319 // TODO allow renaming in PreviewImageFragment
320 MenuItem item
= menu
.findItem(R
.id
.action_rename_file
);
322 item
.setVisible(false
);
323 item
.setEnabled(false
);
326 // additional restriction for this fragment
327 item
= menu
.findItem(R
.id
.action_move
);
329 item
.setVisible(false
);
330 item
.setEnabled(false
);
339 public boolean onOptionsItemSelected(MenuItem item
) {
340 switch (item
.getItemId()) {
341 case R
.id
.action_share_file
: {
343 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile());
346 case R
.id
.action_unshare_file
: {
348 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
351 case R
.id
.action_open_file_with
: {
355 case R
.id
.action_remove_file
: {
356 RemoveFileDialogFragment dialog
= RemoveFileDialogFragment
.newInstance(getFile());
357 dialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
360 case R
.id
.action_see_details
: {
364 case R
.id
.action_send_file
: {
368 case R
.id
.action_sync_file
: {
369 mContainerActivity
.getFileOperationsHelper().syncFile(getFile());
372 case R
.id
.action_favorite_file
:{
373 mContainerActivity
.getFileOperationsHelper().toggleFavorite(getFile(), true
);
376 case R
.id
.action_unfavorite_file
:{
377 mContainerActivity
.getFileOperationsHelper().toggleFavorite(getFile(), false
);
388 * Update the file of the fragment with file value
391 public void updateFile(OCFile file
){
395 private void sendFile() {
397 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
401 private void seeDetails() {
403 mContainerActivity
.showDetails(getFile());
407 private void prepareVideo() {
408 // create helper to get more control on the playback
409 mVideoHelper
= new VideoHelper();
410 mVideoPreview
.setOnPreparedListener(mVideoHelper
);
411 mVideoPreview
.setOnCompletionListener(mVideoHelper
);
412 mVideoPreview
.setOnErrorListener(mVideoHelper
);
415 @SuppressWarnings("static-access")
416 private void playVideo() {
417 // create and prepare control panel for the user
418 mMediaController
.setMediaPlayer(mVideoPreview
);
420 // load the video file in the video player ;
421 // when done, VideoHelper#onPrepared() will be called
422 Uri uri
= Uri
.parse(getFile().getStoragePath());
423 mVideoPreview
.setVideoPath(uri
.encode(getFile().getStoragePath()));
427 private class VideoHelper
implements OnCompletionListener
, OnPreparedListener
, OnErrorListener
{
430 * Called when the file is ready to be played.
432 * Just starts the playback.
434 * @param vp {@link MediaPlayer} instance performing the playback.
437 public void onPrepared(MediaPlayer vp
) {
438 Log_OC
.e(TAG
, "onPrepared");
439 mVideoPreview
.seekTo(mSavedPlaybackPosition
);
441 mVideoPreview
.start();
443 mMediaController
.setEnabled(true
);
444 mMediaController
.updatePausePlay();
450 * Called when the file is finished playing.
452 * Finishes the activity.
454 * @param mp {@link MediaPlayer} instance performing the playback.
457 public void onCompletion(MediaPlayer mp
) {
458 Log_OC
.e(TAG
, "completed");
460 mVideoPreview
.seekTo(0);
461 // next lines are necessary to work around undesired video loops
462 if (Build
.VERSION
.SDK_INT
== Build
.VERSION_CODES
.GINGERBREAD
) {
463 mVideoPreview
.pause();
465 } else if (Build
.VERSION
.SDK_INT
== Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
466 // mVideePreview.pause() is not enough
468 mMediaController
.setEnabled(false
);
469 mVideoPreview
.stopPlayback();
471 mSavedPlaybackPosition
= 0;
472 mVideoPreview
.setVideoPath(getFile().getStoragePath());
474 } // else : called from onError()
475 mMediaController
.updatePausePlay();
480 * Called when an error in playback occurs.
482 * @param mp {@link MediaPlayer} instance performing the playback.
483 * @param what Type of error
484 * @param extra Extra code specific to the error
487 public boolean onError(MediaPlayer mp
, int what
, int extra
) {
488 if (mVideoPreview
.getWindowToken() != null
) {
489 String message
= MediaService
.getMessageForMediaError(
490 getActivity(), what
, extra
);
491 new AlertDialog
.Builder(getActivity())
493 .setPositiveButton(android
.R
.string
.VideoView_error_button
,
494 new DialogInterface
.OnClickListener() {
495 public void onClick(DialogInterface dialog
, int whichButton
) {
497 VideoHelper
.this.onCompletion(null
);
500 .setCancelable(false
)
510 public void onPause() {
511 Log_OC
.e(TAG
, "onPause");
516 public void onResume() {
518 Log_OC
.e(TAG
, "onResume");
522 public void onDestroy() {
523 Log_OC
.e(TAG
, "onDestroy");
528 public void onStop() {
529 Log_OC
.e(TAG
, "onStop");
532 if (mMediaServiceConnection
!= null
) {
533 Log_OC
.d(TAG
, "Unbinding from MediaService ...");
534 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
535 mMediaServiceBinder
.unregisterMediaController(mMediaController
);
537 getActivity().unbindService(mMediaServiceConnection
);
538 mMediaServiceConnection
= null
;
539 mMediaServiceBinder
= null
;
546 public boolean onTouch(View v
, MotionEvent event
) {
547 if (event
.getAction() == MotionEvent
.ACTION_DOWN
&& v
== mVideoPreview
) {
548 // added a margin on the left to avoid interfering with gesture to open navigation drawer
549 if (event
.getX() / Resources
.getSystem().getDisplayMetrics().density
> 24.0) {
550 startFullScreenVideo();
558 private void startFullScreenVideo() {
559 Intent i
= new Intent(getActivity(), PreviewVideoActivity
.class);
560 i
.putExtra(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
561 i
.putExtra(FileActivity
.EXTRA_FILE
, getFile());
562 i
.putExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, mVideoPreview
.isPlaying());
563 mVideoPreview
.pause();
564 i
.putExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, mVideoPreview
.getCurrentPosition());
565 startActivityForResult(i
, 0);
569 public void onConfigurationChanged (Configuration newConfig
) {
570 Log_OC
.e(TAG
, "onConfigurationChanged " + this);
574 public void onActivityResult (int requestCode
, int resultCode
, Intent data
) {
575 Log_OC
.e(TAG
, "onActivityResult " + this);
576 super.onActivityResult(requestCode
, resultCode
, data
);
577 if (resultCode
== Activity
.RESULT_OK
) {
578 mSavedPlaybackPosition
= data
.getExtras().getInt(
579 PreviewVideoActivity
.EXTRA_START_POSITION
);
580 mAutoplay
= data
.getExtras().getBoolean(PreviewVideoActivity
.EXTRA_AUTOPLAY
);
585 private void playAudio() {
586 OCFile file
= getFile();
587 if (!mMediaServiceBinder
.isPlaying(file
)) {
588 Log_OC
.d(TAG
, "starting playback of " + file
.getStoragePath());
589 mMediaServiceBinder
.start(mAccount
, file
, mAutoplay
, mSavedPlaybackPosition
);
592 if (!mMediaServiceBinder
.isPlaying() && mAutoplay
) {
593 mMediaServiceBinder
.start();
594 mMediaController
.updatePausePlay();
600 private void bindMediaService() {
601 Log_OC
.d(TAG
, "Binding to MediaService...");
602 if (mMediaServiceConnection
== null
) {
603 mMediaServiceConnection
= new MediaServiceConnection();
605 getActivity().bindService( new Intent(getActivity(),
607 mMediaServiceConnection
,
608 Context
.BIND_AUTO_CREATE
);
609 // follow the flow in MediaServiceConnection#onServiceConnected(...)
612 /** Defines callbacks for service binding, passed to bindService() */
613 private class MediaServiceConnection
implements ServiceConnection
{
616 public void onServiceConnected(ComponentName component
, IBinder service
) {
617 if (getActivity() != null
) {
618 if (component
.equals(
619 new ComponentName(getActivity(), MediaService
.class))) {
620 Log_OC
.d(TAG
, "Media service connected");
621 mMediaServiceBinder
= (MediaServiceBinder
) service
;
622 if (mMediaServiceBinder
!= null
) {
623 prepareMediaController();
624 playAudio(); // do not wait for the touch of nobody to play audio
626 Log_OC
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
629 Log_OC
.e(TAG
, "Unexpected response from MediaService while binding");
635 private void prepareMediaController() {
636 mMediaServiceBinder
.registerMediaController(mMediaController
);
637 if (mMediaController
!= null
) {
638 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
639 mMediaController
.setEnabled(true
);
640 mMediaController
.updatePausePlay();
645 public void onServiceDisconnected(ComponentName component
) {
646 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
647 Log_OC
.e(TAG
, "Media service suddenly disconnected");
648 if (mMediaController
!= null
) {
649 mMediaController
.setMediaPlayer(null
);
653 "No media controller to release when disconnected from media service",
654 Toast
.LENGTH_SHORT
).show();
656 mMediaServiceBinder
= null
;
657 mMediaServiceConnection
= null
;
665 * Opens the previewed file with an external application.
667 private void openFile() {
669 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
674 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment}
677 * @param file File to test if can be previewed.
678 * @return 'True' if the file can be handled by the fragment.
680 public static boolean canBePreviewed(OCFile file
) {
681 return (file
!= null
&& (file
.isAudio() || file
.isVideo()));
685 public void stopPreview(boolean stopAudio
) {
686 OCFile file
= getFile();
687 if (file
.isAudio() && stopAudio
) {
688 mMediaServiceBinder
.pause();
690 } else if (file
.isVideo()) {
691 mVideoPreview
.stopPlayback();
698 * Finishes the preview
700 private void finish() {
701 getActivity().onBackPressed();
705 public int getPosition() {
707 mSavedPlaybackPosition
= mVideoPreview
.getCurrentPosition();
709 Log_OC
.e(TAG
, "getting position: " + mSavedPlaybackPosition
);
710 return mSavedPlaybackPosition
;
713 public boolean isPlaying() {
715 mAutoplay
= mVideoPreview
.isPlaying();