Asegúrate de tener las dependencias necesarias en tu archivo build.gradle
1 2 |
implementation 'com.google.zxing:core:3.4.1' implementation 'com.journeyapps:zxing-android-embedded:4.2.0' |
MainActivity.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package com.example.myapplication import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.zxing.integration.android.IntentIntegrator import com.google.zxing.integration.android.IntentResult class MainActivity : AppCompatActivity() { private val REQUEST_CODE = 123 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(Manifest.permission.CAMERA), REQUEST_CODE) } else { startScanner() } } private fun startScanner() { val integrator = IntentIntegrator(this) integrator.setPrompt("Escanea un código QR") integrator.setBeepEnabled(true) integrator.setOrientationLocked(false) integrator.initiateScan() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startScanner() } else { Toast.makeText(this, "Se requiere permiso para la cámara", Toast.LENGTH_SHORT).show() } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val result: IntentResult? = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) if (result != null) { if (result.contents == null) { Toast.makeText(this, "Cancelado", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Escaneado: ${result.contents}", Toast.LENGTH_LONG).show() } } else { super.onActivityResult(requestCode, resultCode, data) } } } |