在github网站搜索Zxing

详见:https://github.com/yipianfengye/android-zxingLibrary

在module的build.gradle中执行compile操作

compile 'cn.yipianfengye.android:zxing-library:2.1'

在Activity或者Application onCreate()中执行初始化操作

  @Override
public void onCreate() {
super.onCreate(); ZXingLibrary.initDisplayOpinion(this);
}

添加权限:

    <uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

代码实现:

package com.loaderman.zxingdemo;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast; import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.activity.ZXingLibrary; public class MainActivity extends AppCompatActivity { private static final int REQUEST_CODE = 10;
private static final int REQUEST_IMAGE = 20; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ZXingLibrary.initDisplayOpinion(this);
findViewById(R.id.btn_create).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,CreateActviity.class)); }
});
findViewById(R.id.btn_open).setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {//集成默认的二维码扫描页面
Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
findViewById(R.id.btn_openPictrue).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {//集成对二维码图片的解析功能
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_IMAGE);
}
});
findViewById(R.id.btn_zidingyi).setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,MyZxingActviity.class));//定制化显示扫描UI
}
});
} @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE) {
//处理扫描结果(在界面上显示)
if (null != data) {
Bundle bundle = data.getExtras();
if (bundle == null) {
return;
}
if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
String result = bundle.getString(CodeUtils.RESULT_STRING);
Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
} else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
}
}
}
if (requestCode == REQUEST_IMAGE) {
if (data != null) {
Uri uri = data.getData();
ContentResolver cr = getContentResolver();
try {
Bitmap mBitmap = MediaStore.Images.Media.getBitmap(cr, uri);//显得到bitmap图片
String path = ImageUtil.getImageAbsolutePath(this, uri);
CodeUtils.analyzeBitmap(path, new CodeUtils.AnalyzeCallback() {
@Override
public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
Toast.makeText(MainActivity.this, "解析结果:" + result, Toast.LENGTH_LONG).show();
} @Override
public void onAnalyzeFailed() {
Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
}
}); if (mBitmap != null) {
mBitmap.recycle();
}
} catch (Exception e) {
e.printStackTrace(); }
}
}
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context="com.loaderman.zxingdemo.MainActivity">
<Button
android:id="@+id/btn_open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始扫描二维码"/>
<Button
android:layout_width="wrap_content"
android:id="@+id/btn_openPictrue"
android:text="打开图库解析图片二维码"
android:layout_height="wrap_content"/>
<Button
android:layout_width="wrap_content"
android:id="@+id/btn_zidingyi"
android:text="自定义布局UI扫描二维码"
android:layout_height="wrap_content"/>
<Button
android:layout_width="wrap_content"
android:id="@+id/btn_create"
android:text="生成二维码"
android:layout_height="wrap_content"/>
</LinearLayout>
package com.loaderman.zxingdemo;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore; public class ImageUtil {
/**
* 根据Uri获取图片绝对路径,解决Android4.4以上版本Uri转换
*
* @param context
* @param imageUri
*/
@TargetApi(19)
public static String getImageAbsolutePath(Context context, Uri imageUri) {
if (context == null || imageUri == null)
return null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
if (isExternalStorageDocument(imageUri)) {
String docId = DocumentsContract.getDocumentId(imageUri);
String[] split = docId.split(":");
String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(imageUri)) {
String id = DocumentsContract.getDocumentId(imageUri);
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} else if (isMediaDocument(imageUri)) {
String docId = DocumentsContract.getDocumentId(imageUri);
String[] split = docId.split(":");
String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} // MediaStore (and general)
else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(imageUri)) {
return imageUri.getLastPathSegment();
}
//return getDataColumn(context, imageUri, null, null);
return getRealPathFromUri(context, imageUri);
}
// File
else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
return imageUri.getPath();
}
return null;
} public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
String column = MediaStore.Images.Media.DATA;
String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
} public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
} /**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
} /**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
} /**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
} /**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
package com.loaderman.zxingdemo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button; import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils; public class MyZxingActviity extends AppCompatActivity {
private boolean flag = false;
private Button btnLight; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_zxing_actviity);
btnLight = (Button) findViewById(R.id.btn_light); btnLight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (flag) {
//关闭闪光灯
CodeUtils.isLightEnable(false);
flag = false;
} else {
// 打开闪光灯
flag = true;
CodeUtils.isLightEnable(true); }
}
});
findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
/**
* 执行扫面Fragment的初始化操作
*/
CaptureFragment captureFragment = new CaptureFragment();
// 为二维码扫描界面设置定制化界面
CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera); captureFragment.setAnalyzeCallback(analyzeCallback);
/**
* 替换自定义扫描控件
*/
getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
} /**
* 二维码解析回调函数
*/
CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
@Override
public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
Intent resultIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
bundle.putString(CodeUtils.RESULT_STRING, result);
resultIntent.putExtras(bundle);
MyZxingActviity.this.setResult(RESULT_OK, resultIntent);
MyZxingActviity.this.finish();
} @Override
public void onAnalyzeFailed() {
Intent resultIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
bundle.putString(CodeUtils.RESULT_STRING, "");
resultIntent.putExtras(bundle);
MyZxingActviity.this.setResult(RESULT_OK, resultIntent);
MyZxingActviity.this.finish();
}
};
}

