android扫描二维码(zxing)附带小例子
16lz
2021-12-04
android扫描二维码(zxing)附带小例子
开发android二维码的功能基本上是必须的了。下面的android小程序,主要实现了这样的一个功能,扫描二维码,然后把二维码内容和当时取得照片读出来。 首先需要的是zxing的下载包,这里使用的是3.1.0的下载地址:下载完整版官方例子程序。 参考android的程序,新建一个自己的小例子,把扫描的主要功能实现。这是程序的目录截图:这里仅仅列出主要的代码: MainActivity.java
package com.example.administrator.scanoo;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;import org.w3c.dom.Text;public class MainActivity extends AppCompatActivity { private Button button; private TextView textView; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) this.findViewById(R.id.button1); textView = (TextView)this.findViewById(R.id.scanResult); imageView = (ImageView)this.findViewById(R.id.scanimage); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, CaptureActivity.class); startActivityForResult(intent, 0x123); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == 0x123 && resultCode==0x345){ if(data != null){ textView.setText("扫描结果:\n" + data.getStringExtra("resultCode")); imageView.setImageBitmap(TransData.bitmap); } } }}
CaptureActivity.java
/* * Copyright (C) 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.example.administrator.scanoo;import android.app.Activity;import android.app.AlertDialog;import android.content.Intent;import android.content.pm.ActivityInfo;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Paint;import android.os.Bundle;import android.os.Handler;import android.preference.PreferenceManager;import android.util.Log;import android.view.SurfaceHolder;import android.view.SurfaceView;import android.view.Window;import android.view.WindowManager;import android.widget.TextView;import android.widget.Toast;import com.google.zxing.BarcodeFormat;import com.google.zxing.DecodeHintType;import com.google.zxing.Result;import com.google.zxing.ResultPoint;import com.google.zxing.client.android.AmbientLightManager;import com.google.zxing.client.android.BeepManager;import com.google.zxing.client.android.CaptureActivityHandler;import com.google.zxing.client.android.FinishListener;import com.google.zxing.client.android.InactivityTimer;import com.google.zxing.client.android.ViewfinderView;import com.google.zxing.client.android.camera.CameraManager;import java.io.IOException;import java.util.Collection;import java.util.Map;/** * This activity opens the camera and does the actual scanning on a background * thread. It draws a viewfinder to help the user place the barcode correctly, * shows feedback as the image processing is happening, and then overlays the * results when a scan is successful. * * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen */public final class CaptureActivity extends Activity implements SurfaceHolder.Callback { private static final String TAG = CaptureActivity.class.getSimpleName(); private static final long BULK_MODE_SCAN_DELAY_MS = 1000L; private CameraManager cameraManager; private CaptureActivityHandler handler; private ViewfinderView viewfinderView; private boolean hasSurface; private Collection decodeFormats; private Map decodeHints; private String characterSet; private InactivityTimer inactivityTimer; private BeepManager beepManager; private AmbientLightManager ambientLightManager; public ViewfinderView getViewfinderView() { return viewfinderView; } public Handler getHandler() { return handler; } public CameraManager getCameraManager() { return cameraManager; } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.capture); hasSurface = false; inactivityTimer = new InactivityTimer(this); beepManager = new BeepManager(this); ambientLightManager = new AmbientLightManager(this); PreferenceManager.setDefaultValues(this, R.xml.preferences, false); } @Override protected void onResume() { super.onResume(); // CameraManager must be initialized here, not in onCreate(). This is // necessary because we don't // want to open the camera driver and measure the screen size if we're // going to show the help on // first launch. That led to bugs where the scanning rectangle was the // wrong size and partially // off screen. cameraManager = new CameraManager(getApplication()); viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view); viewfinderView.setCameraManager(cameraManager); handler = null; //设置横屏竖屏 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view); SurfaceHolder surfaceHolder = surfaceView.getHolder(); if (hasSurface) { // The activity was paused but not stopped, so the surface still // exists. Therefore // surfaceCreated() won't be called, so init the camera here. initCamera(surfaceHolder); } else { // Install the callback and wait for surfaceCreated() to init the // camera. surfaceHolder.addCallback(this); } beepManager.updatePrefs(); ambientLightManager.start(cameraManager); inactivityTimer.onResume(); decodeFormats = null; characterSet = null; } @Override protected void onPause() { if (handler != null) { handler.quitSynchronously(); handler = null; } inactivityTimer.onPause(); ambientLightManager.stop(); beepManager.close(); cameraManager.closeDriver(); if (!hasSurface) { SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view); SurfaceHolder surfaceHolder = surfaceView.getHolder(); surfaceHolder.removeCallback(this); } super.onPause(); } @Override protected void onDestroy() { inactivityTimer.shutdown(); super.onDestroy(); } @Override public void surfaceCreated(SurfaceHolder holder) { if (holder == null) { Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!"); } if (!hasSurface) { hasSurface = true; initCamera(holder); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { hasSurface = false; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } /** * A valid barcode has been found, so give an indication of success and show * the results. * * @param rawResult The contents of the barcode. * @param scaleFactor amount by which thumbnail was scaled * @param barcode A greyscale bitmap of the camera data which was decoded. */ public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) { inactivityTimer.onActivity(); boolean fromLiveScan = barcode != null; if (fromLiveScan) { // Then not from history, so beep/vibrate and we have an image to // draw on beepManager.playBeepSoundAndVibrate(); Toast.makeText(CaptureActivity.this, rawResult.getText(), Toast.LENGTH_SHORT).show(); //开启下面的能够进行持续扫描// restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS); Intent intent = new Intent(); intent.putExtra("resultCode",rawResult.getText()); TransData.bitmap = barcode; setResult(0x345,intent); finish(); } } private void initCamera(SurfaceHolder surfaceHolder) { if (surfaceHolder == null) { throw new IllegalStateException("No SurfaceHolder provided"); } if (cameraManager.isOpen()) { Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?"); return; } try { cameraManager.openDriver(surfaceHolder); // Creating the handler starts the preview, which can also throw a // RuntimeException. if (handler == null) { handler = new CaptureActivityHandler(this, decodeFormats, decodeHints, characterSet, cameraManager); } } catch (IOException ioe) { Log.w(TAG, ioe); displayFrameworkBugMessageAndExit(); } 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); displayFrameworkBugMessageAndExit(); } } private void displayFrameworkBugMessageAndExit() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.app_name)); builder.setMessage(getString(R.string.msg_camera_framework_bug)); builder.setPositiveButton(R.string.button_ok, new FinishListener(this)); builder.setOnCancelListener(new FinishListener(this)); builder.show(); } public void restartPreviewAfterDelay(long delayMS) { if (handler != null) { handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS); } } public void drawViewfinder() { viewfinderView.drawViewfinder(); }}
TransData.java
package com.example.administrator.scanoo;import android.graphics.Bitmap;/** * Created by Administrator on 2016/9/19. *///防止图片过大,不能进行界面间传递public class TransData { public static Bitmap bitmap;}
布局: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
capture.xml
<?xml version="1.0" encoding="UTF-8"?>
运行效果截图:
最后,附上整个代码:点我下载,不要你的积分噢!
更多相关文章
- Android(安卓)线程超时的例子
- Android新控件MotionLayout介绍(三)
- Android(安卓)支持的 media 文件格式--MediaFile
- Android(安卓)AIDL例子
- android 安装文件例子
- Android开发便签2:Activity的生命周期
- Android(安卓)类菜单栏 以及 透明居中排列
- Android第七期 - 二维码扫描与生成图
- android生命周期的例子