Android二維碼掃描的解決方案,都是基于Google的zxing,網(wǎng)上一些主流的開源庫,主要分為有兩種方式。
- android-zxingLibrary,自定義控件方式,優(yōu)點(diǎn)集成方便,缺點(diǎn)是過度封裝,在兼容Android版本上存在問題,例如開啟攝像頭、閃光燈API變更時,或者UI定制化時,需要修改源碼,不方便。
- ZXingProject,在zxing基礎(chǔ)上進(jìn)行精簡,缺點(diǎn)是沒有封裝,Activity、UI、業(yè)務(wù)邏輯、資源文件耦合性高,代碼移植不便。
功能分析
- 在 ZXingProject 的基礎(chǔ)上,封裝一個二維碼掃描的 jar 包。
- 攝像頭掃描二維碼
- 相冊掃描二維碼
- 閃光燈的開啟關(guān)閉
其中攝像頭、相冊、閃光燈等 API 等調(diào)用放在項(xiàng)目中,不去污染 Library 庫,使 Library 具有更強(qiáng)的適用性。
封裝 Library
1. 分析現(xiàn)有工程
先看下 ZXingProject 的項(xiàng)目結(jié)構(gòu)。

- 藍(lán)色框的 jar 包移除,使用遠(yuǎn)程倉庫的
com.google.zxing:core:3.3.3代替,便于后期zxing核心包的更新替換。 - 紅色框的 Activity 移除,不應(yīng)放在我們的 Library 中,移到項(xiàng)目中。
- 綠色框的 BeepManager 是掃描成功蜂鳴聲,為了擴(kuò)展,移到項(xiàng)目中。
2. 移除 Library 冗余代碼
下面是移除后的代碼結(jié)構(gòu)。