activity_my_zxing_actviity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_my_zxing_actviity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.loaderman.zxingdemo.MyZxingActviity">
<FrameLayout
android:layout_weight="1"
android:id="@+id/fl_my_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
></FrameLayout>
<Button
android:id="@+id/btn_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="取消"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="10dp"
android:layout_gravity="bottom|center_horizontal"
/>
<Button
android:id="@+id/btn_light"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="闪光灯控制"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="10dp"
android:layout_gravity="bottom|center_horizontal"
/>
</LinearLayout>

my_camera.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<SurfaceView
android:id="@+id/preview_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<com.uuzuche.lib_zxing.view.ViewfinderView
android:id="@+id/viewfinder_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:inner_width="200dp"
app:inner_height="200dp"
app:inner_margintop="150dp"
app:inner_corner_color="#f00"
app:inner_corner_length="30dp"
app:inner_corner_width="5dp"
app:inner_scan_bitmap="@drawable/ic_launcher"
app:inner_scan_speed="10"
app:inner_scan_iscircle="false"
/> </FrameLayout>

生成二维码图片

package com.loaderman.zxingdemo;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast; import com.uuzuche.lib_zxing.activity.CodeUtils; public class CreateActviity extends AppCompatActivity { private TextView editText;
private ImageView iv;
private Bitmap mBitmap; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_actviity);
editText = (TextView) findViewById(R.id.et_text);
iv = (ImageView) findViewById(R.id.iv);
findViewById(R.id.btn_logo).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {//生成带Logo的二维码图片
String textContent = editText.getText().toString();
if (TextUtils.isEmpty(textContent)) {
Toast.makeText(CreateActviity.this, "您的输入为空!", Toast.LENGTH_SHORT).show();
return;
}
editText.setText("");
mBitmap = CodeUtils.createImage(textContent, 400, 400, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
iv.setImageBitmap(mBitmap);
}
});
findViewById(R.id.btn_no_logo).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {//生成不带logo的二维码图片
String textContent = editText.getText().toString();
if (TextUtils.isEmpty(textContent)) {
Toast.makeText(CreateActviity.this, "您的输入为空!", Toast.LENGTH_SHORT).show();
return;
}
editText.setText("");
mBitmap = CodeUtils.createImage(textContent, 400, 400, null);
iv.setImageBitmap(mBitmap);
}
}); }
}

activity_create_actviity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_create_actviity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.loaderman.zxingdemo.CreateActviity">
<EditText
android:id="@+id/et_text"
android:layout_width="match_parent"
android:text="输入要生成的二维码内容"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btn_logo"
android:text="生成带Logo的二维码"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btn_no_logo"
android:text="生成不带logo的二维码"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

效果图:

