안드로이드/개발중 알게된점

안드로이드 PIP 모드 커스텀 버튼 추가

최효식 2024. 11. 21. 13:40

안드로이드 PIP 모드에서 커스텀 버튼을 추가하는 방법

 

1. PendingIntent.getActivity 를 이용해 onNewIntent 에서 action 에 대해 기능 정의 방법

 

예제 코드

private fun enterPipModeWithActions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val aspectRatio = Rational(16, 9)

            // PIP 모드에서 사용할 액션 버튼 정의
            val intent = Intent(this, PipActivity::class.java).apply {
                action = "ACTION_DO_SOMETHING"
            }
            val pendingIntent = PendingIntent.getActivity(
                this, 0, intent, PendingIntent.FLAG_IMMUTABLE
            )

            val icon = Icon.createWithResource(this, R.drawable.ic_action_icon)
            val action = RemoteAction(icon, "Action Title", "Action Description", pendingIntent)

            // Picture-in-Picture 모드 설정 및 액션 추가
            val pipParams = PictureInPictureParams.Builder()
                .setAspectRatio(aspectRatio)
                .setActions(listOf(action)) // 액션 버튼 추가
                .build()

            enterPictureInPictureMode(pipParams)
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        intent?.let {
            if (it.action == "ACTION_DO_SOMETHING") {
                // 버튼을 눌렀을 때 수행할 작업
                doSomething()
            }
        }
    }

    private fun doSomething() {
        // 버튼을 눌렀을 때 실제로 수행할 동작 정의
        Toast.makeText(this, "PIP 버튼이 눌렸습니다!", Toast.LENGTH_SHORT).show()
    }

 

하지만 해당 로직으로 수행시 PIP 모드에서 자동으로 expand 모드로 변환 되는 이슈가 있었습니다.

 

 

2. BroadcastReceiver 사용 하는 방법

 

예제 코드

 

  • BR 정의
 private val pipActionReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == PIP_ACTION_KEY) {
                if(exoPlayer.isPlaying) exoPlayer.pause()
                else exoPlayer.play()
            }
        }
    }

 

  • BR 등록 및 action 설정
 private fun enterPipMode() {
        registerReceiver(pipActionReceiver, IntentFilter(PIP_ACTION_KEY))
        
        val broadCastIntent = Intent(PIP_ACTION_KEY)

        val pendingIntent = PendingIntent.getBroadcast(this, 0, broadCastIntent, PendingIntent.FLAG_IMMUTABLE)

        val icon = Icon.createWithResource(this, R.drawable.ico_play)
        val action = RemoteAction(icon, "title", "description", pendingIntent)

        // PIP 모드 파라미터 생성
        val aspectRatio = Rational(9, 16) // 가로 세로 비율 설정
        val pipParams = PictureInPictureParams.Builder()
            .setActions(listOf(action))
            .setAspectRatio(aspectRatio)
            .build()

        // PIP 모드로 전환
        enterPictureInPictureMode(pipParams)
    }

 

  • Activity 라이프싸이클 종료시 unregister 등록
override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(pipActionReceiver)
        onBackPressedCallback.remove()
    }

 

 

해당 방법으로 수행시 Activity 를 다시 재구성 시키지 않고 제어를 할 수 있어서 확대가 되는 이슈가 사라졌습니다.