Android基于google ZXing的简化版BarCodeTest实现二维码的扫描及简单的网页跳转

来源:互联网 发布:网络情侣名字大全 编辑:程序博客网 时间:2024/06/01 08:18

对于二维码扫描我们使用的是google的开源框架Zxing,我们可以去http://code.google.com/p/zxing/下载源码和Jar包或者可以去https://github.com/zxing/zxing下载整个开源项目。鉴于这个ZXing比较复杂、通过几天的查资料、使用基于ZXing的BarCodeTest比较简单粗暴,因此我说一下BarCodeTest的使用,直接在百度搜索BarCodeTest,我是在这里下载的。

下载好后解压、然后导入eclipse中、

然后点击项目鼠标右击选择Properties->Android把BarCodeTest作为library然后点击OK就好了


然后clean一下BarCodeTest发现这个时候报错,

找到报错地方,报错的信息主要是case中的值必须为常量不能为变量、出现这个原因主要是

BarCodeTest做为Is Library后产生的。把switch语句修改后就可以了、把switch...case语句替换为if...else语句就可以了



代码如下:if(message.what == R.id.auto_focus)

else if(message.what == ...)里面的代码内容不变、然后新建项目、把BarCodeTest作为库文件。

在项目清单文件中添加

<activity
            android:configChanges="orientation|keyboardHidden"
            android:name="com.zxing.activity.CaptureActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:windowSoftInputMode="stateAlwaysHidden" >
        </activity>

这个在BarCodeTest清单文件中找、直接粘贴复制过来就可以了、同时添加所需的权限

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.CAMERA" />

想要在扫描的界面直接显示扫描出来的结果、直接在BarCodeTest的CaptureActivity类中修改、找到public void handleDecode(Result result, Bitmap barcode) {
inactivityTimer.onActivity();
playBeepSoundAndVibrate();
String resultString = result.getText();
//FIXME
if (resultString.equals("")) {
Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
}else {

System.out.println("Result:"+resultString);
Intent resultIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("result", resultString);
resultIntent.putExtras(bundle);
this.setResult(RESULT_OK, resultIntent);

}

CaptureActivity.this.finish();

这是扫描结果的核心代码、在else里面修改就可以直接显示扫描结果了。记得要把CaptureActivity.this.finish();注释掉、把你想要运行的代码修改进来、例如我将扫描结果直接显示在扫描的界面、如果结果是网址就直接跳转,代码如下:

Pattern pattern=Pattern.compile("http://(([a-zA-z0-9]|-){1,}\\.){1,}[a-zA-z0-9]{1,}-*");
Matcher matcher=pattern.matcher(resultString);
if(matcher.find()){ //判断扫描的结果是否为url、是url直接跳转到网页中                     
Intent intent = new Intent();        
       intent.setAction("android.intent.action.VIEW");    
       Uri content_url = Uri.parse(resultString);   
       intent.setData(content_url);  
       startActivity(intent);
}else{//不是直接显示
//创建dialog对象
AlertDialog alertDialog = new AlertDialog.Builder(CaptureActivity.this).create();
alertDialog.setTitle("扫描结果");
//显示扫描的信息
alertDialog.setMessage(resultString);
//设置按钮
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alertDialog.show();

}





1 0