How to call composable Alertdialog from non composable function

Viewed 53

I wanted to check whether the phone is rooted or not. For that I wanted to check as soon as the app is clicked.

@HiltAndroidApp class ShoppingApp : Application(), Configuration.Provider {

override fun onCreate() {
    super.onCreate() }

This is the first class which is called as soon as the app is launched. Inside this onCreate, I wanted to add check if device is rooted. If its rooted I want to show AlertDialog else navigate to next screen.

When adding composable AlertDialog, its throwing error @Composable should be called from the context of Composable.

In this case, how should I code.

1 Answers

You will need to create a State object in your Application class and make your composable observe that object from an Activity or Fragment.

class ShoppingApp : Application() {
    val isRootedState = mutableStateOf(false)

    override fun onCreate() {
        super.onCreate()
        if (isRootedDevice()) {
            isRootedState.value = true
        }
    }
}

class ShoppingActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val isRooted = remember { (application as ShoppingApp).isRootedState }
            if (isRooted.value) {
                AlertDialog(
                   // AlertDialog params
                )
            }
        }
    }
    //...
}
Related