Zxing二维码的集成使用的更多相关文章

  1. 程序猿媛 九:Adroid zxing 二维码3.1集成(源码无删减)

    Adroid zxing 二维码3.1集成 声明:博文为原创,文章内容为,效果展示,思路阐述,及代码片段. 转载请保留原文出处“http://my.oschina.net/gluoyer/blog”, ...

  2. Android项目实战(二十八):Zxing二维码实现及优化

    前言: 多年之前接触过zxing实现二维码,没想到今日项目中再此使用竟然使用的还是zxing,百度之,竟是如此牛的玩意. 当然,项目中我们也许只会用到二维码的扫描和生成两个功能,所以不必下载完整的ja ...

  3. Android之Zxing二维码扫描图片拉伸

    还是这个接手项目,二维码扫描集成的是zxing,扫描界面的图像有明显的拉伸变形. 这种问题,根据以往的经验,一般是x,y轴错位引起的,处理好x,y轴的问题,一般可以解决问题. 由于这个问题,之前有很多 ...

  4. (转载)Android项目实战(二十八):Zxing二维码实现及优化

    Android项目实战(二十八):Zxing二维码实现及优化   前言: 多年之前接触过zxing实现二维码,没想到今日项目中再此使用竟然使用的还是zxing,百度之,竟是如此牛的玩意. 当然,项目中 ...

  5. Atitit zxing二维码qr码识别解析

    Atitit zxing二维码qr码识别解析 1.1. qr码识别解析 by zxing1 1.2. 解码lib:qrcode.jar  2 1.3. atitit.二维码生成总结java zxing ...

  6. 谷歌zxing 二维码生成工具

    一.加入maven依赖 <!-- 谷歌zxing 二维码 --> <dependency> <groupId>com.google.zxing</groupI ...

  7. Android项目实战(四十四):Zxing二维码切换横屏扫描

    原文:Android项目实战(四十四):Zxing二维码切换横屏扫描 Demo链接 默认是竖屏扫描,但是当我们在清单文件中配置横屏显示的时候: <activity android:name=&q ...

  8. android开发之集成zxing,二维码,以及扫描二维码的功能实现。带源代码下载

    package cc.jiusansec.www; import com.google.zxing.WriterException; import com.zxing.activity.Capture ...

  9. zxing 二维码扫描 配置和使用

    本文转载至 http://blog.csdn.net/a6472953/article/details/8796501   二维码扫描使用最多的主要有两个库:zbarSDK 和zxing 关于zbar ...

随机推荐

  1. IDEA打开光标是粗黑色,backspace键、insert键点击无效的解决办法

    问题描述:打开IDEA的编译器之后,界面显示的光标变粗,点击backspace键和insert键盘之后无效 解决方法:打开File——Settings——Plugins,在右侧的搜索栏中搜索IdeaV ...

  2. WebAPI跨域问题处理

    1.按照https://dzone.com/articles/access-control-allow-origin-header-and-the-aspnet文章所述,在程序中配置允许跨域请求. 但 ...

  3. pat (B)_1002

    1002 写出这个数 (20 分) 读入一个正整数 n,计算其各位数字之和,用汉语拼音写出和的每一位数字. 输入格式: 每个测试输入包含 1 个测试用例,即给出自然数 n 的值.这里保证 n 小于 1 ...

  4. 屏蔽iOS升级方法

    1.iPhone或者iPad使用safari浏览器打开http://d.updater.i4.cn/i4tools7/temp/tvos.mobileconfig 2.点击[允许] 3.进入[通用]- ...

  5. Vue多页面 按钮级别权限控制 directive指令控制

    利用driective 构建自己的指令,实现按钮级别权限 项目结构如下: 修改router.js { path: 'schools', name: '列表', component: () => ...

  6. super运行错误解决方法

    自己实践: 要是下面的不成功,可能的原因是: 目录/var/log/supervisor//var/log/supervisor/ /var/log/supervisor/ /var/log/supe ...

  7. .NET界面控件DevExpress全新发布v19.1.5|改进Office 2019主题

    DevExpress Universal Subscription(又名DevExpress宇宙版或DXperience Universal Suite)是全球使用广泛的.NET用户界面控件套包,De ...

  8. html中删除表格的一行(有弹窗)

    html中删除表格一行其实很简单,但是加上一个提示弹窗后,点击确定后却获取不到要删除的是哪一行,下面是一个demo html: <tr> <td> <input type ...

  9. Android APK 手动签名

    首先,如果没有签名密钥,先生成密钥: keytool -genkey -alias android.keystore -keyalg RSA -validity 20000 -keystore and ...

  10. qt5-QPushButton按钮

    Win::Win(QWidget *parent) //构造函数体 : QWidget(parent) //执行父类初始化操作 { //创建按钮方式一 ,);//重置窗口大小 this->set ...