Android CameraX: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 13: Line 13:
=Implement Permission Checking=
=Implement Permission Checking=
This is the simplest way to get going
This is the simplest way to get going
<syntaxhighlight lang="kt">
<syntaxhighlight lang="kotlin">
class MainActivity : ComponentActivity() {
class MainActivity : ComponentActivity() {
     override fun onCreate(savedInstanceState: Bundle?) {
     override fun onCreate(savedInstanceState: Bundle?) {

Revision as of 03:02, 6 March 2025

Introduction

Already had this working for my Food app but this is now broken so watching a tutorial and thought I better take notes

Setup Permissions

Make sure we give permissions in the Manifest

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

Implement Permission Checking

This is the simplest way to get going

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (!hasRequiredPermissions()) {
            requestPermissions(CAMERAX_PERMISSIONS, 0)
        }
        enableEdgeToEdge()
    }

    private fun hasRequiredPermissions(): Boolean {
        return CAMERAX_PERMISSIONS.all {
            ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
        }
    }

    companion object {
        private val CAMERAX_PERMISSIONS = arrayOf(
            android.Manifest.permission.CAMERA,
            android.Manifest.permission.RECORD_AUDIO
        )
    }

    @Composable
    fun Greeting(name: String, modifier: Modifier = Modifier) {
        Text(
            text = "Hello $name!",
            modifier = modifier
        )
    }
}