Reputation: 6948
I have tried to require permission in activity and then get the function of compose, but when i first time get the permission, it can not directly get the content of compose.
class MainActivity : AppCompatActivity() {
val viewModel by viewModels<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (allPermissionsGranted()) {
// the setContent code not executed after getting the permission first time
setContent {
MyTheme {
Main(
viewModel = viewModel,
backDispatcher = onBackPressedDispatcher
)
}
}
} else {
ActivityCompat.requestPermissions(
this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
}
}
private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
ContextCompat.checkSelfPermission(
baseContext, it) == PackageManager.PERMISSION_GRANTED
}
companion object {
private const val REQUEST_CODE_PERMISSIONS = 10
private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)
}
}
Upvotes: 1
Views: 629
Reputation: 1007484
Activities do not get recreated after a permission grant. So, in your case, nothing will happen in the app after the permission grant. This is unrelated to Compose; you would get the same behavior with setContentView()
where you have setContent {}
.
Move your setContent {}
logic into a different function. Call it from onCreate()
where you have it now. And, override onRequestPermissionsResult()
, and call that function from there if you were granted permission.
A more Compose-y way would be to remember
whether you have permission and update that state from onRequestPermissionsResult()
if you were granted permission. Do all that from inside setContent()
, and Compose will recompose on the state change.
Upvotes: 1
Reputation: 892
Hi you can achieve it by using fragments. You should check permission, request and handle response
If permission granted -> navigate to the fragment
If permission not granted wait until user grants and upon response -> navigate to the fragment
Upvotes: 0