El escaneo por ventana es una función que utiliza la interfaz de usuario estándar heredada. Para usar la función de escaneo en pantalla completa, compatible con el reconocimiento de varios códigos, actualice su línea base de mPaaS a la versión 10.1.68.33 o posterior.
Uso de la función de escaneo en la interfaz estándar
Escaneo en pantalla completa
Para escanear de forma continua sin salir después de un escaneo correcto, utilice el siguiente código.
ScanRequest scanRequest = new ScanRequest();
MPScan.startMPaasScanFullScreenActivity(this, scanRequest, new MPScanCallbackAdapter() {
@Override
public boolean onScanFinish(Context context, MPScanResult mpScanResult, final MPScanStarter mpScanStarter) {
new android.app.AlertDialog.Builder(context)
.setMessage(mpScanResult != null ? mpScanResult.getText() : "No code detected")
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mpScanStarter.restart();
}
})
.create()
.show();
// Return false to indicate that the callback is not consumed. The callback will be invoked again for the next scan.
return false;
}
});
Sobrescriba otros métodos de MPScanCallbackAdapter para escuchar otros eventos:
MPScan.startMPaasScanFullScreenActivity(this, scanRequest, new MPScanCallbackAdapter() {
@Override
public boolean onScanFinish(final Context context, MPScanResult mpScanResult, final MPScanStarter mpScanStarter) {
return true;
}
@Override
public boolean onScanError(Context context, MPScanError error) {
// Scan error.
return super.onScanError(context, error);
}
@Override
public boolean onScanCancel(Context context) {
// Scan canceled.
return super.onScanCancel(context);
}
});
Antes de iniciar la función de escaneo en pantalla completa, establezca los parámetros de inicio como se muestra en el siguiente código.
ScanRequest scanRequest = new ScanRequest();
// Set the prompt text.
scanRequest.setViewText("Prompt text");
// Set the prompt text for turning on the flashlight.
scanRequest.setOpenTorchText("Turn on flashlight");
// Set the prompt text for turning off the flashlight.
scanRequest.setCloseTorchText("Turn off flashlight");
// Set the scan recognition type.
// This setting is effective only for direct scanning, not for recognizing images from the photo album.
scanRequest.setRecognizeType(
ScanRequest.RecognizeType.QR_CODE, // QR code
ScanRequest.RecognizeType.BAR_CODE, // Barcode
ScanRequest.RecognizeType.DM_CODE, // DM code
ScanRequest.RecognizeType.PDF417_Code // PDF417 code
); // If not set, the first three types are recognized by default.
// Hide the photo album button.
scanRequest.setNotSupportAlbum(true);
// Set the marker image for multi-code scanning.
scanRequest.setMultiMaMarker(R.drawable.green_arrow);
// Set the prompt text for multi-code scanning.
scanRequest.setMultiMaTipText("Tap the green arrow to select a code");
// Set the color of the dot after selecting a single code.
scanRequest.setMaTargetColor("#32CD32");
// Enable AI to recognize small codes and automatically zoom in. This feature is supported only on baseline 10.2.3 and later and requires integrating the Scan AI component.
scanRequest.setEnableAI(true);
// Set the delayed prompt text. This feature is supported only on baseline 10.2.3 and later.
scanRequest.setDelayTipText("Toast will pop up after a delay of x seconds");
// Set the delay time for the prompt in milliseconds. This feature is supported only on baseline 10.2.3 and later.
scanRequest.setDelayTipTime(5000);
// Enable recognition of multiple codes (up to 4) from the photo album. This feature is supported only on baseline 10.2.3 and later.
scanRequest.setEnableAlbumMultiCode(true);
// Set a custom permission request flow.
scanRequest.setPermissionDelegate(new PermissionDelegate() {
/**
* Starts the permission request. You can implement your own permission request interaction or provide an explanation here.
* Note:
* 1. After handling your own logic, you must request permissions. Otherwise, the process will be blocked.
* 2. If the user denies the permission, `onPermissionDenied` and `MPScanCallbackAdapter.onScanError` are called.
* `MPScanCallbackAdapter.onScanError` provides a default implementation for handling permission request failures. You can override this method to handle the error.
* @param fragment The scan page.
* @param requestCode 1: Camera permission.
* @param permissions The requested permissions.
*
*/
@Override
public void onRequestPermission(Fragment fragment, final int requestCode, final String[] permissions) {
// Handle camera permission.
if(requestCode == 1){
// Handle your business logic.
showPermissionTipDialog();
}
// This must be called to start the permission request.
fragment.requestPermissions(permissions, requestCode);
}
/**
* Callback for when permissions are successfully granted.
*/
@Override
public void onPermissionGranted(Fragment fragment, int requestCode, String[] permissions, int[] grantResults) {
dismissPermissionTipDialog();
}
/**
* Callback for when permissions are denied.
*/
@Override
public void onPermissionDenied(Fragment fragment, int requestCode, String[] permissions, int[] grantResults) {
dismissPermissionTipDialog();
}
});
Escaneo por ventana
Al utilizar la función de escaneo por ventana, establezca los parámetros de inicio como se muestra en el siguiente código.
ScanRequest scanRequest = new ScanRequest();
// Set the UI style of the scan page.
scanRequest.setScanType(ScanRequest.ScanType.QRCODE); // QR code style
scanRequest.setScanType(ScanRequest.ScanType.BARCODE); // Barcode style, default
// Set the title of the scan interface.
scanRequest.setTitleText("Standard Scan");
// Set the prompt text below the scan window.
scanRequest.setViewText("Prompt text");
// Set the prompt text for turning on the flashlight. Supported only on baseline 10.1.60 and later.
scanRequest.setOpenTorchText("Turn on flashlight");
// Set the prompt text for turning off the flashlight. Supported only on baseline 10.1.60 and later.
scanRequest.setCloseTorchText("Turn off flashlight");
// Set the scan recognition type. Supported only on baselines 10.1.60.6+ and 10.1.68.2+.
// This setting is effective only for direct scanning, not for recognizing images from the photo album.
scanRequest.setRecognizeType(
ScanRequest.RecognizeType.QR_CODE, // QR code
ScanRequest.RecognizeType.BAR_CODE, // Barcode
ScanRequest.RecognizeType.DM_CODE, // DM code
ScanRequest.RecognizeType.PDF417_Code // PDF417 code
); // If not set, the first three types are recognized by default.
// Set a transparent status bar (effective on Android 4.4+). Supported only on baseline 10.1.68.15+.
scanRequest.setTranslucentStatusBar(true);
// Hide the photo album button. Supported only on baseline 10.1.68.22+.
scanRequest.setNotSupportAlbum(true);
Uso de la función de escaneo con una interfaz personalizada
Para obtener más información, consulte el ejemplo de código.
Adaptación de interfaces personalizadas para actualizaciones
A partir de la versión 10.2.3.35, el SDK de escaneo proporciona la clase
MPCustomScanViewe interfaces relacionadas para reemplazar aMPScanneren la implementación de interfaces personalizadas. En comparación conMPScanner, la soluciónMPCustomScanViewencapsula procesos centrales del servicio de escaneo, como la gestión de la cámara, el reconocimiento de códigos, el reconocimiento de varios códigos, el zoom de imagen y el análisis sintáctico de resultados. Esto le permite centrarse en implementar su interfaz personalizada enMPCustomScanViewsin gestionar estas operaciones subyacentes. Puede continuar usandoMPScanner, pero ya no recibe mantenimiento ni actualizaciones de funciones acordes con la interfaz de pantalla completa, como el reconocimiento de varios códigos. Se recomienda cambiar a la soluciónMPCustomScanViewpara implementar su interfaz personalizada cuando sea apropiado. Esta solución mantendrá la consistencia con la interfaz de pantalla completa en futuras actualizaciones de funciones.-
A partir de las versiones 10.1.68.5 y 10.1.60.11, el SDK de escaneo incluye la clase
MPScannere interfaces relacionadas. Estas reemplazan a las interfaces heredadas, comoBQCScanCallbackyMaScanCallback, para el escaneo personalizado. Comparado con las interfaces heredadas,MPScannerofrece una encapsulación completa, API sencillas y compatibilidad con más funciones, como una devolución de llamada para luz ambiental insuficiente. Si aún utiliza interfaces heredadas comoBQCScanCallbackyMaScanCallback, es posible que deba adaptarse a los siguientes cambios al actualizar desde una versión anterior:Versión 10.1.68.22: Se agregaron nuevas interfaces a las clases
MaScanCallback,BQCScanCallbackyIOnMaSDKDecodeInfo. Proporcione implementaciones vacías para estas interfaces y asegúrese de que el métodoMaScanCallback.onMaCodeInterceptordevuelvafalse.Versión 10.1.60.6: Se agregaron nuevas interfaces a la clase
BQCScanCallback. Proporcione implementaciones vacías para estas interfaces.Versión 10.1.60: Se agregaron nuevas interfaces a la clase
BQCScanCallback. Proporcione implementaciones vacías para estas interfaces.-
Versión 10.1.20: La interfaz de la clase
MaScanCallbackcambió devoid onResultMa(MaScanResult maScanResult)avoid onResultMa(MultiMaScanResult multiMaScanResult). ObtengaMaScanResultde la siguiente manera:MaScanResult maScanResult = multiMaScanResult.maScanResults[0];
Referencia de API de interfaz personalizada
MPCustomScanView
Para usar MPCustomScanView, haga que su clase Activity herede de MPaasToolsCaptureActivity. Luego, implemente el método getCustomScanView para devolver su MPCustomScanView personalizada.
public class MyScanActivity extends MPaasToolsCaptureActivity {
private MyScanView myScanView;
@Override
protected MPCustomScanView getCustomScanView() {
myScanView = new MyScanView(this);
// For details, see the code sample on GitHub.
return myScanView;
}
}
Implemente o llame a los siguientes métodos en MPCustomScanView:
/**
* Callback for when the scan starts.
*/
public void onStartScan();
/**
* Callback for when the first frame from the camera is displayed.
*
* The execution order of this method and the scan start callback is not guaranteed.
*/
public void onPreviewShow();
/**
* Callback for when the scan stops.
*/
public void onStopScan();
/**
* Callback for the grayscale value of the camera frame.
* This is called for every frame during the scan.
*
* @param gray The average grayscale value, which can be used to measure ambient brightness.
*/
public void onGetAvgGray(int gray);
/**
* Callback for a successful scan (a code is recognized).
*
* @param context The current context.
* @param list The recognized code results.
*/
public abstract void onScanFinished(Context context, List<MPScanResult> list);
/**
* Callback for a failed scan.
*
* @param context The current context.
* @param error The reason for the failure.
*/
public abstract void onScanFailed(Context context, MPScanError error);
/**
* Callback for when the camera fails to open.
*/
public void onCameraOpenFailed();
/**
* Switches the flashlight on or off.
*
* @return The state of the flashlight after this method is called.
*/
public boolean switchTorch();
/**
* Recognizes codes from a file.
*
* @param path The file path.
* @return The recognized code results.
*/
public List<MPScanResult> scanFromPath(String path);
MPScanResult
/**
* The recognized result string.
*/
private String text;
/**
* The type of the recognized code.
*/
private MPRecognizeType mpRecognizeType;
/**
* The centroid coordinate of the recognized code.
*/
private Point centerPoint;
Flujo de solicitud de permisos personalizado
Para personalizar el flujo de solicitud de permisos, implemente la interfaz PermissionDelegate:
public class MyScanActivity extends MPaasToolsCaptureActivity implements PermissionDelegate{
/**
* Starts the permission request. Users can implement their own permission request interaction or provide an explanation here.
* Note: After handling your own logic, you must request permissions. Otherwise, the process will be blocked.
* @param fragment The scan page.
* @param requestCode 1: Camera permission.
* @param permissions The requested permissions.
*/
@Override
public void onRequestPermission(Fragment fragment, final int requestCode, final String[] permissions) {
// Handle camera permission.
if(requestCode == 1){
// Handle your business logic.
showPermissionTipDialog();
}
// This must be called to start the permission request.
fragment.requestPermissions(permissions, requestCode);
}
/**
* Callback for when permissions are successfully granted.
*/
@Override
public void onPermissionGranted(Fragment fragment, int requestCode, String[] permissions, int[] grantResults) {
dismissPermissionTipDialog();
}
/**
* Callback for when permissions are denied.
*/
@Override
public void onPermissionDenied(Fragment fragment, int requestCode, String[] permissions, int[] grantResults) {
dismissPermissionTipDialog();
}
}
MPScanner (Obsoleto)
La configuración relacionada con la interfaz personalizada es la siguiente:
/**
* Sets the View that displays the camera content.
* Call this in the `onConfiguration` method of `{@link MPScanListener}`.
*
* @param textureView The TextureView in the custom scan page.
*/
public void setDisplayView(TextureView textureView);
/**
* Sets the area for scan recognition.
*
* @param rect The recognition area.
*/
public void setScanRegion(Rect rect);
/**
* Sets the scan listener.
*/
public void setMPScanListener(MPScanListener mpScanListener);
/**
* Sets the listener for the image grayscale value.
*/
public void setMPImageGrayListener(MPImageGrayListener mpImageGrayListener);
/**
* Gets the Camera object.
*
* @return The Camera object.
*/
public Camera getCamera();
/**
* Sets the types of codes to recognize.
* This is effective only for direct scanning, not for recognizing codes from a bitmap.
*
*
* @param recognizeTypes BAR_CODE for barcodes, QR_CODE for QR codes, DM_CODE for DM codes, and PDF417_CODE for PDF417 codes.
* If not set, the first three types are recognized by default.
*/
public void setRecognizeType(MPRecognizeType... recognizeTypes);
Las operaciones de escaneo relacionadas con la interfaz personalizada son las siguientes:
/**
* Opens the camera and starts scanning.
*
* Call this when first entering the page or when the camera is off.
*/
public void openCameraAndStartScan();
/**
* Closes the camera and stops scanning.
*/
public void closeCameraAndStopScan();
/**
* Starts scanning.
*
* This does not change the camera state. It must be called when the camera is on to take effect.
*/
public void startScan();
/**
* Stops scanning.
*
* This does not change the camera state.
*/
public void stopScan();
/**
* Recognizes a code from a bitmap.
*
* @param bitmap The bitmap to be recognized.
* @return The scan result.
*/
public MPScanResult scanFromBitmap(Bitmap bitmap);
Otros:
/**
* Turns the flashlight on or off.
*
* @return Whether the flashlight is on after the method is called.
*/
public boolean switchTorch();
/**
* Turns on the flashlight.
*/
public void openTorch();
/**
* Turns off the flashlight.
*/
public void closeTorch();
/**
* Plays the default beep sound.
*/
public void beep();
/**
* Releases resources.
*
* Call this method in onDestroy.
*/
public void release();
MPScanListener (Obsoleto)
/**
* Called when the scan parameter configuration is complete.
*/
void onConfiguration();
/**
* Called when the scan and detection process starts.
*/
void onStart();
/**
* Called when the detection is successful.
*
* @param result The detection result.
*/
void onSuccess(MPScanResult result);
/**
* Called when a detection error occurs.
*
* @param error The error.
*/
void onError(MPScanError error);
MPImageGrayListener (Obsoleto)
/**
* Gets the average grayscale value of the image.
*
* The normal range is approximately 50 to 140.
* If the grayscale value is outside this range, it usually indicates that the ambient brightness is too low or too high. You can use this information to prompt the user to turn the flashlight on or off.
* Note: This method is called continuously during the recognition process.
*
* @param gray The average grayscale value of the image.
*/
void onGetImageGray(int gray);