Android二維碼工具zxing使用
阿新 • • 發佈:2017-07-23
bit imageview bitmap spl mage word static factor stc
二維碼在我們生活中隨處可見。在我眼裏簡直能夠用“泛濫”來形容啦。那怎樣在我們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
Android二維碼工具zxing使用