Android studio picture in picture

Android studio picture in picture

Android Picture in Picture Mode Example

February 07, 2018

Picture in picture support, introduced in Android 8.0 API level 26 and uses multi window APIs, allows you to develop a feature in your app which lets users to view an activity in a small window pinned to a corner while users can do something on the main screen. This feature is intended for playing videos in a small window while user is trying to browse files on the main screen or to perform other actions.

In this post, you can learn how to make an activity enter and exit picture-in-picture mode, hide and show UI controls on activity screen depending on picture-in-picture mode and implement picture-in-picture feature with an example.

Picture in Picture Mode Example

Our example app, which shows how to implement picture-in-picture mode, first displays a screen which allows user to select a video. On selecting a video, it will start video activity and play the video in VideoView with an option of allowing user to choose videos. When user click the button, video activity will be shown in PIP mode and user can select video from the previous activity. On selecting a video again, it will reuse the video activity which is running in PIP mode and start playing new video in full-screen mode.

Below screen shows video activity in fullscreen mode.

Below screen shows video activity in PIP mode.

Entering Picture in Picture Mode

First step to provide picture-in-picture support in your app is configuring the activity that you want to provide picture-in-picture support for. In AndroidManifest xml file, you need to set android:resizeableActivity and android:supportsPictureInPicture attributes of activity declaration to true.

In Android, any layout or configuration change restarts an activity. Since we don’t want this behavior when an activity transitions into picture-in-picture mode, we need to add android:configChanges to inform the system that activity handles the configuration changes.

Once activity declaration is complete, you need to provide a way for user to make the activity display in picture-in-picture mode. In our example, it is button, clicking it displays the activity in picture-in-picture mode and shows previous activity that allows user to choose a different video file. Other way of showing PIP mode is when user presses home button or recents button.

To display an activity in picture-in-picture mode, you need to call enterPictureInPictureMode method of activity passing PictureInPictureParams.Builder object. PictureInPictureParams.Builder allows you to set actions for the activity in picture-in-picture mode using setActions method and to set aspect ratio of activity using setAspectRatio method.

Exiting Picture in Picture Mode

When the activity which is in picture-in-picture mode is touched or tapped, it will display full screen and close controls to allow user to go back to full screen mode or close the activity as shown in the below screen.

You can declare the activity as singleTask by setting android:launchMode attribute in AndroidManifest file to reuse the same activity in full-screen mode with new content that user selects. In our example, when video activity is in picture-in-picture mode, user can select new video file and app will play the selected video using same activity because its launchMode is set to singleTask.

Picture-in-Picture Mode Change Callback Method

System calls activity’s onPictureInPictureModeChanged callback method when activity changes to and from picture-in-picture mode. This callback methods gives an opportunity to remove UI components not required when activity is in pip mode and add them back when it is in full-screen mode.

PIP Mode when Home or Recents Buttons Pressed

You can display your video activity in picture-in-picture mode when user presses home or recents button. When user presses home or recents button, current activity goes to background. In the activity life cycle, onUserLeaveHint callback method will be called when an activity is about to go to background due to user actions.

Читайте также:  Final fantasy vii для android

So, onUserLeaveHint callback method can be used to show the activity in PIP mode when user presses home or recents button as shown below. You can check whether the activity is already in PIP mode using isInPictureInPictureMode method.

Источник

Making magic moments with picture in picture

PIP, PIP, Hooray

Picture in Picture (PIP) is an interesting feature that gives the user a magical experience. Pip is a special case of the multi-window UI. Video playback and camera activities can often be enhanced by using PIP. For example, while watching YouTube you can select another video to add to your playlist while continuing to watch the current video because the running video goes into PIP mode. This is a magical moment that lets you comfortably do two things at once.

Another great use of PIP is checking your calendar while you are on a video chat. The video can shrink and move out of the way allowing you to check your appointments. You can stay engaged in the conversation while completing another task.

