Android之不须要自己定义View(ViewfindView.java)最简单的二维码扫描
不废话,先爆照
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
第一步:
看下我项目里面的类结构
第二步:
<uses-permission android:name="android.permission.CALL_PHONE"/>
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<!--加入扫一扫二维码的权限-->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" /> <uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" /> <uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
第三步:介绍相关类
第四步:
/*
* 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.dtr.zxing.activity; import java.io.IOException;
import java.lang.reflect.Field; import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout; import com.dtr.zxing.camera.CameraManager;
import com.dtr.zxing.decode.DecodeThread;
import com.dtr.zxing.utils.BeepManager;
import com.dtr.zxing.utils.CaptureActivityHandler;
import com.dtr.zxing.utils.InactivityTimer;
import com.google.zxing.Result;
import com.kuyu.kuyucontact.R; /**
* 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 CameraManager cameraManager;
private CaptureActivityHandler handler;
private InactivityTimer inactivityTimer;
private BeepManager beepManager; private SurfaceView scanPreview = null;
private RelativeLayout scanContainer;
private RelativeLayout scanCropView;
private ImageView scanLine; private Rect mCropRect = null; public Handler getHandler() {
return handler;
} public CameraManager getCameraManager() {
return cameraManager;
} private boolean isHasSurface = false; @Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle); Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_capture); scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
scanContainer = (RelativeLayout) findViewById(R.id.capture_container);
scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);
scanLine = (ImageView) findViewById(R.id.capture_scan_line); inactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this); TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT,
0.9f);
animation.setDuration(4500);
animation.setRepeatCount(-1);
animation.setRepeatMode(Animation.RESTART);
scanLine.startAnimation(animation);
} @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()); handler = null; if (isHasSurface) {
// The activity was paused but not stopped, so the surface still
// exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(scanPreview.getHolder());
} else {
// Install the callback and wait for surfaceCreated() to init the
// camera.
scanPreview.getHolder().addCallback(this);
} inactivityTimer.onResume();
} @Override
protected void onPause() {
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
beepManager.close();
cameraManager.closeDriver();
if (!isHasSurface) {
scanPreview.getHolder().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 (!isHasSurface) {
isHasSurface = true;
initCamera(holder);
}
} @Override
public void surfaceDestroyed(SurfaceHolder holder) {
isHasSurface = 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 bundle
* The extras
*/
public void handleDecode(Result rawResult, Bundle bundle) {
inactivityTimer.onActivity();
beepManager.playBeepSoundAndVibrate(); bundle.putInt("width", mCropRect.width());
bundle.putInt("height", mCropRect.height());
bundle.putString("result", rawResult.getText()); startActivity(new Intent(CaptureActivity.this, ResultActivity.class).putExtras(bundle));
} 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, cameraManager, DecodeThread.ALL_MODE);
} initCrop();
} 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() {
// camera error
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage("相机打开出错,请稍后重试");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog, int which) {
finish();
} });
builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override
public void onCancel(DialogInterface dialog) {
finish();
}
});
builder.show();
} public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
}
} public Rect getCropRect() {
return mCropRect;
} /**
* 初始化截取的矩形区域
*/
private void initCrop() {
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] - getStatusBarHeight(); int cropWidth = scanCropView.getWidth();
int cropHeight = scanCropView.getHeight(); /** 获取布局容器的宽高 */
int containerWidth = scanContainer.getWidth();
int containerHeight = scanContainer.getHeight(); /** 计算终于截取的矩形的左上角顶点x坐标 */
int x = cropLeft * cameraWidth / containerWidth;
/** 计算终于截取的矩形的左上角顶点y坐标 */
int y = cropTop * cameraHeight / containerHeight; /** 计算终于截取的矩形的宽度 */
int width = cropWidth * cameraWidth / containerWidth;
/** 计算终于截取的矩形的高度 */
int height = cropHeight * cameraHeight / containerHeight; /** 生成终于的截取的矩形 */
mCropRect = new Rect(x, y, width + x, height + y);
} private int getStatusBarHeight() {
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
return getResources().getDimensionPixelSize(x);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
ResulutActivity.java类
package com.dtr.zxing.activity; import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.TypedValue;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView; import com.dtr.zxing.decode.DecodeThread;
import com.kuyu.kuyucontact.R; public class ResultActivity extends Activity { private ImageView mResultImage;
private TextView mResultText; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result); Bundle extras = getIntent().getExtras(); mResultImage = (ImageView) findViewById(R.id.result_image);
mResultText = (TextView) findViewById(R.id.result_text); if (null != extras) {
int width = extras.getInt("width");
int height = extras.getInt("height"); LayoutParams lps = new LayoutParams(width, height);
lps.topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, getResources().getDisplayMetrics());
lps.leftMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics());
lps.rightMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics()); mResultImage.setLayoutParams(lps); String result = extras.getString("result");
mResultText.setText(result); Bitmap barcode = null;
byte[] compressedBitmap = extras.getByteArray(DecodeThread.BARCODE_BITMAP);
if (compressedBitmap != null) {
barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null);
// Mutable copy:
barcode = barcode.copy(Bitmap.Config.RGB_565, true);
} mResultImage.setImageBitmap(barcode);
}
}
}
资源文件
Android之不须要自己定义View(ViewfindView.java)最简单的二维码扫描的更多相关文章
- android利用zbar二维码扫描-(解决中文乱码及扫描区域定义)
写在最前(这是对上一篇博文的问题做的更新[android利用zbar二维码扫描]) project下载 zbarLib编译project project下载0积分 bug 在2.3的系统中Hol ...
- Android自由行之走进zxing,轻松实现二维码扫描
现在很多App都集成了扫一扫功能,最常用的微信.QQ.手机助手等.二维码也使得生活变得更加简洁,扫一扫订餐.扫一扫下载等等.那么,说到二维码,我们不得不提Google一个开源的扫码框架:zxing. ...
- Android 二维码扫描/生成
先看看实现效果 1.在module的build.gradle中执行compile操作 compile 'cn.yipianfengye.android:zxing-library:2.2' 2.在Ap ...
- Android高级控件(三)—— 使用Google ZXing实现二维码的扫描和生成相关功能体系
Android高级控件(三)-- 使用Google ZXing实现二维码的扫描和生成相关功能体系 摘要 如今的二维码可谓是烂大街了.到处都是二维码.什么都是二维码,扫一扫似乎已经流行到习以为常了,今天 ...
- Android集成二维码扫描功能
文章转载自 https://github.com/yipianfengye/android-zxingLibrary 在具体介绍该扫描库之前我们先看一下其具体的使用方式,看看是不是几行代码就可以集成 ...
- Android仿微信二维码扫描
转载:http://blog.csdn.net/xiaanming/article/details/10163203 了解二维码这个东西还是从微信中,当时微信推出二维码扫描功能,自己感觉挺新颖的,从一 ...
- Android 基于google Zxing实现二维码、条形码扫描,仿微信二维码扫描效果
Android 高手进阶(21) 版权声明:本文为博主原创文章,未经博主允许不得转载. 转载请注明出处:http://blog.csdn.net/xiaanming/article/detail ...
- android 二维码扫描
了解二维码这个东西还是从微信 中,当时微信推出二维码扫描功能,自己感觉挺新颖的,从一张图片中扫一下竟然能直接加好友,不可思议啊,那时候还不了解二维码,呵呵,然后做项目的时候, 老板说要加上二维码扫描功 ...
- 【转】Android手机客户端关于二维码扫描的源码--不错
原文网址:https://github.com/SkillCollege/QrCodeScan QrCodeScan 这是Android手机客户端关于二维码扫描的源码,使用了高效的ZBar解码库,并修 ...
随机推荐
- oracle导入TYPE对象报错ORA-02304
Type是我们经常使用的数据库对象结构.我们在实际中,可以单独定义type类型,之后在PL/SQL代码或者数据表中使用. 在一个偶然的机会让笔者发现使用Type类型在数据exp/imp中的麻烦.当我们 ...
- 如何部署Java_web项目到云服务器上
步骤 1:购买 Linux 实例(略) 步骤2:安装JDK 本节介绍如何安装java jdk. 软件包中包含的软件及版本如下: Tomcat:1.8.0_121 说明:这是写文档时参考的软件版本.您下 ...
- Makefile持续学习二
Makefile概述 一.Makefile里有什么? Makefile里主要包含5个东西:显式规则.隐晦规则.变量定义.文件指示和注释 1.显式规则:显式规则说明如恶化生成一个或多的目标文件,包含要生 ...
- SpringMVC---CookieValue
配置文件承接一二章 @CookieValue的作用 用来获取Cookie中的值 1.value:参数名称 2.required:是否必须 3.defaultValue:默认值 原网址:https:// ...
- (11.20)Java小知识!
经过一段时间的学习,我也终于来到了Java语言的核心篇,也就是对象与类的学习,今天想要和大家分享的是关于类的小知识点. 1.类的声明: 类可以看成创建Java对象的模板.类亦可以理解成Java一种 ...
- canvas图表(3) - 饼图
原文地址:canvas图表(3) - 饼图 这几天把canvas图表都优化了下,动画效果更加出色了,可以说很逼近echart了.刚刚写完的饼图,非常好的实现了既定的功能,交互的动画效果也是很棒的. 效 ...
- spring装配Bean过程
主要流程: 1.读取配置文件 2.实例化bean和填充bean属性 这个粗略的流程感觉更像是一个需求,有了这个需求,那么spring内部是怎么处理的呢? 我们知道spring的两个核心接口BeanFa ...
- P1457 城堡 The Castle
轻度中毒 原题 :The Castle 以下为题解部分:明明辣么简单的一道题,硬是搞了1.5h,WTF?以下列出本题的一些要点. 搜索(DFS)嘛,染色嘛,统计大小嘛,很容易想,也很更易处理. 接下来 ...
- 虚拟机Ubuntu无法上网问题解决过程
查看了网上大部分经验贴,都没有解决问题,只好自己思考琢磨,以下是思考解决过程 1.查看文件配置 2.查看虚拟机网络配置方式 3.查看硬件驱动是否存在 4.配置完文件ifcfg-eth0后重启,无效(虚 ...
- selenium定位tr及td,并获取其文本及属性
#获取所有的trtrlist=brower.find_elements_by_tag_name("tr")for tr in trlist: #获取tr中的所有td tdlist= ...