dependencies {
...
implementation 'com.google.android.gms:play-services-vision:16.2.0'
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="301dp"
android:layout_height="281dp"
android:layout_marginTop="48dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
SurfaceView surfaceView;
TextView textView;
CameraSource cameraSource; //相機
BarcodeDetector barcodeDetector;//Google的Vision套件
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource=new CameraSource.Builder(this,barcodeDetector)
.setRequestedPreviewSize(300,300).build();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback(){
@Override
public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
if(ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED)
return;
try{
cameraSource.start(surfaceHolder);
}catch (IOException e){
e.printStackTrace();
}
}
@Override
public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
});
之後再將關閉相機的程式碼打在 surfaceView 下的 surfaceDestroyed 就可以了
cameraSource.stop();
*可以只打以下代碼之後按 Alt+Enter自動生成 *
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback(){
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>(){
@Override
public void release() {
}
@Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes=detections.getDetectedItems();
if(qrCodes.size()!=0){
textView.post(new Runnable() {
@Override
public void run() {
textView.setText(qrCodes.valueAt(0).displayValue);
}
});
}
}
});
最後即可顯示到你的textview 上了