Created
July 4, 2020 00:47
-
-
Save Younes-Charfaoui/420e29981394b4d1820a13574b25cc4c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : AppCompatActivity() { | |
private lateinit var fotoapparat: Fotoapparat | |
private lateinit var barcodeScanner: BarcodeScanner | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
initializeBarcodeScanner() | |
initializeFotoapparat() | |
button.setOnClickListener { | |
if (isCameraPermissionGranted()) | |
takeImage() | |
else requestCameraPermission() | |
} | |
if (!isCameraPermissionGranted()) requestCameraPermission() | |
} | |
private fun takeImage() { | |
fotoapparat.takePicture().toBitmap().whenAvailable { | |
scanImageForBarcode(it!!) | |
} | |
} | |
private fun scanImageForBarcode(it: BitmapPhoto) { | |
val inputImage = InputImage.fromBitmap(it.bitmap, it.rotationDegrees) | |
val task = barcodeScanner.process(inputImage) | |
task.addOnSuccessListener { barCodesList -> | |
for (barcodeObject in barCodesList) { | |
val barcodeValue = barcodeObject.rawValue | |
textView.text = barcodeValue | |
Log.d("Barcode", "The code %s".format(barcodeValue)) | |
} | |
} | |
task.addOnFailureListener { | |
Log.d("ERROR", "An Exception occurred", it) | |
} | |
} | |
private fun initializeFotoapparat() { | |
fotoapparat = Fotoapparat.with(this) | |
.into(cameraView) | |
.previewScaleType(ScaleType.CenterCrop) | |
.build() | |
} | |
private fun initializeBarcodeScanner() { | |
val options = BarcodeScannerOptions.Builder() | |
.setBarcodeFormats( | |
Barcode.FORMAT_EAN_13, | |
Barcode.FORMAT_QR_CODE | |
) | |
.build() | |
barcodeScanner = BarcodeScanning.getClient(options) | |
} | |
override fun onStart() { | |
super.onStart() | |
fotoapparat.start() | |
} | |
override fun onStop() { | |
super.onStop() | |
fotoapparat.stop() | |
} | |
private fun isCameraPermissionGranted(): Boolean { | |
return (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) | |
== PackageManager.PERMISSION_GRANTED) | |
} | |
private fun requestCameraPermission() { | |
ActivityCompat.requestPermissions( | |
this, | |
arrayOf(Manifest.permission.CAMERA), | |
1144 | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment