首先导入依赖:
compile 'com.journeyapps:zxing-android-embedded:3.5.0'
这个库可以自定义扫描界面,很方便,自带的扫描界面很丑,满足不了开发需求,所以改掉了。
效果:
button_scan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(mActivity);
integrator.setOrientationLocked(false)//设置扫码的方向
.setPrompt("请将二维码放至扫描区域")//设置下方提示文字
.setCameraId(0)//前置或后置摄像头
.setBeepEnabled(true)//扫码提示音,默认开启
.setCaptureActivity(ScanActivity.class)//设置扫码界面为自定义样式
.initiateScan();
}
});
注释写的都很清楚,.setCaptureActivity(ScanActivity.class),自定义扫描界面需要自定义扫描界面。
看下ScanActivity
package cn.jinyuanmy.store.activity;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import cn.jinyuanmy.store.R;
/**
* Created by Administrator on 2017/11/1.
*/
public class ScanActivity extends Activity {
private CaptureManager capture;
private DecoratedBarcodeView barcodeScannerView;
private ImageView light;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.zxing_barcode_scanner_activity);
barcodeScannerView = (DecoratedBarcodeView)findViewById(R.id.zxing_barcode_scanner);
//固定写法
capture = new CaptureManager(this, barcodeScannerView);
capture.initializeFromIntent(getIntent(), savedInstanceState);
capture.decode();
light = (ImageView) findViewById(R.id.light);//开灯按钮
if (!hasFlash()) {//判断该手机是否存在闪光灯
light.setVisibility(View.GONE);
}
light.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
light();
}
});
}
private boolean flag = true;
// 开启闪光灯
protected void light() {
if (flag) {
flag = false;
// 开闪光灯
barcodeScannerView.setTorchOn();
} else {
flag = true;
// 关闪光灯
barcodeScannerView.setTorchOff();
}
int icon= flag?R.drawable.icon_flash_lamp_norm:R.drawable.icon_flash_lamp;
light.setImageResource(icon);
}
@Override
protected void onResume() {
super.onResume();
capture.onResume();
}
@Override
protected void onPause() {
super.onPause();
capture.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
capture.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
capture.onSaveInstanceState(outState);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
capture.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return barcodeScannerView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
// 判断是否有闪光灯功能
private boolean hasFlash() {
return getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
}
zxing_barcode_scanner_activity.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="@+id/zxing_barcode_scanner"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:zxing_scanner_layout="@layout/custom_barcode_scanner"
app:zxing_use_texture_view="true" />
<ImageView
android:id="@+id/light"
android:layout_width="25dp"
android:layout_height="25dp"
android:scaleType="fitXY"
android:layout_alignParentBottom="true"
android:layout_marginBottom="100dp"
android:layout_centerHorizontal="true"
android:src="@drawable/icon_flash_lamp_norm"/>
</RelativeLayout>
导入自定义布局
app:zxing_scanner_layout="@layout/custom_barcode_scanner"
custom_barcode_scannerd.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<com.journeyapps.barcodescanner.BarcodeView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/zxing_barcode_surface"
app:zxing_framing_rect_width="250dp"
app:zxing_framing_rect_height="250dp">
</com.journeyapps.barcodescanner.BarcodeView>
<cn.jinyuanmy.store.ui.CustomViewfinderView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/zxing_viewfinder_view"
app:zxing_possible_result_points="@color/zxing_custom_possible_result_points"
app:zxing_result_view="@color/zxing_custom_result_view"
app:zxing_viewfinder_laser="#0F8EE9"
app:zxing_viewfinder_mask="@color/zxing_custom_viewfinder_mask"/>
<TextView
android:id="@+id/zxing_status_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:background="@color/zxing_transparent"
android:text="@string/zxing_msg_default_status"
android:textColor="@color/zxing_status_text"/>
</merge>
然后自定义CustomViewfinderView
package cn.jinyuanmy.store.ui;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;
import com.google.zxing.ResultPoint;
import com.journeyapps.barcodescanner.ViewfinderView;
import java.util.ArrayList;
import java.util.List;
/**
* 自定义zxing二维码扫描界面
* Created by IBM on 2016/10/20.
*/
public class CustomViewfinderView extends ViewfinderView {
public int laserLinePosition=0;
public float[] position=new float[]{0f,0.5f,1f};
public int[] colors=new int[]{0x00ffffff,0xffffffff,0x00ffffff};
public LinearGradient linearGradient ;
public CustomViewfinderView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 重写draw方法绘制自己的扫描框
* @param canvas
*/
@Override
public void onDraw(Canvas canvas) {
refreshSizes();
if (framingRect == null || previewFramingRect == null) {
return;
}
Rect frame = framingRect;
Rect previewFrame = previewFramingRect;
int width = canvas.getWidth();
int height = canvas.getHeight();
//绘制4个角
paint.setColor(Color.parseColor("#0F8EE9"));//定义画笔的颜色
canvas.drawRect(frame.left, frame.top, frame.left+70, frame.top+10, paint);
canvas.drawRect(frame.left, frame.top, frame.left + 10, frame.top + 70, paint);
canvas.drawRect(frame.right-70, frame.top, frame.right, frame.top+10, paint);
canvas.drawRect(frame.right-10, frame.top, frame.right, frame.top+70, paint);
canvas.drawRect(frame.left, frame.bottom-10, frame.left+70, frame.bottom, paint);
canvas.drawRect(frame.left, frame.bottom-70, frame.left+10, frame.bottom, paint);
canvas.drawRect(frame.right-70, frame.bottom-10, frame.right, frame.bottom, paint);
canvas.drawRect(frame.right-10, frame.bottom-70, frame.right, frame.bottom, paint);
// Draw the exterior (i.e. outside the framing rect) darkened
paint.setColor(resultBitmap != null ? resultColor : maskColor);
canvas.drawRect(0, 0, width, frame.top, paint);
canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
canvas.drawRect(0, frame.bottom + 1, width, height, paint);
if (resultBitmap != null) {
// Draw the opaque result bitmap over the scanning rectangle
paint.setAlpha(CURRENT_POINT_OPACITY);
canvas.drawBitmap(resultBitmap, null, frame, paint);
} else {
// paint.setAlpha(SCANNER_ALPHA[scannerAlpha]);
// scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length;
int middle = frame.height() / 2 + frame.top;
laserLinePosition=laserLinePosition+5;
if(laserLinePosition>frame.height())
{
laserLinePosition=0;
}
linearGradient= new LinearGradient(frame.left + 1, frame.top+laserLinePosition , frame.right -1 , frame.top +10+laserLinePosition, colors, position, Shader.TileMode.CLAMP);
// Draw a red "laser scanner" line through the middle to show decoding is active
// paint.setColor(laserColor);
paint.setShader(linearGradient);
//绘制扫描线
canvas.drawRect(frame.left + 1, frame.top+laserLinePosition , frame.right -1 , frame.top +10+laserLinePosition, paint);
paint.setShader(null);
float scaleX = frame.width() / (float) previewFrame.width();
float scaleY = frame.height() / (float) previewFrame.height();
List<ResultPoint> currentPossible = possibleResultPoints;
List<ResultPoint> currentLast = lastPossibleResultPoints;
int frameLeft = frame.left;
int frameTop = frame.top;
if (currentPossible.isEmpty()) {
lastPossibleResultPoints = null;
} else {
possibleResultPoints = new ArrayList<>(5);
lastPossibleResultPoints = currentPossible;
paint.setAlpha(CURRENT_POINT_OPACITY);
paint.setColor(resultPointColor);
for (ResultPoint point : currentPossible) {
canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
frameTop + (int) (point.getY() * scaleY),
POINT_SIZE, paint);
}
}
if (currentLast != null) {
paint.setAlpha(CURRENT_POINT_OPACITY / 2);
paint.setColor(resultPointColor);
float radius = POINT_SIZE / 2.0f;
for (ResultPoint point : currentLast) {
canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
frameTop + (int) (point.getY() * scaleY),
radius, paint);
}
}
postInvalidateDelayed(16,
frame.left ,
frame.top ,
frame.right ,
frame.bottom);
// postInvalidate();
}
}
}
这个类用自定义四个边角,然后扫描线绘制
看下扫描成功后如何处理
package cn.jinyuanmy.store.util;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import cn.jinyuanmy.store.Run;
import cn.jinyuanmy.store.activity.AgentActivity;
/**
* Created by Administrator on 2017/11/2.
*
*二维码工具类
*/
public class QRCodeUtil {
/**
* 处理 扫面后返回结果处理
* @param requestCode
* @param resultCode
* @param data
* @param activity
*/
public static String onResult(int requestCode, int resultCode , Intent data, Activity activity)
{
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
//扫描成功
if (result.getContents() == null) {
//结束扫码
} else {
if (result.getContents().contains("agent_bn"))//是否包含注册会员推荐码
{
//扫码出结果
String [] resultArr=result.getContents().split("\\?");
if (resultArr!=null&&resultArr.length>0&&resultArr.length==2)
{
String agent_bn =resultArr[1];//获得推荐码
String [] agentArr= agent_bn.split("=");
if (agentArr!=null&&agentArr.length>0)
{
return agentArr[1];
}else {
return "";
}
}
}else {//不包含
Run.alert(activity,"请放置正确的二维码");
return "";
}
}
}
return "";
}
/**
* 点击生成按钮,根据字符串生成对应的二维码
*/
public static Bitmap createCode(String erWeiMa) {
Bitmap bitmap=null;
BitMatrix matrix;
MultiFormatWriter writer = new MultiFormatWriter();
try {
matrix = writer.encode(erWeiMa, BarcodeFormat.QR_CODE, 500, 500);
BarcodeEncoder encoder = new BarcodeEncoder();
bitmap = encoder.createBitmap(matrix);
} catch (WriterException e) {
e.printStackTrace();
}
return bitmap;
}
}
使用:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String qrCodeRequest= QRCodeUtil.onResult(requestCode, resultCode, data,mTabActivity);
if (!TextUtils.isEmpty(qrCodeRequest))
{
if (AgentApplication.getLoginedUser(this).isLogined())//判断是否登录
{
Run.excuteJsonTask(new JsonTask(), new SetMyAgentTask(qrCodeRequest));
}else {//没有登录
startActivity(AgentActivity.intentForFragment(mTabActivity, AgentActivity.FRAGMENT_ACCOUNT_REGIST).
putExtra("agent_bn",qrCodeRequest));
}
}
}
每个项目中生成的二维码格式不一样的,所以如何处理是需要你们自己去弄。
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
result.getContents()//可以获得我们扫描回来的结果,自己处理即可