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
.os
.Bundle
;
40 import android
.os
.IBinder
;
41 import android
.view
.LayoutInflater
;
42 import android
.view
.Menu
;
43 import android
.view
.MenuInflater
;
44 import android
.view
.MenuItem
;
45 import android
.view
.MotionEvent
;
46 import android
.view
.View
;
47 import android
.view
.View
.OnTouchListener
;
48 import android
.view
.ViewGroup
;
49 import android
.widget
.ImageView
;
50 import android
.widget
.Toast
;
51 import android
.widget
.VideoView
;
53 import com
.owncloud
.android
.R
;
54 import com
.owncloud
.android
.datamodel
.OCFile
;
55 import com
.owncloud
.android
.files
.FileMenuFilter
;
56 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
57 import com
.owncloud
.android
.media
.MediaControlView
;
58 import com
.owncloud
.android
.media
.MediaService
;
59 import com
.owncloud
.android
.media
.MediaServiceBinder
;
60 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
61 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
62 import com
.owncloud
.android
.ui
.dialog
.RemoveFileDialogFragment
;
63 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
67 * This fragment shows a preview of a downloaded media file (audio or video).
69 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will
70 * produce an {@link IllegalStateException}.
72 * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is
73 * generated on instantiation too.
75 public class PreviewMediaFragment
extends FileFragment
implements
78 public static final String EXTRA_FILE
= "FILE";
79 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
80 private static final String EXTRA_PLAY_POSITION
= "PLAY_POSITION";
81 private static final String EXTRA_PLAYING
= "PLAYING";
84 private Account mAccount
;
85 private ImageView mImagePreview
;
86 private VideoView mVideoPreview
;
87 private int mSavedPlaybackPosition
;
89 private MediaServiceBinder mMediaServiceBinder
= null
;
90 private MediaControlView mMediaController
= null
;
91 private MediaServiceConnection mMediaServiceConnection
= null
;
92 private VideoHelper mVideoHelper
;
93 private boolean mAutoplay
;
94 public boolean mPrepared
;
96 private static final String TAG
= PreviewMediaFragment
.class.getSimpleName();
100 * Creates a fragment to preview a file.
102 * When 'fileToDetail' or 'ocAccount' are null
104 * @param fileToDetail An {@link OCFile} to preview in the fragment
105 * @param ocAccount An ownCloud account; needed to start downloads
107 public PreviewMediaFragment(
110 int startPlaybackPosition
,
114 mAccount
= ocAccount
;
115 mSavedPlaybackPosition
= startPlaybackPosition
;
116 mAutoplay
= autoplay
;
121 * Creates an empty fragment for previews.
123 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically
124 * (for instance, when the device is turned a aside).
126 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful
129 public PreviewMediaFragment() {
132 mSavedPlaybackPosition
= 0;
141 public void onCreate(Bundle savedInstanceState
) {
142 super.onCreate(savedInstanceState
);
143 setHasOptionsMenu(true
);
151 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
152 Bundle savedInstanceState
) {
153 super.onCreateView(inflater
, container
, savedInstanceState
);
154 Log_OC
.v(TAG
, "onCreateView");
157 mView
= inflater
.inflate(R
.layout
.file_preview
, container
, false
);
159 mImagePreview
= (ImageView
) mView
.findViewById(R
.id
.image_preview
);
160 mVideoPreview
= (VideoView
) mView
.findViewById(R
.id
.video_preview
);
161 mVideoPreview
.setOnTouchListener(this);
163 mMediaController
= (MediaControlView
) mView
.findViewById(R
.id
.media_controller
);
173 public void onActivityCreated(Bundle savedInstanceState
) {
174 super.onActivityCreated(savedInstanceState
);
175 Log_OC
.v(TAG
, "onActivityCreated");
177 OCFile file
= getFile();
178 if (savedInstanceState
== null
) {
180 throw new IllegalStateException("Instanced with a NULL OCFile");
182 if (mAccount
== null
) {
183 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
185 if (!file
.isDown()) {
186 throw new IllegalStateException("There is no local file to preview");
191 file
= (OCFile
) savedInstanceState
.getParcelable(PreviewMediaFragment
.EXTRA_FILE
);
193 mAccount
= savedInstanceState
.getParcelable(PreviewMediaFragment
.EXTRA_ACCOUNT
);
194 mSavedPlaybackPosition
=
195 savedInstanceState
.getInt(PreviewMediaFragment
.EXTRA_PLAY_POSITION
);
196 mAutoplay
= savedInstanceState
.getBoolean(PreviewMediaFragment
.EXTRA_PLAYING
);
199 if (file
!= null
&& file
.isDown()) {
200 if (file
.isVideo()) {
201 mVideoPreview
.setVisibility(View
.VISIBLE
);
202 mImagePreview
.setVisibility(View
.GONE
);
207 mVideoPreview
.setVisibility(View
.GONE
);
208 mImagePreview
.setVisibility(View
.VISIBLE
);
209 extractAndSetCoverArt(file
);
216 * tries to read the cover art from the audio file and sets it as cover art.
218 * @param file audio file with potential cover art
220 private void extractAndSetCoverArt(OCFile file
) {
221 if (file
.isAudio()) {
223 MediaMetadataRetriever mmr
= new MediaMetadataRetriever();
224 mmr
.setDataSource(file
.getStoragePath());
225 byte[] data
= mmr
.getEmbeddedPicture();
227 Bitmap bitmap
= BitmapFactory
.decodeByteArray(data
, 0, data
.length
);
228 mImagePreview
.setImageBitmap(bitmap
); //associated cover art in bitmap
230 mImagePreview
.setImageResource(R
.drawable
.logo
);
232 } catch (Throwable t
) {
233 mImagePreview
.setImageResource(R
.drawable
.logo
);
243 public void onSaveInstanceState(Bundle outState
) {
244 super.onSaveInstanceState(outState
);
245 Log_OC
.v(TAG
, "onSaveInstanceState");
247 outState
.putParcelable(PreviewMediaFragment
.EXTRA_FILE
, getFile());
248 outState
.putParcelable(PreviewMediaFragment
.EXTRA_ACCOUNT
, mAccount
);
250 if (getFile().isVideo()) {
251 mSavedPlaybackPosition
= mVideoPreview
.getCurrentPosition();
252 mAutoplay
= mVideoPreview
.isPlaying();
253 outState
.putInt(PreviewMediaFragment
.EXTRA_PLAY_POSITION
, mSavedPlaybackPosition
);
254 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
.v(TAG
, "onStart");
271 OCFile file
= getFile();
272 if (file
!= null
&& file
.isDown()) {
273 if (file
.isAudio()) {
278 if (file
.isVideo()) {
287 private void stopAudio() {
288 Intent i
= new Intent(getActivity(), MediaService
.class);
289 i
.setAction(MediaService
.ACTION_STOP_ALL
);
290 getActivity().startService(i
);
298 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
299 super.onCreateOptionsMenu(menu
, inflater
);
300 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
308 public void onPrepareOptionsMenu(Menu menu
) {
309 super.onPrepareOptionsMenu(menu
);
311 if (mContainerActivity
.getStorageManager() != null
) {
312 FileMenuFilter mf
= new FileMenuFilter(
314 mContainerActivity
.getStorageManager().getAccount(),
321 // additional restriction for this fragment
322 // TODO allow renaming in PreviewImageFragment
323 MenuItem item
= menu
.findItem(R
.id
.action_rename_file
);
325 item
.setVisible(false
);
326 item
.setEnabled(false
);
329 // additional restriction for this fragment
330 item
= menu
.findItem(R
.id
.action_move
);
332 item
.setVisible(false
);
333 item
.setEnabled(false
);
336 // additional restriction for this fragment
337 item
= menu
.findItem(R
.id
.action_copy
);
339 item
.setVisible(false
);
340 item
.setEnabled(false
);
349 public boolean onOptionsItemSelected(MenuItem item
) {
350 switch (item
.getItemId()) {
351 case R
.id
.action_share_file
: {
355 case R
.id
.action_open_file_with
: {
359 case R
.id
.action_remove_file
: {
360 RemoveFileDialogFragment dialog
= RemoveFileDialogFragment
.newInstance(getFile());
361 dialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
364 case R
.id
.action_see_details
: {
368 case R
.id
.action_send_file
: {
372 case R
.id
.action_sync_file
: {
373 mContainerActivity
.getFileOperationsHelper().syncFile(getFile());
376 case R
.id
.action_favorite_file
:{
377 mContainerActivity
.getFileOperationsHelper().toggleFavorite(getFile(), true
);
380 case R
.id
.action_unfavorite_file
:{
381 mContainerActivity
.getFileOperationsHelper().toggleFavorite(getFile(), false
);
391 * Update the file of the fragment with file value
393 * @param file Replaces the held file with a new one
395 public void updateFile(OCFile file
) {
399 private void sendFile() {
401 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
405 private void seeDetails() {
407 mContainerActivity
.showDetails(getFile());
410 private void seeShareFile() {
412 mContainerActivity
.getFileOperationsHelper().showShareFile(getFile());
415 private void prepareVideo() {
416 // create helper to get more control on the playback
417 mVideoHelper
= new VideoHelper();
418 mVideoPreview
.setOnPreparedListener(mVideoHelper
);
419 mVideoPreview
.setOnCompletionListener(mVideoHelper
);
420 mVideoPreview
.setOnErrorListener(mVideoHelper
);
423 @SuppressWarnings("static-access")
424 private void playVideo() {
425 // create and prepare control panel for the user
426 mMediaController
.setMediaPlayer(mVideoPreview
);
428 // load the video file in the video player ;
429 // when done, VideoHelper#onPrepared() will be called
430 mVideoPreview
.setVideoURI(getFile().getStorageUri());
434 private class VideoHelper
implements OnCompletionListener
, OnPreparedListener
, OnErrorListener
{
437 * Called when the file is ready to be played.
439 * Just starts the playback.
441 * @param vp {@link MediaPlayer} instance performing the playback.
444 public void onPrepared(MediaPlayer vp
) {
445 Log_OC
.v(TAG
, "onPrepared");
446 mVideoPreview
.seekTo(mSavedPlaybackPosition
);
448 mVideoPreview
.start();
450 mMediaController
.setEnabled(true
);
451 mMediaController
.updatePausePlay();
457 * Called when the file is finished playing.
459 * Finishes the activity.
461 * @param mp {@link MediaPlayer} instance performing the playback.
464 public void onCompletion(MediaPlayer mp
) {
465 Log_OC
.v(TAG
, "completed");
467 mVideoPreview
.seekTo(0);
468 } // else : called from onError()
469 mMediaController
.updatePausePlay();
474 * Called when an error in playback occurs.
476 * @param mp {@link MediaPlayer} instance performing the playback.
477 * @param what Type of error
478 * @param extra Extra code specific to the error
481 public boolean onError(MediaPlayer mp
, int what
, int extra
) {
482 Log_OC
.e(TAG
, "Error in video playback, what = " + what
+ ", extra = " + extra
);
483 if (mVideoPreview
.getWindowToken() != null
) {
484 String message
= MediaService
.getMessageForMediaError(
485 getActivity(), what
, extra
);
486 new AlertDialog
.Builder(getActivity())
488 .setPositiveButton(android
.R
.string
.VideoView_error_button
,
489 new DialogInterface
.OnClickListener() {
490 public void onClick(DialogInterface dialog
, int whichButton
) {
492 VideoHelper
.this.onCompletion(null
);
495 .setCancelable(false
)
505 public void onPause() {
506 Log_OC
.v(TAG
, "onPause");
511 public void onResume() {
513 Log_OC
.v(TAG
, "onResume");
517 public void onDestroy() {
518 Log_OC
.v(TAG
, "onDestroy");
523 public void onStop() {
524 Log_OC
.v(TAG
, "onStop");
527 if (mMediaServiceConnection
!= null
) {
528 Log_OC
.d(TAG
, "Unbinding from MediaService ...");
529 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
530 mMediaServiceBinder
.unregisterMediaController(mMediaController
);
532 getActivity().unbindService(mMediaServiceConnection
);
533 mMediaServiceConnection
= null
;
534 mMediaServiceBinder
= null
;
541 public boolean onTouch(View v
, MotionEvent event
) {
542 if (event
.getAction() == MotionEvent
.ACTION_DOWN
&& v
== mVideoPreview
) {
543 // added a margin on the left to avoid interfering with gesture to open navigation drawer
544 if (event
.getX() / Resources
.getSystem().getDisplayMetrics().density
> 24.0) {
545 startFullScreenVideo();
553 private void startFullScreenVideo() {
554 Intent i
= new Intent(getActivity(), PreviewVideoActivity
.class);
555 i
.putExtra(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
556 i
.putExtra(FileActivity
.EXTRA_FILE
, getFile());
557 i
.putExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, mVideoPreview
.isPlaying());
558 mVideoPreview
.pause();
559 i
.putExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, mVideoPreview
.getCurrentPosition());
560 startActivityForResult(i
, 0);
564 public void onConfigurationChanged(Configuration newConfig
) {
565 Log_OC
.v(TAG
, "onConfigurationChanged " + this);
569 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
570 Log_OC
.v(TAG
, "onActivityResult " + this);
571 super.onActivityResult(requestCode
, resultCode
, data
);
572 if (resultCode
== Activity
.RESULT_OK
) {
573 mSavedPlaybackPosition
= data
.getExtras().getInt(
574 PreviewVideoActivity
.EXTRA_START_POSITION
);
575 mAutoplay
= data
.getExtras().getBoolean(PreviewVideoActivity
.EXTRA_AUTOPLAY
);
580 private void playAudio() {
581 OCFile file
= getFile();
582 if (!mMediaServiceBinder
.isPlaying(file
)) {
583 Log_OC
.d(TAG
, "starting playback of " + file
.getStoragePath());
584 mMediaServiceBinder
.start(mAccount
, file
, mAutoplay
, mSavedPlaybackPosition
);
588 if (!mMediaServiceBinder
.isPlaying() && mAutoplay
) {
589 mMediaServiceBinder
.start();
590 mMediaController
.updatePausePlay();
596 private void bindMediaService() {
597 Log_OC
.d(TAG
, "Binding to MediaService...");
598 if (mMediaServiceConnection
== null
) {
599 mMediaServiceConnection
= new MediaServiceConnection();
601 getActivity().bindService( new Intent(getActivity(),
603 mMediaServiceConnection
,
604 Context
.BIND_AUTO_CREATE
);
605 // follow the flow in MediaServiceConnection#onServiceConnected(...)
608 /** Defines callbacks for service binding, passed to bindService() */
609 private class MediaServiceConnection
implements ServiceConnection
{
612 public void onServiceConnected(ComponentName component
, IBinder service
) {
613 if (getActivity() != null
) {
614 if (component
.equals(
615 new ComponentName(getActivity(), MediaService
.class))) {
616 Log_OC
.d(TAG
, "Media service connected");
617 mMediaServiceBinder
= (MediaServiceBinder
) service
;
618 if (mMediaServiceBinder
!= null
) {
619 prepareMediaController();
620 playAudio(); // do not wait for the touch of nobody to play audio
622 Log_OC
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
626 Log_OC
.e(TAG
, "Unexpected response from MediaService while binding");
632 private void prepareMediaController() {
633 mMediaServiceBinder
.registerMediaController(mMediaController
);
634 if (mMediaController
!= null
) {
635 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
636 mMediaController
.setEnabled(true
);
637 mMediaController
.updatePausePlay();
642 public void onServiceDisconnected(ComponentName component
) {
643 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
644 Log_OC
.w(TAG
, "Media service suddenly disconnected");
645 if (mMediaController
!= null
) {
646 mMediaController
.setMediaPlayer(null
);
651 "No media controller to release when disconnected from media service",
652 Toast
.LENGTH_SHORT
).show();
654 mMediaServiceBinder
= null
;
655 mMediaServiceConnection
= null
;
662 * Opens the previewed file with an external application.
664 private void openFile() {
666 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
671 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment}
674 * @param file File to test if can be previewed.
675 * @return 'True' if the file can be handled by the fragment.
677 public static boolean canBePreviewed(OCFile file
) {
678 return (file
!= null
&& (file
.isAudio() || file
.isVideo()));
682 public void stopPreview(boolean stopAudio
) {
683 OCFile file
= getFile();
684 if (file
.isAudio() && stopAudio
) {
685 mMediaServiceBinder
.pause();
689 if (file
.isVideo()) {
690 mVideoPreview
.stopPlayback();
697 * Finishes the preview
699 private void finish() {
700 getActivity().onBackPressed();
704 public int getPosition() {
706 mSavedPlaybackPosition
= mVideoPreview
.getCurrentPosition();
708 Log_OC
.v(TAG
, "getting position: " + mSavedPlaybackPosition
);
709 return mSavedPlaybackPosition
;
712 public boolean isPlaying() {
714 mAutoplay
= mVideoPreview
.isPlaying();