移除 CaptureActivity 后,CaptureActivityHandler 和 DecodeHandler 相關(guān)代碼會報(bào)錯,新增 Constants ,CaptureCallback 兩個接口。
ZXingProject 中 Handler 的 what 是控件 id,這里使用 Constants 中定義的常量替代 。
public interface Constants {
int DECODE = 10001;
int DECODE_FAILED = 10002;
int DECODE_SUCCEEDED = 10003;
int QUIT = 10004;
int RESTART_PREVIEW = 10005;
int RETURN_SCAN_RESULT = 10006;
}
使用接口 CaptureCallback 解藕 ZXingProject 中的 CaptureActivity。
public interface CaptureCallback {
Rect getCropRect();// 獲取矩形
Handler getHandler();// 獲取Handler
CameraManager getCameraManager();// 獲取CameraManager
/**
* 掃碼成功之后回調(diào)的方法
*
* @param result
* @param bundle
*/
void handleDecode(Result result, Bundle bundle);
/**
* {@link android.app.Activity#setResult(int, Intent)}
*
* @param resultCode The result code to propagate back to the originating
* activity, often RESULT_CANCELED or RESULT_OK
* @param data The data to propagate back to the originating activity.
*/
void setResult(int resultCode, Intent data);
/**
* {@link android.app.Activity#finish()}
*/
void finish();
}
運(yùn)行時權(quán)限
需要兩組權(quán)限,攝像頭和內(nèi)部存儲。
// 獲得運(yùn)行時權(quán)限
private void getRuntimePermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String[] perms = {Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (checkSelfPermission(perms[0]) == PackageManager.PERMISSION_DENIED
|| checkSelfPermission(perms[1]) == PackageManager.PERMISSION_DENIED) {
requestPermissions(perms, 200);
} else {
jumpScanPage();
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
switch (requestCode) {
case 200: {
for (int i : grantResults) {
if (i == PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "權(quán)限拒絕", Toast.LENGTH_SHORT).show();
return;
}
}
jumpScanPage();
break;
}
}
}
項(xiàng)目集成
攝像頭掃描二維碼
1. 掃描界面保持屏幕常亮
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_capture);
}
2. 掃描動畫
選擇屬性動畫,原因是可以暫停,方便在 onResume 和 onPause 處理。
private void initScan() {
ImageView scanLine = findViewById(R.id.scan_line);
// 掃描線性動畫(屬性動畫可暫停)
float curTranslationY = scanLine.getTranslationY();
objectAnimator = ObjectAnimator.ofFloat(scanLine, "translationY",
curTranslationY, Utils.dp2px(this, 170));
// 動畫持續(xù)的時間
objectAnimator.setDuration(4000);
// 線性動畫 Interpolator 勻速
objectAnimator.setInterpolator(new LinearInterpolator());
// 動畫重復(fù)次數(shù)
objectAnimator.setRepeatCount(ObjectAnimator.INFINITE);
// 動畫如何重復(fù),從下到上,還是重新開始從上到下
objectAnimator.setRepeatMode(ValueAnimator.RESTART);
}
3. 開始掃描
private void startScan() {
inactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this);
if (isPause) {
// 如果是暫停,掃描動畫應(yīng)該要暫停
objectAnimator.resume();
isPause = false;
} else {
// 開始掃描動畫
objectAnimator.start();
}
// 初始化相機(jī)管理
cameraManager = new CameraManager(this);
handler = null; // 重置handler
if (isHasSurface) {
initCamera(scanPreview.getHolder());
} else {
// 等待surfaceCreated來初始化相機(jī)
scanPreview.getHolder().addCallback(this);
}
// 開啟計(jì)時器
if (inactivityTimer != null) {
inactivityTimer.onResume();
}
}
4. 初始化 SurfaceView
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e("netease >>> ", "SurfaceHolder is null");
return;
}
if (!isHasSurface) {
isHasSurface = true;
initCamera(holder);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
isHasSurface = false;
}
5. 暫停掃描
由于相機(jī)、動畫、記時器都是消耗性能的,需要在 onPause 中進(jìn)行釋放處理,同樣在 onResume 中執(zhí)行 startScan()。
private void pauseScan() {
if (handler != null) {
// handler退出同步并置空
handler.quitSynchronously();
handler = null;
}
// 計(jì)時器的暫停
if (inactivityTimer != null) {
inactivityTimer.onPause();
}
// 關(guān)閉蜂鳴器
beepManager.close();
// 關(guān)閉相機(jī)管理器驅(qū)動
cameraManager.closeDriver();
if (!isHasSurface) {
// remove等待
scanPreview.getHolder().removeCallback(this);
}
// 動畫暫停
objectAnimator.pause();
isPause = true;
}
6. 初始化相機(jī)
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("SurfaceHolder is null");
}
if (cameraManager.isOpen()) {
Log.e(TAG, "surfaceCreated: camera is open");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
if (handler == null) {
handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
}
initCrop();
} catch (IOException ioe) {
Log.w(TAG, ioe);
Utils.displayFrameworkBugMessageAndExit(this);
} catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.lang.RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
Utils.displayFrameworkBugMessageAndExit(this);
}
}
7. 繪制掃描框矩形
private void initCrop() {
// 獲取相機(jī)的寬高
int cameraWidth = cameraManager.getCameraResolution().y;
int cameraHeight = cameraManager.getCameraResolution().x;
// 獲取布局中掃描框的位置信息
int[] location = new int[2];
scanCropView.getLocationInWindow(location);
int cropLeft = location[0];
int cropTop = location[1] - Utils.getStatusBarHeight(this);
// 獲取截取的寬高
int cropWidth = scanCropView.getWidth();
int cropHeight = scanCropView.getHeight();
// 獲取布局容器的寬高
int containerWidth = scanContainer.getWidth();
int containerHeight = scanContainer.getHeight();
// 計(jì)算最終截取的矩形的左上角頂點(diǎn)x坐標(biāo)
int x = cropLeft * cameraWidth / containerWidth;
// 計(jì)算最終截取的矩形的左上角頂點(diǎn)y坐標(biāo)
int y = cropTop * cameraHeight / containerHeight;
// 計(jì)算最終截取的矩形的寬度
int width = cropWidth * cameraWidth / containerWidth;
// 計(jì)算最終截取的矩形的高度
int height = cropHeight * cameraHeight / containerHeight;
// 生成最終的截取的矩形
mCropRect = new Rect(x, y, width + x, height + y);
}
8. 掃描成功的回調(diào)
@Override
public void handleDecode(Result result, Bundle bundle) {
// 掃碼成功之后回調(diào)的方法
if (inactivityTimer != null) {
inactivityTimer.onActivity();
}
// 播放蜂鳴聲
beepManager.playBeepSoundAndVibrate();
// 將掃碼的結(jié)果返回到MainActivity
Intent intent = new Intent();
intent.putExtra(Utils.BAR_CODE, result.getText());
Utils.setResultAndFinish(CaptureActivity.this, RESULT_OK, intent);
}
相冊掃描二維碼
// 跳轉(zhuǎn)到圖片選擇
public static void openAlbum(Activity activity) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
activity.startActivityForResult(intent, SELECT_PIC_KITKAT);
} else {
activity.startActivityForResult(intent, SELECT_PIC);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
// 相冊返回
if (requestCode == Utils.SELECT_PIC_KITKAT // 4.4及以上圖庫
&& resultCode == Activity.RESULT_OK) {
new Thread(new Runnable() {
@Override
public void run() {
showProgressDialog();
Uri uri = data.getData();
String path = Utils.getPath(CaptureActivity.this, uri);
Result result = Utils.scanningImage(path);
Intent intent = new Intent();
if (result == null) {
intent.putExtra(Utils.BAR_CODE, "未發(fā)現(xiàn)二維碼/條形碼");
} else {
// 數(shù)據(jù)返回
intent.putExtra(Utils.BAR_CODE, Utils.recode(result.getText()));
}
Utils.setResultAndFinish(CaptureActivity.this, RESULT_OK, intent);
dismissProgressDialog();
}
}).start();
}
}
閃光燈
final TextView tvLight = findViewById(R.id.tv_light);
ToggleButton tbLight = findViewById(R.id.tb_light);
// 閃光燈控制
tbLight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
tvLight.setText("關(guān)燈");
Utils.openFlashlight(cameraManager);
} else {
tvLight.setText("開燈");
Utils.closeFlashlight();
}
}
});
生成 jar 包
調(diào)試完畢最后,需要將 Library 生成 jar,在 build.gradle 中增加 makeJar 任務(wù)。
apply plugin: 'com.android.library'
android {
compileSdkVersion 28
defaultConfig {
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
task makeJar(type: Copy) {
// 刪除存在的
delete 'build/libs/zxing.jar'
// 設(shè)置拷貝的文件
from('build/intermediates/packaged-classes/release/')
// 打進(jìn)jar包后的文件目錄
into('build/libs/')
// 將classes.jar放入build/libs/目錄下
// include ,exclude參數(shù)來設(shè)置過濾
//(我們只關(guān)心classes.jar這個文件)
include('classes.jar')
// 重命名
rename('classes.jar', 'zxing.jar')
}
makeJar.dependsOn(build)
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.google.zxing:core:3.3.3'
}
最后在 AS 右側(cè)的 Gradle 中運(yùn)行 makeJar ,就可以看到生成的 build/libs/zxing.jar了。


DONE
完工,這個 jar 包可以集成到多個項(xiàng)目的二維碼掃描,不會對項(xiàng)目造成污染,并且將攝像頭,相冊,閃光燈,蜂鳴聲,UI等抽離,擴(kuò)展性強(qiáng)。