最近研究了一下二维码扫描,github地址(https://github.com/zxing/zxing)。本来想做个扫描相册内的二维码的,结果没做成。我先分析一下整个开源项目的流程
这里我要重点接收一下restartPreviewAndDecode这个函数
/**
* A single preview frame will be returned to the handler supplied. The data
* will arrive as byte[] in the message.obj field, with width and height
* encoded as message.arg1 and message.arg2, respectively.
*
* @param handler
* The handler to send the message to.
* @param message
* The what field of the message to be sent.
*/
public synchronized void requestPreviewFrame(Handler handler, int message) {
Camera theCamera = camera;
if (theCamera != null && previewing) {
previewCallback.setHandler(handler, message);
theCamera.setOneShotPreviewCallback(previewCallback);
}
}
意思很明确,会返回handler一个消息,消息的what域就是这个id。
好,我们继续往下看。
其中setHandler函数就是把handler和message绑定在一个PreviewCallback类里面
setOneShotPreviewCallback参数是一个接口,这里传入previewCallback这个实例,那么必然会调用继承的函数onPreviewFrame
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
Point cameraResolution = configManager.getCameraResolution();
Handler thePreviewHandler = previewHandler;
if (cameraResolution != null && thePreviewHandler != null) {
Message message = thePreviewHandler.obtainMessage(previewMessage,
cameraResolution.x, cameraResolution.y, data);
message.sendToTarget();
previewHandler = null;
} else {
Log.d(TAG,
"Got preview callback, but no handler or resolution available");
}
}
注意到了没,这个byte[] data数据就是之后会解析的数据,但是如何生成的这里看不到,它又是如何从bitmap转化来的,也不知道。网上的一些demo有的是自己生成自己解析的,那当然知道数据来源以及格式。
二维码的解析函数大致摘抄如下:
RGBLuminanceSource source = new RGBLuminanceSource(width,
height, pixels);
Result rawResult = null;
if (source != null) {
MultiFormatReader multiFormatReader = new MultiFormatReader();
BinaryBitmap binaryBitmap = new BinaryBitmap(
new HybridBinarizer(source));
try {
rawResult = multiFormatReader.decode(binaryBitmap);
Toast.makeText(
getApplicationContext(),
rawResult.getBarcodeFormat() + "\n"
+ rawResult.getText().toString(),
Toast.LENGTH_SHORT).show();
} catch (ReaderException re) {
Toast.makeText(getApplicationContext(), "二维码解析有误",
Toast.LENGTH_SHORT).show();
} finally {
multiFormatReader.reset();
}
}
由于不知道上文所述的byte[] data哪里来的导致RGBLuminanceSource 构造函数有问题,所以就一直Toast二维码解析有误。有没有大神指点一二啊