Android block activity based on condition from base activity? -


for example.. activity a attempts start activity b, activity b requires state exist before allowed shown (i.e. user must first create entity in activity, or must have active subscription, etc).

i have baseactivity activities extend, , i'd show alertdialog describing restriction , finish activity in baseactivity#oncreate method, error window leaks because activity context no longer exists (because finish() called), , passing application context throws different error. can't put finish() call in ondismiss because activity still load behind modal since android modals not block. attempted override startactivity , disallow activity shown altogether, seems worse putting conditionals everywhere because there lots of ways start activities, , handful of startactivityx methods have overridden achieve way.

is there approach this? can't seem find documentation on it, there kind of application level global hooks can implement run sort of checks , perform actions?

i ended tracking "active" activity in application class via activitylifecyclecallbacks, setting current activity in onactivityresumed method , performing checks needed in baseactivity#oncreate, calling finish() when invalid , showing alertdialog using set activity application

hope helps someone, here's code (kotlin):

// yourapplication.kt class yourapplication : application() {     override fun oncreate() {         ...         registeractivitylifecyclecallbacks(object: activitylifecyclecallbacks {             ...             override fun onactivityresumed(activity: activity?) {                currentactivity = activity             }         })     }      companion object {         var currentactivity: activity? = null             private set     } }  // baseactivity.kt open class baseactivity : appcompatactivity() {     override fun oncreate(savedinstancestate: bundle?) {         super.oncreate(savedinstancestate)          if (requiresactivesubscription() && !subscriptionservice.hasactivesubscription()) {             finish()             // show alert here using yourapplication.currentactivity context         }     } }