android / media-samples

Multiple samples showing the best practices in media APIs on Android (audio, video, etc.).
Apache License 2.0
1.27k stars 740 forks source link

How to use "setCloseAction"? #97

Open TechToArt opened 8 months ago

TechToArt commented 8 months ago

I tried to use "PictureInPictureParams.Builder.setCloseAction(RemoteAction)" to finish Activity, but is not work. what should i do?

    private const val ACTION_STOPWATCH_CONTROL = "stopwatch_control"
    private const val EXTRA_CONTROL_TYPE = "control_type"
    private const val CONTROL_TYPE_CLOSE = 3
    private const val REQUEST_CLOSE = 5
    private val broadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent == null || intent.action != ACTION_STOPWATCH_CONTROL) {
                return
            }
            when (intent.getIntExtra(EXTRA_CONTROL_TYPE, 0)) {
                CONTROL_TYPE_CLOSE -> this@MainActivity.finish()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        registerReceiver(broadcastReceiver, IntentFilter(ACTION_STOPWATCH_CONTROL))
    }

    private fun updatePictureInPictureParams(started: Boolean): PictureInPictureParams {
        val params = PictureInPictureParams.Builder()
            .setAspectRatio(Rational(16, 9))
            .setSeamlessResizeEnabled(false)
            .setAutoEnterEnabled(true)
            .setCloseAction(
                createRemoteAction(
                    R.drawable.close,
                    R.string.close,
                    REQUEST_CLOSE,
                    CONTROL_TYPE_CLOSE
                )
            )
            .build()
        setPictureInPictureParams(params)
        return params
    }
dinhthaidaica commented 6 months ago

Ran into the same problem today. When I tried to set custom action to closeAction, nothing happened.

Even the document of setCloseAction is not so clear when saying :

custom action must close the activity quickly using {@link Activity#finish()}

        /**
         * Sets a close action that should be invoked before the default close PiP action. The
         * custom action must close the activity quickly using {@link Activity#finish()}.
         * Otherwise, the system will forcibly close the PiP as if no custom close action was
         * provided.
         *
         * If the action matches one set via {@link PictureInPictureParams.Builder#setActions(List)}
         * it may be shown in place of that custom action in the menu.
         *
         * @param action to replace the system close action
         * @return this builder instance.
         * @see RemoteAction
         */

At then end, I ended up with a solution to implement my logic in onStop function of Activity.

    override fun onStop() {
        if (isInPictureInPictureMode) {
                // logic goes here.
        }
        super.onStop()
    }