程序源代码及可执行文件下载地址:http://files.cnblogs.com/rainboy2010/zbardemo.zip
Android下常用的条码扫描类库有zxing和zbar,比较了一下,发现zbar扫描速度更快,能够识别的条码类型更多,下面就讲解一下如何利用zbar实现扫一扫,先放上一张效果图:
主要代码如下:
1.在onPreviewFrame方法里获取预览图像,然后传递给DecodeHandler去解析
@Override
public void onPreviewFrame(byte[] data, Camera camera)
{
if (!useOneShotPreviewCallback)
{
camera.setPreviewCallback(null);
}
if(previewHandler != null)
{
Camera.Parameters parameters = camera.getParameters();
Size size = parameters.getPreviewSize();
Message message = previewHandler.obtainMessage(previewMessage, size.width,size.height, data);
message.sendToTarget();
previewHandler = null;
}
else
{
Log.d(TAG, "Got preview callback, but no handler for it");
} }
2. 在decode方法里调用zbar类库对图像进行解析
private void decode(byte[] data, int width, int height) { Image barcode = new Image(width, height, "Y800");
Rect scanImageRect = activity.getViewfinderView().getScanImageRect(height,width);
barcode.setCrop(scanImageRect.top, scanImageRect.left, scanImageRect.bottom, scanImageRect.right);
barcode.setData(data); int result = scanner.scanImage(barcode);
String strResult="";
if (result != 0)
{
SymbolSet syms = scanner.getResults();
for (Symbol sym : syms)
{
strResult=sym.getData().trim();
if(!strResult.isEmpty())
{
break;
}
}
} if(!strResult.isEmpty())
{
Message message = Message.obtain(activity.getHandler(), R.id.decode_succeeded, strResult);//Message信息传来传去,有点绕
Log.d(TAG, "Sending decode succeeded message...");
message.sendToTarget();
}
else
{
Message message = Message.obtain(activity.getHandler(), R.id.decode_failed);
message.sendToTarget();
}
}