เกี่ยวกับฟีเจอร์ภาพซ้อนภาพ (PIP)

การแสดงภาพซ้อนภาพ (PiP) เป็นโหมดหลายหน้าต่างประเภทพิเศษที่ส่วนใหญ่ใช้สำหรับการเล่นวิดีโอ โดยจะช่วยให้ผู้ใช้ดูวิดีโอในหน้าต่างขนาดเล็กที่ปักหมุดไว้ที่มุมของหน้าจอในระหว่างที่ไปยังแอปต่างๆ หรือเลือกดูเนื้อหาบนหน้าจอหลัก

PiP ใช้ประโยชน์จาก API ของหลายหน้าต่างที่พร้อมใช้งานใน Android 7.0 เพื่อแสดงหน้าต่างวิดีโอซ้อนทับที่ปักหมุดไว้ หากต้องการเพิ่ม PiP ในแอป คุณต้องลงทะเบียนกิจกรรม เปลี่ยนกิจกรรมเป็นโหมด PiP ตามความจำเป็น และตรวจสอบว่าไม่ได้แสดงองค์ประกอบของ UI และวิดีโอจะเล่นต่อไปเมื่อกิจกรรมอยู่ในโหมด PiP

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.

จัดการ UI ในโหมด PiP

เมื่อเข้าสู่โหมด PiP UI ทั้งหมดของแอปจะเข้าสู่หน้าต่าง PiP เว้นแต่คุณจะระบุลักษณะที่ UI ควรแสดงในโหมด PiP และเมื่อออกจากโหมด PiP

ก่อนอื่น คุณต้องทราบว่าแอปอยู่ในโหมด 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() เพื่อสลับองค์ประกอบ UI ที่จะแสดงเมื่อแอปเข้าสู่โหมด PiP ได้แล้ว

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()
}