Using PIP in your app

Starting with Android 8.0 (API level 26), you can easily put your activity into PIP mode.

Your activity must declare that it supports PIP. In your manifest you should set the supportsPictureInPicture flag to true .

Entering PIP on purpose

There are several appropriate times to enter PIP mode. The simplest way is with a button or menu item. Material design provides standard PIP icons; however a menu option might make more sense for your app.

The icon should indicate what happens when entering PIP. For example, if your PIP window shows in the top right of the screen, use an icon to give the user a subtle hint of what to expect.

PIP as an alternative to switching apps

It is often useful to enter PIP instead of leaving an app, for example when the user presses the home or back button.

PIP might be a better experience than closing your app.

When the user selects back, it may be useful to enter PIP mode rather than closing a running video. For instance, the user might be browsing for more content to view, and could continue to watch the original program in PIP mode. If you do enter PIP mode in this way, be sure to provide an option to dismiss the PIP window.

If the user selects home, recent apps, or opens a notification while handling a video call or watching a video, it might make more sense to enter PIP rather than leave the app.

The Android Activity lifecycle has a callback hook that you can use to detect when the user is leaving the app. You can override onUserLeaveHint(), as explained below, and enter PIP mode instead of leaving.

Diving Deeper

When you are in PIP mode, you should hide everything except the most important thing. In most cases, that will be the video or the camera.

Before entering PIP, you should prepare by performing these tasks:

  1. Hide any controls or overlays on the view. For example, hide video playback controls or a camera options menu.
  2. Create a PictureInPictureParams.Builder
  3. Set the aspect ratio based on your view. For example, the Google Maps navigation has a vertical PIP window while YouTube videos appear in a horizontal window.
  4. Optionally add custom actions. For example, provide rewind/fast forward for video playback or a mute action for video calls.
  5. Optionally set a Rect bounds to smooth the transition for the activity into PIP.

Here is an example of entering PIP mode in response to a button:

Here is an example of onUserLeaveHint() to catch the app switching and enter PIP as a side effect, with no user action required.

You should create a PictureInPictureParams to pass to enterPictureInPictureMode() . There is an overloaded method with no parameters that is deprecated. Android Studio can help make sure that you are not using the deprecated API.

Switching in and out of Picture in Picture mode

Entering PIP mode is pretty easy but what if the user restores your window to full-screen? You should restore your activity to how it was before entering PIP. For example, showing the playback controls that you hid. Activity has a callback, onPictureInPictureModeChanged(), that you can override that listens for such events. There is also a callback for Fragments.

Читайте также:  Android layout weight что такое

If the user restores the window to fullscreen, isInPictureInPictureMode will be false. You want to restore your view to before you entered PIP mode. For example, show the video playback controls or restore the camera’s option menu overlay.

Note that you get a reference to the new configuration, like you do when the configuration itself changes.

Adding custom actions

Even though you should simplify the UI when in PIP mode, you can still allow user interaction with remote actions. The PictureInPictureParams.Builder has setActions() which takes a list of RemoteActions. If there are more than getMaxNumPictureInPictureActions() actions, the input list will be truncated to that number.

You can add custom simplistic actions that preserve some of your full-screen features, such as a play/pause toggle. The sample app, defines two custom actions; a play/pause toggle and request info.

If you are using MediaSession for video playback, the framework automatically recognizes the session and adds the actions to play/pause, skip next, and skip previous. The actions are handled by the corresponding methods in MediaSession.Callback.

The actions are automatically enabled and disabled depending on the MediaSession state. In the picture below, the MediaSession state is set to PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT

If you do not need any or all of the actions supplied by MediaSession, call setActions() to specify only the actions you want.

In Summary

Deciding when to enter PIP is the hardest part. PIP can make your app feel magical by deducing user intention or it can make your app feel clunky and annoying. Once you understand your the user’s intent, then the code will fall into place.

