Android: Introduction to Picture In Picture mode, that amazing overshadowed feature.

Image for post
Image for post
(Source: https://9to5google.com/wp-content/uploads/sites/4/2017/05/android-o-dev-preview-picture-in-picture.jpg?quality=82&strip=all)
Image for post
Image for post
Image for post
Image for post
source: https://media1.tenor.com/images/e2771e999a5dbe25e6337c055e05a198/tenor.gif?itemid=8803801

First Step:

// Lines to Add
android:supportsPictureInPicture="true"
android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"
// Old Code
<activity
android:name=".MainActivity"
android:screenOrientation="landscape">
/* */
</activity>
// New Code
<activity
android:name=".MainActivity"
android:supportsPictureInPicture="true"
android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"
android:screenOrientation="landscape">
/* */
</activity

Second Step:

@TargetApi(Build.VERSION_CODES.O)
private fun updatePic2PicParams() = PictureInPictureParams.Builder()
.setActions(emptyList())
.build()

Third Step:

// MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Include this line
initObservers()
}
// Create this private method
private fun initObservers() {
if (isPlaying && hasPipSupport()) {
setPictureInPictureParams(updatePic2PicParams())
}
}
// BooleanExt.kt:
// Create this extensions functions to check if the device is SDK Oreo or above and if has Picture 2 picture support
fun Context.isOreoOrAbove(): Boolean {
return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O
}

fun Context.hasPipSupport(): Boolean {
return this.isOreoOrAbove() && packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)
}

Fourth Step:

override fun onUserLeaveHint() {
super.onUserLeaveHint()
if (hasPipSupport() && isPlaying) {
enterPictureInPictureMode(updatePic2PicParams())
}
}

Fifth Step:

override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration?) {
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)

// add this line to your PlayerView
binding.playerView.useController = !isInPictureInPictureMode
}

Android Lead, Kotlin developer & Blogger

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store