效果图:
条形码扫描:
二维码扫描:
二维码生成:
项目结构:
这个项目很简单,就2个类,一个jar包和一些依赖,十分简洁。
主要代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView resultTV;
private ImageView resultIV;
private EditText strET;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultTV = (TextView) findViewById(R.id.tv_scan_result);
resultIV = (ImageView) findViewById(R.id.iv_qr_image);
strET = (EditText) findViewById(R.id.et_qr_string);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_scan_barcode) {
IntentIntegrator integrator = new IntentIntegrator(this);
//获取屏幕尺寸
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
//条形码
int width = dm.heightPixels / 2;
int height = dm.widthPixels / 2;
integrator.setScanningRectangle(width, height);//扫描框
integrator.setPrompt("请对准条形码进行扫描");
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);//条形码
//二维码
// int len = dm.heightPixels / 2;
// integrator.setScanningRectangle(len, len);//扫描框
// integrator.setPrompt("请对准二维码进行扫描");
// integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);//二维码
integrator.setResultDisplayDuration(0);//扫描框内横线的时间
integrator.setCameraId(0);
integrator.initiateScan();
} else {
final String filePath = getFileRoot(this) + File.separator + "qr_" + System.currentTimeMillis() + ".jpg";
//二维码图片较大时,生成图片、保存文件的时间可能较长,因此放在新线程中
new Thread(new Runnable() {
@Override
public void run() {
boolean success = QRCodeUtil.createQRImage(strET.getText().toString().trim(), 800, 800, BitmapFactory.decodeResource(getResources(), R.drawable.c4),
filePath);
if (success) {
runOnUiThread(new Runnable() {
@Override
public void run() {
resultIV.setImageBitmap(BitmapFactory.decodeFile(filePath));
}
});
}
}
}).start();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
resultTV.setText("扫描取消");
} else {
resultTV.setText(result.getContents());
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
//文件存储根目录
private String getFileRoot(Context context) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File external = context.getExternalFilesDir(null);
if (external != null) {
return external.getAbsolutePath();
}
}
return context.getFilesDir().getAbsolutePath();
}
}
源码下载:
参考链接:感谢这篇博客
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-15 07:05:32