- Android studio videoview fullscreen
- Android VideoView Full Screen Example
- Adding Full Screen Functionality & Custom MediaController
- Custom MediaController
- Activity
- Layout
- Playing Videos Full Screen when Device in Landscape Orientation
- About
- Android studio videoview fullscreen
- About
- Работа с мультимедиа
- Работа с видео
- MediaController
- VideoView
- Связка с MediaPlayer
- artemisia-absynthium / AndroidManifest.xml
Android studio videoview fullscreen
October 27, 2017
If you want to provide video content in your application, you can create a feature in your app to play videos using Android VideoView and MediaController. Playing videos in full screen gives the best user experience.
In this post, I’ll explain how to create a feature in your app which allows users to play videos in full screen and exit full screen.
Android VideoView Full Screen Example
We will use window flag to enter and exit full screen. By setting window flag WindowManager.LayoutParams.FLAG_FULLSCREEN, VideoView can be made to be played in full screen mode. And also, if there are other views on the screen, you need to hide them when entering into full screen and shown them back on full screen exit like for example action bar.
We need to provide a button along with VideoView for entering and exiting full screen mode. Every time the button is clicked, it will restart the video activity and provide the desired behavior by showing VideoView in full screen and existing full screen.
I experimented with other ways of providing full screen feature, but implementing in the way explained above is the best way in my opinion.
Adding Full Screen Functionality & Custom MediaController
First thing we need is a button in UI that can be used to view video in full screen and exit full screen to watch in normal mode. The best component to place view-full-screen and exit-full-screen button is in MediaController as MediaController is associated with VideoView and is visible on touching the video.
So, to add full screen button to MediaController, we need to customize MediaController by creating a subclass and overriding setAnchorView method.
In setAnchorView method, create a button, add layout parameters and add it to media controller by calling addView mthod.
Get icons for enter-full-screen and exit-full-screen buttons and save them in your project. Based on the indicator from intent in setAnchorView of MediaController, you can set button icon to either enter-full-screen or exit-full-screen icon.
Add onclick listener to the button, in the listener, toggle image icon and restart the activity passing full screen or normal mode indicator.
Below picture shows video view in normal mode with enter full screen button in medial controller.
Below picture shows video view in full screen mode.
Custom MediaController
Activity
Activity sets window’s flag to FLAG_FULLSCREEN by calling setFlag on it if full screen indicator from intent is on.
Layout
Playing Videos Full Screen when Device in Landscape Orientation
If you don’t want to show full screen feature in your app when device is in portrait orientation, then you can simply use MediaController instead of custom media controller which has full screen button.
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник
Android studio videoview fullscreen
An Android Library to replace VideoView.
Adds fullscreen funcionality, encapsulating MediaPlayer as video player.
In addition to replace VideoView, FullscreenVideoView can organize some child views, as it extends RelativeLayout 😉
And, support for min SDK version is 7.
I’ve created FullscreenVideoLayout using FullscreenVideoView with some UI (play/pause buttons, fullscreen button and seekbar)
If you don’t want to create your own video controls, you can use FullscreenVideoLayout.
Suppose we want to build a screen like that:
Remember to create a FullscreenVideoLayout container because FullscreenVideoLayout is added in its original parent, when coming back from fullscreen.
So, is very important to put FullscreenVideoLayout inside a View container. I’m going to change it in near future. But, it will not affect this container implementation.
If you want to use portrait and landscape mode, just remember to put android:configChanges=»orientation|screenSize» and implement onConfigurationChanged inside Activity, to avoid recreating content view everytime we change the device orientation.
Ok, but I want to create my own controls:
Let’s describe the process to customize your view controls’.
The first thing we have to do, is create the UI:
As FullscreenVideoView extends RelativeLayout (ViewGroup) we can add some child views. You could use XML and write inside the FullscreenVideoView tag, but as we are creating a new Class (extending FullscreenVideoView), we are going to create the control view inside the constructor.
So, first thing is to create a new Class extending FullscreenVideoView:
And then, we override our FullscreenVideoView.init() method:
Now we have our control bar inside our view.
Next, we need to implement what to do with our buttons. So, at the end of init() method, we add:
And then, we need to interact with our buttons:
Now, we need to hide/show our control view when user clicks inside our view.
First, we add at the end of init():
Where hideControls() and showControls() just calls videoControlsView.setVisibility()
Now, we want to update the seekBar with the progress of the video.
To implement that, we need a Handler and a Runnable to check FullscreenVideoVideo.getCurrentPosition() in a 500ms interval.
And then, we update our seekBar writing inside our Runnable:
I have override some other methods to control start/stop the updateTimeRunnable
You can see the full FullscreenVideoLayout sample here.
About
An Android Library to replace VideoView with Fullscreen feature
Источник
Работа с мультимедиа
Работа с видео
Для работы с видеоматериалами в стандартном наборе виджетов Android определен класс VideoView, который позволяет воспроизводить видео.
Какие типы видеофайлов можно использовать? Android поддерживает большинство распространенных типов видеофайлов, в частности, 3GPP (.3gp), WebM (.webm), Matroska (.mkv), MPEG-4 (.mp4).
VideoView может работать как с роликами, размещенными на мобильном устройстве, так и с видеоматериалами из сети. В данном случае используем видеоролик, размещенный локально. Для этого добавим в проект какой-нибудь видеоролик. Обычно видеоматериалы помещают в проекте в папку res/raw . По умолчанию проект не содержит подобной папки, поэтому добавим в каталог res подпапку raw. Для этого нажмем на папку res правой кнопкой мыши и в появившемся меню выберем New -> Android Resource Directory :
Затем в появившемся окне в качестве типа папки укажем raw (что также будет использоваться в качестве названия папки):
После добавления папки raw скопируем в нее какой-нибудь видеофайл:
Теперь определим функционал для его воспроизведения. Для этого в файле activity_main.xml укажем следующий код:
Для управления воспроизведением видео здесь определены три кнопки: для запуска видео, для паузы и для его остановки.
И также изменим код MainActivity :
Во-первых, чтобы управлять потоком воспроизведения, нам надо получить объект VideoView: videoPlayer = findViewById(R.id.videoPlayer);
Чтобы указать источник воспроизведения, необходим объект Uri . В данном случае с помощью выражения Uri myVideoUri= Uri.parse(«android.resource://» + getPackageName() + «/» + R.raw.cats); получаем адрес видеоролика внутри пакета приложения.
Строка URI имеет ряд частей: сначала идет Uri-схема ( http:// или как здесь android.resource:// ), затем название пакета, получаемое через метод getPackageName(), и далее непосредственно название ресурса видео из папки res/raw , которое совпадает с названием файла.
Затем этот Uri устанавливается у videoPlayerа: videoPlayer.setVideoURI(myVideoUri);
Чтобы управлять видеопотоком, обработчики нажатия кнопок вызывают соответствующее действие:
Метод videoPlayer.start() начинает или продолжает воспроизведение.
Метод videoPlayer.pause() приостанавливает видео.
Метод videoPlayer.stopPlayback() полностью останавливает видео.
Метод videoPlayer.resume() позволяет снова начать воспроизведение видео с начала после его полной остановки.
При запуске приложения мы сможем с помощью кнопок управляь воспроизведением:
MediaController
С помощью класса MediaController мы можем добавить к VideoView дополнительно элементы управления. Для этого изменим код MainActivity:
И если мы запустим приложения, то при касании по VideoView внизу появятся инструменты для управления видео. В прицнипе теперь и кнопки, которые мы создали ранее, не нужны:
Источник
VideoView
Компонент VideoView предназначен для воспроизведения видеоклипов.
Находится в разделе Images. Желательно использовать реальное устройство при тестировании примеров.
Android поддерживает файлы формата 3gp и mp4. Точную информацию по поддержке форматов воспроизведения мультимедийных файлов смотрите на сайте .
Использовать класс VideoView очень просто. Он содержит поверхность (объект Surface), на которую выводится видео, а также инкапсулирует все операции по управлению проигрывателем. Размещаете на экране компонент и указываете путь к воспроизводимому файлу. Можно воспроизводить файлы с флеш-карточки, из ресурсов или с веб-сервера через интернет.
Данный элемент скрывает от разработчика инициализацию медиапроигрывателя, предоставляя удобный и простой API. Чтобы задать видео для воспроизведения, вызовите метод setVideoPath() или setVideoUri(). В качестве единственного параметра они принимают путь к локальному файлу, путь URI к источнику данных или адрес удалённого видеопотока.
Завершив инициализацию, вы получаете возможность управлять воспроизведением с помощью методов start(), stopPlayback(), pause() и seekTo(). VideoView также включает метод setKeepScreenOn() для предотвращения отключения подсветки экрана во время проигрывания.
Код для воспроизведения:
Метод setVideoPath() указывает на файл, который находится на SD-карточке. Не забудьте установить разрешение
Метод videoView.setMediaController(new MediaController(this)); позволяет вывести кнопки паузы и воспроизведения. Кнопки появляются, если коснуться экрана. Можете не использовать данную возможность или отключать программно, используя значение null.
Метод requestFocus() необходим, чтобы компонент получил фокус и реагировал на касания пальцев.
Метод start() позволяет сразу начать воспроизведение файла. Если вам не нужно, то не добавляйте строку в код.
Если вам нужно воспроизвести файл с сервера, то нужно использовать метод setVideoURI:
Не забываем добавить необходимое разрешение для работы через интернет:
Ещё можно поместить файл в папку ресурсов res/raw. В этом случае также надо использовать URI:
Связка с MediaPlayer
Компонент может использовать методы интерфейса, которые используются классом MediaPlayer.
В комментариях дан альтернативный вариант загрузки файла из интернета. Раньше в Android 2.2 пример работал, сейчас я проверил на новых устройствах — видео не показывалось. Не знаю с чем связано.
Источник
artemisia-absynthium / AndroidManifest.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
xml version = » 1.0 » encoding = » utf-8 » ?> |
FrameLayout xmlns : android = » http://schemas.android.com/apk/res/android « |
xmlns : tools = » http://schemas.android.com/tools « |
android : id = » @+id/enclosing_layout « |
android : layout_width = » match_parent « |
android : layout_height = » match_parent « |
android : background = » @android:color/black « |
tools : context = » .FullscreenVideoActivity » > |
com .google.android.exoplayer2.ui.PlayerView |
android : id = » @+id/player_view « |
android : layout_width = » match_parent « |
android : layout_height = » match_parent »/> |
FrameLayout > |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
. |
activity |
android : name = » .FullscreenVideoActivity « |
android : configChanges = » orientation|keyboardHidden|screenSize « |
android : label = » @string/app_name « |
android : theme = » @style/FullscreenTheme »/> |
. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
. |
color name = » black_overlay » >#66000000 color > |
. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
xml version = » 1.0 » encoding = » utf-8 » ?> |
LinearLayout xmlns : android = » http://schemas.android.com/apk/res/android « |
xmlns : app = » http://schemas.android.com/apk/res-auto « |
android : layout_width = » match_parent « |
android : layout_height = » wrap_content « |
android : layout_gravity = » bottom « |
android : background = » #CC000000 « |
android : layoutDirection = » ltr « |
android : orientation = » vertical » > |
LinearLayout |
android : layout_width = » match_parent « |
android : layout_height = » wrap_content « |
android : gravity = » center « |
android : orientation = » horizontal « |
android : paddingTop = » 4dp » > |
ImageButton |
android : id = » @id/exo_prev « |
style = » @style/ExoMediaButton.Previous »/> |
ImageButton |
android : id = » @id/exo_rew « |
style = » @style/ExoMediaButton.Rewind »/> |
ImageButton |
android : id = » @id/exo_shuffle « |
style = » @style/ExoMediaButton.Shuffle »/> |
ImageButton |
android : id = » @id/exo_repeat_toggle « |
style = » @style/ExoMediaButton »/> |
ImageButton |
android : id = » @id/exo_play « |
style = » @style/ExoMediaButton.Play »/> |
ImageButton |
android : id = » @id/exo_pause « |
style = » @style/ExoMediaButton.Pause »/> |
ImageButton |
android : id = » @id/exo_ffwd « |
style = » @style/ExoMediaButton.FastForward »/> |
ImageButton |
android : id = » @id/exo_next « |
style = » @style/ExoMediaButton.Next »/> |
LinearLayout > |
LinearLayout |
android : layout_width = » match_parent « |
android : layout_height = » wrap_content « |
android : layout_marginTop = » 4dp « |
android : gravity = » center_vertical « |
android : orientation = » horizontal » > |
TextView |
android : id = » @id/exo_position « |
android : layout_width = » wrap_content « |
android : layout_height = » wrap_content « |
android : includeFontPadding = » false « |
android : paddingLeft = » 4dp « |
android : paddingRight = » 4dp « |
android : textColor = » #FFBEBEBE « |
android : textSize = » 14sp « |
android : textStyle = » bold »/> |
com .google.android.exoplayer2.ui.DefaultTimeBar |
android : id = » @id/exo_progress « |
android : layout_width = » 0dp « |
android : layout_height = » 26dp « |
android : layout_weight = » 1 »/> |
TextView |
android : id = » @id/exo_duration « |
android : layout_width = » wrap_content « |
android : layout_height = » wrap_content « |
android : includeFontPadding = » false « |
android : paddingLeft = » 4dp « |
android : paddingRight = » 4dp « |
android : textColor = » #FFBEBEBE « |
android : textSize = » 14sp « |
android : textStyle = » bold »/> |
FrameLayout |
android : id = » @+id/exo_fullscreen_button « |
android : layout_width = » 32dp « |
android : layout_height = » wrap_content « |
android : layout_gravity = » right » > |
ImageView |
android : id = » @+id/exo_fullscreen_icon « |
android : layout_width = » 40dp « |
android : layout_height = » 40dp « |
android : layout_gravity = » center « |
android : adjustViewBounds = » true « |
android : scaleType = » fitCenter « |
app : srcCompat = » @drawable/ic_fullscreen »/> |
FrameLayout > |
LinearLayout > |
LinearLayout > |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
xml version = » 1.0 » encoding = » utf-8 » ?> |
merge xmlns : android = » http://schemas.android.com/apk/res/android » > |
com .google.android.exoplayer2.ui.AspectRatioFrameLayout |
android : id = » @id/exo_content_frame « |
android : layout_width = » match_parent « |
android : layout_height = » match_parent « |
android : layout_gravity = » center » > |
Video surface will be inserted as the first child of the content frame. —> |
View |
android : id = » @id/exo_shutter « |
android : layout_width = » match_parent « |
android : layout_height = » match_parent « |
android : background = » @android:color/black »/> |
ImageView |
android : id = » @id/exo_artwork « |
android : layout_width = » match_parent « |
android : layout_height = » match_parent « |
android : scaleType = » fitXY »/> |
com .google.android.exoplayer2.ui.SubtitleView |
android : id = » @id/exo_subtitles « |
android : layout_width = » match_parent « |
android : layout_height = » match_parent »/> |
com .google.android.exoplayer2.ui.AspectRatioFrameLayout> |
FrameLayout |
android : id = » @id/exo_overlay « |
android : layout_width = » match_parent « |
android : layout_height = » match_parent »/> |
com .google.android.exoplayer2.ui.PlayerControlView |
android : id = » @id/exo_controller « |
android : layout_width = » match_parent « |
android : layout_height = » match_parent »/> |
merge > |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
public class ExoPlayerViewManager < |
private static final String TAG = » ExoPlayerViewManager » ; |
public static final String EXTRA_VIDEO_URI = » video_uri » ; |
private static Map String , ExoPlayerViewManager > instances = new HashMap<> (); |
private Uri videoUri; |
public static ExoPlayerViewManager getInstance ( String videoUri ) < |
ExoPlayerViewManager instance = instances . get(videoUri); |
if (instance == null ) < |
instance = new ExoPlayerViewManager (videoUri); |
instances . put(videoUri, instance); |
> |
return instance; |
> |
private SimpleExoPlayer player; |
private boolean isPlayerPlaying; |
private ExoPlayerViewManager ( String videoUri ) < |
this . videoUri = Uri . parse(videoUri); |
> |
public void prepareExoPlayer ( Context context , PlayerView exoPlayerView ) < |
if (context == null || exoPlayerView == null ) < |
return ; |
> |
if (player == null ) < |
// Create a new player if the player is null or |
// we want to play a new video |
// Do all the standard ExoPlayer code here. |
// Prepare the player with the source. |
player . prepare(videoSource); |
> |
player . clearVideoSurface(); |
player . setVideoSurfaceView(( SurfaceView ) exoPlayerView . getVideoSurfaceView()); |
player . seekTo(player . getCurrentPosition() + 1 ); |
exoPlayerView . setPlayer(player); |
> |
public void releaseVideoPlayer () < |
if (player != null ) < |
player . release(); |
> |
player = null ; |
> |
public void goToBackground () < |
if (player != null ) < |
isPlayerPlaying = player . getPlayWhenReady(); |
player . setPlayWhenReady( false ); |
> |
> |
public void goToForeground () < |
if (player != null ) < |
player . setPlayWhenReady(isPlayerPlaying); |
> |
> |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
// Fullscreen related code taken from Android Studio blueprint |
public class FullscreenVideoActivity extends AppCompatActivity < |
/** |
* Some older devices needs a small delay between UI widget updates |
* and a change of the status and navigation bar. |
*/ |
private static final int UI_ANIMATION_DELAY = 300 ; |
private final Handler mHideHandler = new Handler (); |
private View mContentView; |
private final Runnable mHidePart2Runnable = new Runnable () < |
@SuppressLint ( » InlinedApi » ) |
@Override |
public void run () < |
// Delayed removal of status and navigation bar |
// Note that some of these constants are new as of |
// API 19 (KitKat). It is safe to use them, as they are inlined |
// at compile-time and do nothing on earlier devices. |
mContentView . setSystemUiVisibility( View . SYSTEM_UI_FLAG_LOW_PROFILE |
| View . SYSTEM_UI_FLAG_FULLSCREEN |
| View . SYSTEM_UI_FLAG_LAYOUT_STABLE |
| View . SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
| View . SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
| View . SYSTEM_UI_FLAG_HIDE_NAVIGATION ); |
> |
>; |
private final Runnable mHideRunnable = new Runnable () < |
@Override |
public void run () < |
hide(); |
> |
>; |
private String mVideoUri; |
@Override |
public void onCreate ( Bundle savedInstanceState ) < |
super . onCreate(savedInstanceState); |
setContentView( R . layout . activity_fullscreen_video); |
mContentView = findViewById( R . id . enclosing_layout); |
PlayerView playerView = findViewById( R . id . player_view); |
mVideoUri = getIntent() . getStringExtra( ExoPlayerViewManager . EXTRA_VIDEO_URI ); |
ExoPlayerViewManager . getInstance(mVideoUri) |
.prepareExoPlayer( this , playerView); |
// Set the fullscreen button to «close fullscreen» icon |
View controlView = playerView . findViewById( R . id . exo_controller); |
ImageView fullscreenIcon = controlView . findViewById( R . id . exo_fullscreen_icon); |
fullscreenIcon . setImageResource( R . drawable . exo_controls_fullscreen_exit); |
controlView . findViewById( R . id . exo_fullscreen_button) |
.setOnClickListener( new View . OnClickListener () < |
@Override |
public void onClick ( View v ) < |
finish(); |
> |
>); |
> |
@Override |
public void onResume () < |
super . onResume(); |
ExoPlayerViewManager . getInstance(mVideoUri) . goToForeground(); |
> |
@Override |
public void onPause () < |
super . onPause(); |
ExoPlayerViewManager . getInstance(mVideoUri) . goToBackground(); |
> |
@Override |
public void onPostCreate ( Bundle savedInstanceState ) < |
super . onPostCreate(savedInstanceState); |
// Trigger the initial hide() shortly after the activity has been |
// created, to briefly hint to the user that UI controls |
// are available. |
delayedHide(); |
> |
private void hide () < |
// Schedule a runnable to remove the status and navigation bar after a delay |
mHideHandler . postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY ); |
> |
/** |
* Schedules a call to hide() in delay milliseconds, canceling any |
* previously scheduled calls. |
*/ |
private void delayedHide () < |
mHideHandler . removeCallbacks(mHideRunnable); |
mHideHandler . postDelayed(mHideRunnable, 100 ); |
> |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
public class MyActivity extends AppCompatActivity < |
private List String > mVideoUrls; |
@Override |
public void onCreate ( Bundle savedInstanceState ) < |
super . onCreate(savedInstanceState); |
// Your activity setup code. |
for ( String videoUrl : mVideoUrls) < |
setupPlayerView(videoView, videoUrl); |
> |
> |
@Override |
public void onResume () < |
super . onResume(); |
for ( String videoUrl : mVideoUrls) < |
ExoPlayerViewManager . getInstance(videoUrl) . goToForeground(); |
> |
> |
@Override |
public void onPause () < |
super . onPause(); |
for ( String videoUrl : mVideoUrls) < |
ExoPlayerViewManager . getInstance(videoUrl) . goToBackground(); |
> |
> |
@Override |
public void onDestroyView () < |
super . onDestroyView(); |
for ( String videoUrl : mVideoUrls) < |
ExoPlayerViewManager . getInstance(videoUrl) . releaseVideoPlayer(); |
> |
> |
private void setupPlayerView ( final PlayerView videoView , final String videoUrl ) < |
ExoPlayerViewManager . getInstance(videoUrl) . prepareExoPlayer(getContext(), videoView); |
ExoPlayerViewManager . getInstance(videoUrl) . goToForeground(); |
View controlView = videoView . findViewById( R . id . exo_controller); |
controlView . findViewById( R . id . exo_fullscreen_button) |
.setOnClickListener( new View . OnClickListener () < |
@Override |
public void onClick ( View v ) < |
Intent intent = new Intent (getContext(), FullscreenVideoActivity . class); |
intent . putExtra( ExoPlayerViewManager . EXTRA_VIDEO_URI , videoUrl); |
getActivity() . startActivity(intent); |
> |
>); |
> |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Источник