原文章:点击打开链接
在这里介绍一个简单速成的二维码方法
首先加入相机权限声明
<uses-permission android:name="android.permission.CAMERA" /> <!--相机-->
有网络的条件下添加依赖
compile 'com.journeyapps:zxing-android-embedded:3.5.0'
写一个布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:weightSum="1"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="生成" android:id="@+id/btn_produce" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="扫描" android:id="@+id/btn_scan" /> </LinearLayout> <ImageView android:layout_width="300dp" android:layout_height="300dp" android:id="@+id/iv_zxing" /> <TextView android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/tv_result" android:hint="result"/> <EditText android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/et_string" android:text="http://www.csdn.net"/> </LinearLayout>
生成二维码所需的主要代码
public void generate(View view,String string) { Bitmap qrBitmap = generateBitmap(string,300, 300); iv_zxing.setImageBitmap(qrBitmap); } private Bitmap generateBitmap(String content, int width, int height) { QRCodeWriter qrCodeWriter = new QRCodeWriter(); Map<EncodeHintType, String> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); try { BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints); int[] pixels = new int[width * height]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (encode.get(j, i)) { pixels[i * width + j] = 0x00000000; } else { pixels[i * width + j] = 0xffffffff; } } } return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565); } catch (WriterException e) { e.printStackTrace(); } return null; }
这里在点击生成按钮那里,调用上面的generate()函数,并传入EditText中获得的文字(view没用)
对文字处理后generateBitmap得到的bitmap,传给布局中的imageview,调用
iv_zxing.setImageBitmap(qrBitmap);
就可以显示我们生成的二维码啦
扫描二维码所需的代码
在点击扫描按钮那里,调用以下代码,利用IntentIntegrator 进入扫描界面
IntentIntegrator intentIntegrator=new IntentIntegrator(ZxingActivity.this); intentIntegrator.initiateScan(); Log.w("Zxingactivity","开始扫描");
扫描成功后,从扫描界面返回
重写Actictivity中的onActivityResult方法来对获得的数据进行处理
public void onActivityResult(int requestCode,int resultCode,Intent data) { IntentResult result=IntentIntegrator.parseActivityResult(requestCode,resultCode,data); if(result!=null) { if(result.getContents()==null) { Toast.makeText(this, "取消扫描", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(this,"扫描成功",Toast.LENGTH_SHORT).show(); tv_result.setText(result.getContents()); } } else{ super.onActivityResult(requestCode,resultCode,data); } }
调用 tv_result.setText(result.getContents());
并展示在textview中,这样基本的功能就实现了。
另外条形码也可以扫描哦