二维码在我们生活中随处可见,在我眼里简直可以用“泛滥”来形容啦!那如何在我们Android项目中扫描识别二维码或生成二维码图片呢?
我们通常使用的开源框架是zxing。在github上的开源地址:https://github.com/zxing/zxing,目前在做的项目中也用到这个框架,
所以自己做了个demo,方便学习及下次使用。
识别二维码
/**
* 扫描二维码示例
*/
public class ScanCodeActivity extends Activity implements View.OnClickListener {
private Button start_scan;
private TextView result_tv;
private final static int REQUEST_CODE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
this.start_scan = (Button) findViewById(R.id.start_scan);
this.result_tv = (TextView) findViewById(R.id.result_tv);
this.start_scan.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.start_scan) {
//zxing框架已经帮我们封装好对应的实现类,直接调用startActivityForResult即可
Intent intent = new Intent(this, CaptureActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
}
/**
* 在onActivityResult中处理数据
* @param requestCode
* @param resultCode
* @param data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
Bundle bundle = data.getExtras();
String scanResult = bundle.getString("result");
this.result_tv.setText(scanResult);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
生成二维码:
/**
* 生成二维码示例
*/
public class MadeCodeActivity extends Activity implements View.OnClickListener {
private EditText code_edt;
private Button made_code;
private ImageView result_iv;
private CheckBox logo_cb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_made);
this.code_edt = (EditText) findViewById(R.id.code_edt);
this.made_code = (Button) findViewById(R.id.made_code);
this.result_iv = (ImageView) findViewById(R.id.result_iv);
logo_cb = (CheckBox) findViewById(R.id.logo_cb);
this.made_code.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.made_code) {
String content = code_edt.getText().toString().trim();
boolean isAddLogo = logo_cb.isChecked();
if (TextUtils.isEmpty(content)) {
Toast.makeText(this, "输入内容不能为空", Toast.LENGTH_LONG).show();
return;
}
madeCode(content, isAddLogo);
}
}
/**
* 生成二维码
*
* @param content 要生成图片的文字内容
* @param isAddLogo 是否在二维码中添加LOGO图片
*/
private void madeCode(String content, boolean isAddLogo) {
String bitmapPath;
if (!isAddLogo) {//不带LOGO
bitmapPath = EncodeUtil.createQRImage(this, content, 300, 300, null);
} else {//带Logo,R.mipmap.ic_launcher就是LOGO对应图片,自行添加
bitmapPath = EncodeUtil.createQRImage(this, content, 300, 300, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
}
if (!TextUtils.isEmpty(bitmapPath)) {
result_iv.setImageBitmap(BitmapFactory.decodeFile(bitmapPath));
}
}
}
完成的项目(AndroidStudio项目)下载地址:
http://download.csdn.net/detail/true100/9487162