The most common flows to enter PIP mode will be as follows:

  1. Trigger from a button
  • onClicked(View) , onOptionsItemSelected(MenuItem) , etc.

2. Trigger from intentionally leaving your app

3. Trigger from discovery

Continue Learning

Check out the following articles and training documents to continue learning about PIP.

To play with PIP, download the sample.

To dive deeper into PIP, read my second article about Navigation with PIP.

Источник

How to implement Picture in Picture (PIP) in Android?

In this article, it is explained how to implement a Picture in Picture (PIP) in an Android application.
We have seen in many apps such as Google Maps while using navigation that when we close the app, there is a floating screen that appears at the bottom right of the screen as shown in the image below. This screen is known as PIP(Picture in Picture) mode.

What is PIP(Picture in Picture) mode?
PIP is a special type of multi-window mode mainly used for activities that need to be active on screen but should not take up the whole screen space like watching videos, video calls, navigation, etc. It lets the user watch a video in a small window pinned to a corner of the screen (by default bottom right) while navigating between apps or browsing content on the main screen. Android 8.0 (API level 26) and above allows activities to launch in PIP mode.
The PIP window appears in the top-most layer of the screen. You can drag the PIP window to another location using some special toggles. When you tap on the window two special controls appear:

  • a full-screen toggle (in the centre of the window) and
  • a close button (an “X” in the upper right corner).

Below is the implementation of the PIP mode.

Источник

Волшебные моменты с Picture in Picture

Разработчик Бенджамин Бакстер рассказал о том, как вы можете применить режим Picture in Picture в своем приложении.

Picture in Picture (PIP) – это интересная функция, которая позволяет пользователю получить волшебный опыт. PIP – это особый случай мультиоконного UI. Проигрывание видео или действия с камерой могут быть значительно улучшены при использовании PIP. Например, во время просмотра YouTube вы можете выбрать другое видео и добавить его в свой плейлист, продолжая смотреть текущее видео в режиме PIP. Это тот самый волшебный момент, который позволяет вам комфортно делать две вещи одновременно.

Другой отличный пример использования PIP – проверка вашего календаря одновременно с видеочатом. Видео может сворачиваться, позволяя вам проверить свои запланированные встречи. При этом вы можете оставаться в разговоре, делая другую задачу.

Использование PIP в вашем приложении

Начиная с Android 8.0 (API Level 26), вы можете легко переводить активности в режим PIP. В активности вы должны заявить поддержку PIP. В манифесте вы должны установить supportsPictureInPicture на true.

Читайте также:  Живые обои розы для андроид

Целенаправленный переход к PIP

Существует несколько приемлемых способов перейти в режим PIP. Самый простой способ – при помощи кнопки или пункта в меню. Материальный дизайн предоставляет стандартные PIP-иконки, но, возможно, опция меню лучше подойдет к вашему приложению.

Иконка должна показывать, что происходит при переходе в PIP. Например, если ваше PIP-окно показано в правом верхнем углу экрана, используйте иконку, чтобы подсказать пользователю, чего ожидать.

PIP как альтернатива переходу между приложениями

Зачастую полезно переходить в PIP вместо выхода из приложения, например, когда пользователь нажимает кнопку Home или “Назад”.

Если пользователь переходит назад, лучше будет перейти в режим PIP, чем закрывать текущее видео. Например, пользователь может искать другой контент для просмотра. Если вы переходите в PIP-режим таким образом, убедитесь, что предоставляете возможность закрыть PIP-окно. Если пользователь выбирает домашний экран, недавние приложения или открывает оповещение во время видеозвонка или просмотра видео, режим PIP также будет более логичен, чем закрытие приложения.

Жизненный цикл Android Activity имеет хук обратного вызова, который можно использовать для обнаружения, когда пользователь покидает приложение. Вы можете переопределить onUserLeaveHint (), как описано ниже, и перейти в режим PIP вместо того, чтобы закрывать приложение.

Погружаясь глубже

Когда вы переходите в PIP-режим, вам следует спрятать все, кроме самого важного. Во многих случаях, это будет видео или изображение с камеры.

Перед переходом в PIP вы должны подготовиться, выполнив следующие задачи:

  1. Спрячьте любые элементы управления или overlay в view. Например, скройте элементы управления видео или меню с опциями камеры.
  2. Создайте PictureInPictureParams.Builder
  3. Установите соотношение сторон. Например, навигация карт Google имеет вертикальное PIP-окно, а видео с YouTube появляются в горизонтальном окне.
  4. Вы можете добавить кастомные действия. Например, функцию перемотки видео или беззвучный режим для видеозвонка.
  5. Также можно установить границы Rect, чтобы сгладить переход активности в PIP.

Вот пример перехода в режим PIP в ответ на нажатие кнопки:

Вот пример использования onUserLeaveHint() для того, чтобы уловить переключение между приложениями и перейти в PIP, не требуя действия пользователя.

Вам следует создать PictureInPictureParams для перехода к enterPictureInPictureMode (). Существует overloaded метод без устаревших параметров. Android Studio поможет вам убедиться, что вы не используете устаревший API.

Переход в режим PIP и выход из него

Переход в режим PIP довольно прост, но что если пользователь снова разворачивает окно на полный экран? Вам нужно вернуть свою активность в прежний режим. Например, показать элементы управления, которые вы спрятали. У Activity есть обратный вызов, onPictureInPictureModeChanged(), который будет искать подобные события. Существует обратный вызов для Fragments.

Если пользователь возвращает окно на полный экран isInPictureInPictureMode будет false. Вам нужно будет восстановить свой вид до состояния, предшествующего режиму PIP. Например, показать элементы управления воспроизведением видео или восстановите меню опций камеры.

Обратите внимание, что вы получаете ссылку на новую конфигурацию, как и при изменении самой конфигурации.

Добавление кастомных действий

Хотя вам следует упрощать интерфейс в режиме PIP, вы все ещё можете разрешать пользователю взаимодействовать с приложением при помощи действий. PictureInPictureParams.Builder имеет setActions (), который принимает список RemoteActions. Если их больше, чем getMaxNumPictureInPictureActions (), список ввода будет усечен до этого числа.

Вы можете добавить упрощенные действия, которые поддерживают некоторые ваши полноэкранные функции, такие как переключение воспроизведения или пауза. Этот пример приложения определяет два пользовательских действия: переключатель воспроизведения и паузы и запрос информации.

Кастомные действия в PIP

Если вы используете MediaSession для воспроизведения видео, система автоматически распознает сеанс и добавляет действия для воспроизведения и паузы, перемотки на следующее и предыдущее видео. Действия обрабатываются соответствующими методами в MediaSession.Callback.

Стандартные действия в PIP

Действия автоматически включаются и отключаются в зависимости от состояния MediaSession. На приведенном ниже изображении состояние MediaSession установлено на значение PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT.

Обновленные действия, основанные на состоянии MediaSession

Если вам не нужны какие-либо или все действия, предоставленные MediaSession, вызовите setActions (), чтобы указать только те действия, которые вам нужны.

Самое сложное – решить, когда необходим режим PIP. PIP может быть отличным опытом, следующим за действиями пользователя, или он может сделать ваше приложение ужасно раздражающим. Как только вы поймете намерения своего пользователя, все встанет на свои места.

Самыми распространенными переходами в режим PIP будут:

  1. При нажатии на кнопку: onClicked(View), onOptionsItemSelected(MenuItem)
  2. При целенаправленном выходе из вашего приложения: onUserLeaveHint()
  3. При обнаружении: onBackPressed()

Продолжайте учиться

Чтобы узнать больше о PIP, вы можете посмотреть эти статьи и обучающие документы:

Источник

Оцените статью