相机现在已弃用,建议使用 camera2,有人可以指导我了解如何使用 camera2 和检测条形码
问问题
3359 次
2 回答
1
这里有2种可能
- 从头开始创建条形码扫描仪(这很复杂)
- 使用现有的库(这个答案涵盖)
有一些完善的库可供您使用
- ZXing跨平台库,用 C++ 编写
- ZXing Embedded是一个 Android 端口
- 更易于使用的Google Mobile Vision API
此外,您可以参考此问题以更深入地了解如何将 Camera2 与 Mobile Vision 结合使用。
于 2018-09-05T11:46:04.487 回答
0
是的,当然!你必须使用BarcodeDetector
. 像这样的东西:
open class BarcodeFragmentInternal : Fragment(), ActivityCompat.OnRequestPermissionsResultCallback {
protected var mSurfaceView: SurfaceView? = null
protected var mScanListener: Listener? = null
private var mCameraSource: CameraSource? = null
override fun onStart() {
super.onStart()
// Initialize Barcode Detector
// Used to recognize barcodes like {@link Barcode.DATA_MATRIX} and {@link Barcode.QR_CODE}
val mBarcodeDetector = BarcodeDetector.Builder(activity)
.setBarcodeFormats(Barcode.DATA_MATRIX or Barcode.QR_CODE)
.build()
if (!mBarcodeDetector.isOperational) {
sendError("NO_BARCODE_DETECTOR")
}
mBarcodeDetector.setProcessor(object : Detector.Processor<Barcode> {
override fun release() {
}
override fun receiveDetections(detections: Detector.Detections<Barcode>?) {
if (detections != null && mScanListener != null) {
val detectedItems = detections.detectedItems
if (detectedItems != null) {
var i = 0
val size = detectedItems.size()
while (i < size) {
val barcode = detectedItems.valueAt(i)
mScanListener!!.onQRCodeAvailable(barcode.rawValue)
i++
}
}
}
}
})
mCameraSource = CameraSource.Builder(context!!, mBarcodeDetector).build()
mSurfaceView!!.holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(surfaceHolder: SurfaceHolder) {
try {
if (ContextCompat.checkSelfPermission(activity!!, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestCameraPermission()
return
}
mCameraSource!!.start(mSurfaceView!!.holder)
} catch (e: Exception) {
sendError("NO_CAMERA_ACCESS")
}
}
override fun surfaceChanged(surfaceHolder: SurfaceHolder, format: Int, width: Int, height: Int) {
}
override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) {
mCameraSource!!.stop()
}
})
}
private fun requestCameraPermission() {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
ConfirmationDialog().show(childFragmentManager, FRAGMENT_DIALOG)
} else {
requestPermissions(arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA_PERMISSION)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
grantResults: IntArray) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.size != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
sendError("NOT_AUTHORIZED")
view!!.post {
ErrorDialog.newInstance(getString(R.string.request_permission))
.show(childFragmentManager, FRAGMENT_DIALOG)
}
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
}
于 2018-09-05T11:36:29.160 回答