How to Start an Activity and Call a Method from Another Class on Click in a Jetpack Glance Widget?

151 Views Asked by At

I'm working on an Android app where I'm using Jetpack Glance for creating a widget. I need to implement functionality where a click on the widget's button starts an activity and also calls a method from another class. However, I'm unsure how to correctly implement this, as my current approach only allows for a single action.

Here's what I have so far:

// Example of my current Glance widget implementation
@Composable
fun MyGlanceWidget() {
    // ...
    Box(
        modifier = GlanceModifier.clickable(
            actionStartActivity(Intent(context, MyActivity::class.java))
        )
    )
    // ...
}

// The method I want to call from another class
class AnalyticsTracker {
    fun trackWidgetClick() {
        // Tracking logic
    }
}

In this setup, clicking the box starts MyActivity, but I also need to execute trackWidgetClick() from AnalyticsTracker class. I'm unsure how to modify my Glance widget to accommodate both actions on a single click.

Could someone provide guidance or an example of how to achieve this in a Jetpack Glance widget?

1

There are 1 best solutions below

4
Jan Bína On

You can set an action and maybe even some extras on the Intent:

actionStartActivity(
    Intent(context, MyActivity::class.java)
        .setAction("startedFromWidget")
        .putExtra("param1", false)
)

then you get those in your activity and do whatever you need:

class MyActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        checkIntent(intent)
    }

    override fun onNewIntent(intent: Intent) {
        ...
        checkIntent(intent)
    }

    private fun checkIntent(intent: Intent?) {
        if (intent?.action == "startedFromWidget") {
            val param = intent.getBooleanExtra("param1", false)
            trackWidgetClick(param)
        }
        // set activity.intent to null so you don't check it again
        // when activity is recreated
        this.intent = null
    }
}