添加依赖
rootDir/build.gradle
1 2 3 4 5 6
| allprojects { repositories { ... google { url 'https://maven.aliyun.com/repository/google' } } }
|
module/build.gradle
1 2 3 4
| dependencies { api 'com.google.mlkit:barcode-scanning:17.0.0' }
|
扫码工具类
BarcodeScannerProcessor.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
| import android.graphics.Bitmap import android.util.Log import com.google.mlkit.vision.barcode.Barcode import com.google.mlkit.vision.barcode.BarcodeScanner import com.google.mlkit.vision.barcode.BarcodeScanning import com.google.mlkit.vision.common.InputImage import java.util.concurrent.Executors
class BarcodeScannerProcessor {
private val barcodeScanner: BarcodeScanner = BarcodeScanning.getClient() private val executor = Executors.newSingleThreadExecutor()
fun stop() { barcodeScanner.close() executor.shutdown() }
fun processBitmap(bitmap: Bitmap, onNext: (barcode: Barcode?) -> Unit) { val image = InputImage.fromBitmap(bitmap, 0) barcodeScanner.process(image).continueWith(executor) { val barcodes = it.result if (barcodes.isEmpty()) { Log.v("BarcodeScanner", "No barcode has been detected") } onNext(barcodes.firstOrNull()) } } }
|
使用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| private final BarcodeScannerProcessor processor = new BarcodeScannerProcessor();
public void decodeByMlkit(Bitmap bitmap) { processor.processBitmap(bitmap, (barcode) -> { if (barcode != null) { } return null; }); }
public void onScanDone() { processor.stop(); }
|
注意事项
TODO 待补充