android使用zxing实现扫码功能并附上demo
时间: 2023-11-13 14:05:35 浏览: 222
好的,下面是Android使用zxing库实现扫码功能的示例代码:
1. 首先添加zxing库依赖,在app的build.gradle文件中添加以下代码:
```
implementation 'com.google.zxing:core:3.4.0'
implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
```
2. 在需要使用扫码功能的Activity中添加以下代码:
```java
public class ScanActivity extends AppCompatActivity {
private static final int REQUEST_CODE_SCAN = 0x0000; // 扫码请求码
private static final String DECODED_CONTENT_KEY = "codedContent"; // 扫码结果key
private CaptureManager captureManager; // ZXing扫码管理器
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
// 初始化ZXing扫码管理器
captureManager = new CaptureManager(this, (DecoratedBarcodeView) findViewById(R.id.zxing_barcode_scanner));
captureManager.initializeFromIntent(getIntent(), savedInstanceState);
captureManager.decode();
}
@Override
protected void onResume() {
super.onResume();
captureManager.onResume();
}
@Override
protected void onPause() {
super.onPause();
captureManager.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
captureManager.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return captureManager.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
/**
* 扫码结果回调方法
*/
public void onScanResult(String result) {
Intent intent = new Intent();
intent.putExtra(DECODED_CONTENT_KEY, result);
setResult(RESULT_OK, intent);
finish();
}
/**
* 启动扫码界面
*/
public static void start(Activity activity) {
Intent intent = new Intent(activity, ScanActivity.class);
activity.startActivityForResult(intent, REQUEST_CODE_SCAN);
}
/**
* 获取扫码结果
*/
public static String getScanResult(Intent data) {
return data.getStringExtra(DECODED_CONTENT_KEY);
}
}
```
3. 在布局文件中添加zxing扫码控件:
```xml
<com.journeyapps.barcodescanner.CaptureDecoratedBarcodeView
android:id="@+id/zxing_barcode_scanner"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:zxing_use_texture_view="true"
app:zxing_framing_rect_height="240dp"
app:zxing_framing_rect_width="240dp"
app:zxing_preview_scaling_strategy="fitCenter" />
```
4. 在需要使用扫码功能的地方调用`ScanActivity.start(this)`方法启动扫码界面,并在`onActivityResult`方法中获取扫码结果:
```java
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ScanActivity.REQUEST_CODE_SCAN && resultCode == RESULT_OK && data != null) {
String result = ScanActivity.getScanResult(data); // 获取扫码结果
// 处理扫码结果
}
}
```
至此,Android使用zxing实现扫码功能的示例代码就完成了。完整的示例代码可以在以下链接中找到:
https://github.com/zxing/zxing/tree/master/android/sample-app
阅读全文