Home > Blockchain >  Jetpack Compose update ad banner in Android View
Jetpack Compose update ad banner in Android View

Time:10-27

In Jetpack Compose I'm using AndroidView to display an ad banner from a company called Smart.IO.

At the moment the banner shows when first initialised, but then fails to recompose when user comes back to the screen it's displayed on.

I'm aware of using the update function inside compose view, but I can't find any parameters I could use to essentially update on Banner to trigger the recomposition.

AndroidView(
    modifier = Modifier
        .fillMaxWidth(),
    factory = { context ->
        Banner(context as Activity?)
    },
    update = {
        
    }
)

CodePudding user response:

This could be a library error. You can check if this view behaves normally in normal Android XML.

Or maybe you need to use some API from this library, personally I haven't found any decent documentation or Android SDK source code.


Anyway, here is how you can make your view update.

You can keep track of life-cycle events, as shown in this answer, and only display your view during ON_RESUME. This will take it off the screen when it is paused, and make it create a new view when it resumes:

val lifeCycleState by LocalLifecycleOwner.current.lifecycle.observeAsSate()
if (lifeCycleState == Lifecycle.Event.ON_RESUME) {
    AndroidView(
        modifier = Modifier
            .fillMaxWidth(),
        factory = { context ->
            Banner(context as Activity?)
        },
        update = {

        }
    )
}

Lifecycle.observeAsSate:

@Composable
fun Lifecycle.observeAsSate(): State<Lifecycle.Event> {
    val state = remember { mutableStateOf(Lifecycle.Event.ON_ANY) }
    DisposableEffect(this) {
        val observer = LifecycleEventObserver { _, event ->
            state.value = event
        }
        this@observeAsSate.addObserver(observer)
        onDispose {
            this@observeAsSate.removeObserver(observer)
        }
    }
    return state
}
  • Related