ピクチャー イン ピクチャー(PIP)について

ピクチャー イン ピクチャー(PIP)は特別なタイプのマルチウィンドウ モードで、主に動画の再生に使用されます。ユーザーは、アプリ間を移動したり、メイン画面でコンテンツをブラウジングしたりしながら、画面の隅に固定された小さなウィンドウで動画を見続けることができます。

PIP は、Android 7.0 で使用可能になったマルチウィンドウ API を利用して、固定された動画オーバーレイ ウィンドウを提供します。アプリで PIP を使用するには、アクティビティを登録し、必要に応じてアクティビティを PIP モードに切り替える必要があります。そして、アクティビティが PIP モードのときには、UI 要素を非表示にして動画の再生を継続するようにします。

Implement PiP with Jetpack

Use the Jetpack Picture-in-Picture library to implement picture-in-picture experience as it streamlines integration and reduces common in-app issues. Refer to our platform sample app to see an example of its usage. However, if you prefer to implement PiP using the platform APIs, refer to the following documentation.

PIP モードで UI を処理する

PIP モードに入ると、アプリの UI 全体が PIP ウィンドウに入ります。ただし、PIP モードのときとそうでないときの UI の外観を指定している場合は除きます。

まず、アプリが PiP モードかどうかを把握する必要があります。これには OnPictureInPictureModeChangedProvider を使用します。次のコードは、アプリが PiP モードかどうかを判断します。

@Composable
fun rememberIsInPipMode(): Boolean {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val activity = LocalContext.current.findActivity()
        var pipMode by remember { mutableStateOf(activity.isInPictureInPictureMode) }
        DisposableEffect(activity) {
            val observer = Consumer<PictureInPictureModeChangedInfo> { info ->
                pipMode = info.isInPictureInPictureMode
            }
            activity.addOnPictureInPictureModeChangedListener(
                observer
            )
            onDispose { activity.removeOnPictureInPictureModeChangedListener(observer) }
        }
        return pipMode
    } else {
        return false
    }
}

これで、rememberIsInPipMode() を使用して、アプリが PIP モードになったときに表示する UI 要素を切り替えることができます。

val inPipMode = rememberIsInPipMode()

Column(modifier = modifier) {
    // This text will only show up when the app is not in PiP mode
    if (!inPipMode) {
        Text(
            text = "Picture in Picture",
        )
    }
    VideoPlayer()
}