花了一下午的时间,终于将二维码扫描功能的整个流程整理清楚了.
具体步骤:
1.将zxing-1.6.jar拷贝到项目libs文件夹下;
2.在app的build.gradle文件写的dependencies添加: compile files('libs/zxing-1.6.jar')
3.清单文件添加权限:
<uses-permission android:name="android.permission.VIBRATE"/> <uses-permission android:name="android.permission.CAMERA"/> <uses-feature android:name="android.hardware.camera"/> <uses-feature android:name="android.hardware.camera.autofocus"/>
4.拷贝(Demo里有):
1)相关类:我是分成三个包,分别为:camera,decoding,view.直接拷贝在项目里就可以了.
2)res文件夹下:
a)raw文件夹---beep.ogg文件
b)value文件夹
1.ids文件
2.colors文件:<color name="result_view">#b0000000</color> <color name="viewfinder_mask">#60000000</color> <color name="possible_result_points">#c0ffff00</color>3.string文件:<string name="scan_text">将商家二维码放入框内,即可自动扫描</string>
5.改错:先将所有报错的类里报错的import删掉
1)CaptureActivityHandler类:
a)将报错的Activity替换成当下项目里用到二维码扫描功能的Activity或者Fragment
b)在报错的地方导入相对应的class(Alt+Enter)
c)剩下报错:要在项目里用到二维码扫描功能的Activity或者Fragment,添加对应方法(三个方法)
d)将handleMessage方法里的switch修改为if
2)DecodeHandler类:
a)将报错的Activity替换成自己当下项目里用到二维码扫描的Activity或者Fragment
b)在报错的地方导入相对应的class(Alt+Enter)
c)剩下报错:要在项目里用到二维码扫描功能的Activity或者Fragment,添加对应方法(一个方法)
3)DecodeThread类:将报错的Activity替换成当下项目里用到二维码扫描功能的Activity或者Fragment
4)ViewfinderView类:
在报错的地方导入相对应的class(Alt+Enter)
6.拷贝扫描布局到Activity或者Fragment对应layout里:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SurfaceView
android:id="@+id/surfaceview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"/>
<com.example.yyj.qrcode.view.ViewfinderView
android:id="@+id/viewfinder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
7.扫描功能的Activity或者Fragment代码
package com.example.yyj.qrcode;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.yyj.qrcode.camera.CameraManager;
import com.example.yyj.qrcode.decoding.CaptureActivityHandler;
import com.example.yyj.qrcode.decoding.InactivityTimer;
import com.example.yyj.qrcode.view.ViewfinderView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import java.io.IOException;
import java.util.Vector;
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback,View.OnClickListener{
private ViewfinderView viewfinderView;
private TextView tv;
private boolean hasSurface;
private InactivityTimer inactivityTimer;
private SurfaceHolder surfaceHolder;
private Vector
decodeFormats;
private String characterSet;
private boolean playBeep;
private boolean vibrate;
private CaptureActivityHandler handler;
private MediaPlayer mediaPlayer;
private static final float BEEP_VOLUME = 0.10f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder);
tv = (TextView) findViewById(R.id.tv_show);
CameraManager.init(getApplicationContext());
hasSurface=false;
inactivityTimer = new InactivityTimer(this);
}
@Override
protected void onResume() {
super.onResume();
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
if (hasSurface){
initCamera(surfaceHolder);
}else {
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
decodeFormats=null;
characterSet=null;
playBeep=true;
AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL){
playBeep=false;
}
initBeepSound();
vibrate = true;
}
/**
* 以下是扫描 相关代码
*/
private void initCamera(SurfaceHolder surfaceHolder) {
try {
CameraManager.get().openDriver(surfaceHolder);
} catch (IOException e) {
return;
}catch (RuntimeException e){
return;
}
if (handler==null){
handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
}
}
private void initBeepSound() {
if (playBeep && mediaPlayer==null){
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(beepListener);
AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(),file.getStartOffset(),file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME,BEEP_VOLUME);
mediaPlayer.prepare();
} catch (IOException e) {
mediaPlayer=null;
}
}
}
private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.seekTo(0);
}
};
@Override
protected void onPause() {
super.onPause();
if (handler!=null){
handler.quitSynchronously();
handler=null;
}
CameraManager.get().closeDriver();
}
@Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
/**
* SurfaceHolder.Callback的三个方法
*/
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (!hasSurface){
hasSurface=true;
initCamera(holder);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface=false;
}
/**
*CaptureActivityHandler类里需要的三个方法
* handleDecode
* getViewfinderView
* drawViewfinder
*/
/**
* 处理扫描结果
* @param result
* @param barcode
*/
public void handleDecode(Result result, Bitmap barcode) {
inactivityTimer.onActivity();
playBeepSoundAndVibrate();
String resultString = result.getText();
if (resultString.equals("")) {
Toast.makeText(this, "扫描失败", Toast.LENGTH_SHORT).show();
}else {
Intent resultIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("result", resultString);
bundle.putParcelable("bitmap", barcode);
resultIntent.putExtras(bundle);
this.setResult(RESULT_OK, resultIntent);
tv.setText(resultString);
tv.setOnClickListener(this);
onPause();
}
}
private static final long VIBRATE_DURATION = 200L;
private void playBeepSoundAndVibrate() {
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
}
if (vibrate) {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATE_DURATION);
}
}
public ViewfinderView getViewfinderView() {
return viewfinderView;
}
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
/**
* DecodeHandler类里需要的方法
*/
public Handler getHandler() {
return handler;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_show:
tv.setText("");//重新扫描
initCamera(surfaceHolder);
break;
}
}
}
:
package com.example.yyj.qrcode;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.yyj.qrcode.camera.CameraManager;
import com.example.yyj.qrcode.decoding.CaptureActivityHandler;
import com.example.yyj.qrcode.decoding.InactivityTimer;
import com.example.yyj.qrcode.view.ViewfinderView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import java.io.IOException;
import java.util.Vector;
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback,View.OnClickListener{
private ViewfinderView viewfinderView;
private TextView tv;
private boolean hasSurface;
private InactivityTimer inactivityTimer;
private SurfaceHolder surfaceHolder;
private Vector
decodeFormats;
private String characterSet;
private boolean playBeep;
private boolean vibrate;
private CaptureActivityHandler handler;
private MediaPlayer mediaPlayer;
private static final float BEEP_VOLUME = 0.10f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder);
tv = (TextView) findViewById(R.id.tv_show);
CameraManager.init(getApplicationContext());
hasSurface=false;
inactivityTimer = new InactivityTimer(this);
}
@Override
protected void onResume() {
super.onResume();
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
if (hasSurface){
initCamera(surfaceHolder);
}else {
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
decodeFormats=null;
characterSet=null;
playBeep=true;
AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL){
playBeep=false;
}
initBeepSound();
vibrate = true;
}
/**
* 以下是扫描 相关代码
*/
private void initCamera(SurfaceHolder surfaceHolder) {
try {
CameraManager.get().openDriver(surfaceHolder);
} catch (IOException e) {
return;
}catch (RuntimeException e){
return;
}
if (handler==null){
handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
}
}
private void initBeepSound() {
if (playBeep && mediaPlayer==null){
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(beepListener);
AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(),file.getStartOffset(),file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME,BEEP_VOLUME);
mediaPlayer.prepare();
} catch (IOException e) {
mediaPlayer=null;
}
}
}
private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.seekTo(0);
}
};
@Override
protected void onPause() {
super.onPause();
if (handler!=null){
handler.quitSynchronously();
handler=null;
}
CameraManager.get().closeDriver();
}
@Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
/**
* SurfaceHolder.Callback的三个方法
*/
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (!hasSurface){
hasSurface=true;
initCamera(holder);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface=false;
}
/**
*CaptureActivityHandler类里需要的三个方法
* handleDecode
* getViewfinderView
* drawViewfinder
*/
/**
* 处理扫描结果
* @param result
* @param barcode
*/
public void handleDecode(Result result, Bitmap barcode) {
inactivityTimer.onActivity();
playBeepSoundAndVibrate();
String resultString = result.getText();
if (resultString.equals("")) {
Toast.makeText(this, "扫描失败", Toast.LENGTH_SHORT).show();
}else {
Intent resultIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("result", resultString);
bundle.putParcelable("bitmap", barcode);
resultIntent.putExtras(bundle);
this.setResult(RESULT_OK, resultIntent);
tv.setText(resultString);
tv.setOnClickListener(this);
onPause();
}
}
private static final long VIBRATE_DURATION = 200L;
private void playBeepSoundAndVibrate() {
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
}
if (vibrate) {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATE_DURATION);
}
}
public ViewfinderView getViewfinderView() {
return viewfinderView;
}
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
/**
* DecodeHandler类里需要的方法
*/
public Handler getHandler() {
return handler;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_show:
tv.setText("");//重新扫描
initCamera(surfaceHolder);
break;
}
}
}