//参数:(String str, int widthAndHeight)
Bitmap bitmap = EncodingHandler.createQRCode(str, 300);
iv.setImageBitmap(bitmap);
//开启扫描界面
Intent intent = new Intent(context, CaptureActivity.class);
startActivityForResult(intent, 0);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 0) {
//获取扫描的数据
String result = data.getExtras().getString("result");
tv.setText(result);
}
}
1 zxing.jar
2 zxing下的类
3 res下的文件
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<activity
android:name="com.zxing.activity.CaptureActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="stateAlwaysHidden" >
activity>
结构图:
需要复制的文件:
public class MainActivity extends Activity {
private Context context;
private TextView tv;
private ImageView iv;
private Button btn2;
private EditText et;
private String str;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
scan();// 扫描二维码并显示结果
generate();
}
public void generate() {
iv = (ImageView) findViewById(R.id.iv);
btn2 = (Button) findViewById(R.id.btn2);
et = (EditText) findViewById(R.id.et);
et.addTextChangedListener(new TextWatcher() {
private String str2;
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
str2 = s.toString();
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (TextUtils.isEmpty(str2)) {
Toast.makeText(context, "请输入内容", 0).show();
} else {
try {
Bitmap bitmap = EncodingHandler.createQRCode(
str2, 300);
iv.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
}
});
}
});
}
public void scan() {
tv = (TextView) findViewById(R.id.tv);
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, CaptureActivity.class);
startActivityForResult(intent, 0);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
String result = data.getExtras().getString("result");
tv.setText(result);
}
}
}
点击下载源码
上面的Demo只涉及二维码,而且还有导入各种文件,为了方便,抽取相关代码做成了libary。这个Demo比较全面,涉及一维码和二维码的生成+扫描,AS项目,zxingLibrary是library,作为module的依赖库。使用的时候导入zxingLibrary,将其添加为你module的library,然后调用生成一二维码和扫描的方法即可。
生成一维码和二维码都是类BarCodeUtil完成的
方法 | 意义 |
---|---|
bitmap1(String s) | 生成一维码的bitmap |
bitmap2(String s) | 生成二维码的bitmap |
在生成一维码和二维码的时候,需要传入宽高,这个宽高作为维码图片的宽高,这样我们就可以自定义维码的宽高。
//设置一维码和二维码宽高
int width = wm.getDefaultDisplay().getWidth();
int height = wm.getDefaultDisplay().getHeight();
util = new BarCodeUtil(width * 2 / 3, height / 4);
//扫码:
Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
startActivityForResult(intent, 0);
//获取扫码结果
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 0) {
String result = data.getExtras().getString("result");
tv1.setText(result);
}
}
/**
* 利用zxing.jar实现一维码和二维码 的生成和扫描
*/
public class MainActivity extends AppCompatActivity {
private Button btn1;
private Button btn2;
private Button btn3;
private TextView tv1;
private TextView tv2;
private EditText et1;
private BarCodeUtil util;
private ImageView iv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WindowManager wm = getWindowManager();
//设置一维码和二维码宽高
int width = wm.getDefaultDisplay().getWidth();
int height = wm.getDefaultDisplay().getHeight();
util = new BarCodeUtil(width * 2 / 3, height / 4);
findViews();
initViews();
}
private void findViews() {
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
btn3 = (Button) findViewById(R.id.btn3);
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
et1 = (EditText) findViewById(R.id.editText1);
iv1 = (ImageView) findViewById(R.id.iv1);
}
private void initViews() {
/**
* 扫码
*/
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
startActivityForResult(intent, 0);
}
});
/**
* 生成一维码
*/
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String text = et1.getText().toString().trim();
try {
iv1.setImageBitmap(util.bitmap1(text));
tv2.setText(text);
} catch (Exception e) {
e.printStackTrace();
Log.e("barCoder", "draw bar code failed." + e.toString());
}
}
});
/**
* 生成二维码
*/
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String text = et1.getText().toString().trim();
try {
iv1.setImageBitmap(util.bitmap2(text));
tv2.setText(text);
} catch (Exception e) {
e.printStackTrace();
Log.e("barCoder", "draw bar code failed." + e.toString());
}
}
});
}
//获取扫码结果
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 0) {
String result = data.getExtras().getString("result");
tv1.setText(result);
}
}
}
源码:https://git.oschina.net/zxingcode/ZxingCode
github地址:BGAQRCode-Android
这个库bug太多,不建议使用。
dependencies {
...
compile 'cn.bingoogolapple:bga-qrcodecore:1.1.5@aar'
compile 'cn.bingoogolapple:bga-zbar:1.1.5@aar'
...
}
.bingoogolapple.qrcode.zbar.ZBarView
android:id="@+id/zBarView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:qrcv_animTime="1000"
app:qrcv_qrCodeTipText="将二维码/条码放入框内,即可自动扫描"
app:qrcv_borderColor="@android:color/white"
app:qrcv_borderSize="1dp"
app:qrcv_cornerColor="@color/colorPrimaryDark"
app:qrcv_cornerLength="20dp"
app:qrcv_cornerSize="3dp"
app:qrcv_isShowDefaultScanLineDrawable="true"
app:qrcv_maskColor="#33FFFFFF"
app:qrcv_rectWidth="200dp"
app:qrcv_scanLineColor="@color/colorPrimaryDark"
app:qrcv_topOffset="90dp"/>
-keep class net.sourceforge.zbar.** { *; }
-keep interface net.sourceforge.zbar.** { *; }
-dontwarn net.sourceforge.zbar.**
ZBar 扫描二维码「扫描中文会有乱码,如果对中文有要求,请使用 ZXing」
git地址:https://github.com/liang530/ScanCode
使用zxing封装的android扫描全功能系列,包括二维码扫描,条形码扫描,二维码生成,条形码生成,从图片中扫描二维码或者条形码,闪光灯控制。
优点:
1.该有的功能一个都不少!
2.扫描界面布局xml完成,可自行订制!
3.不乱码,不变形!
4.扫描后可得到扫描的截图!
5.支持连续扫描!
6.在一个项目中可多处使用,根据CommonScanActivity在多写一个自己的扫描界面就行了!
作者没有把他发布到jcenter,所有我们不能使用gradle添加,只可以copy代码到自己的项目中。需要复制的内容
先复制zxing.jar
activity_create_bar_code.xml
、activity_create_qr_code.xml
、activity_scan_bar_code.xml
icon_arrow.png
、icon_light.png
、scanning_line.png
Qrcode_ids.xml
colors.xml:
<color name="scan_bg">#7f000000
strings.xml
<string name="scan_barcode_hint">将条形码对入取景框,即可自动扫描string>
Bitmap barCode = EncodingHandler.createBarCode(text, 600, 300);
Bitmap barCode = EncodingHandler.create2Code(text, 600);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_bar_code);
ButterKnife.bind(this);
context = this;
scanManager = new ScanManager(this, surfaceView, rootView, rlCropView, scanLine, DecodeThread.BARCODE_MODE, new ScanListener() {
@Override
public void scanResult(Result rawResult, Bundle bundle) {
ToastUtil.showShortToast(context, rawResult.getText());
Intent intent = new Intent();
intent.putExtra("BarCode", rawResult.getText());
setResult(2, intent);
finish();
}
@Override
public void scanError(Exception e) {
ToastUtil.showShortToast(context, e.getMessage());
}
});
}
@Override
public void onResume() {
super.onResume();
scanManager.onResume();
}
@Override
public void onPause() {
super.onPause();
scanManager.onPause();
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_bar_code);
ButterKnife.bind(this);
context = this;
scanManager = new ScanManager(this, surfaceView, rootView, rlCropView, scanLine, DecodeThread.QRCODE_MODE, new ScanListener() {
@Override
public void scanResult(Result rawResult, Bundle bundle) {
ToastUtil.showShortToast(context, rawResult.getText());
Intent intent = new Intent();
intent.putExtra("QrCode", rawResult.getText());
setResult(3, intent);
finish();
}
@Override
public void scanError(Exception e) {
ToastUtil.showShortToast(context, e.getMessage());
}
});
}
@Override
public void onResume() {
super.onResume();
scanManager.onResume();
}
@Override
public void onPause() {
super.onPause();
scanManager.onPause();
}
一维码和二维码都可以扫描:DecodeThread.ALL_MODE
Demo:http://git.oschina.net/beifang2008/zxing01
基于ZXing Android实现的QRCode扫描支持库。包括生成二维码图片
和相机扫描二维码图片即时解码
两部分功能。 基于ZXing Android实现的QRCode扫描支持库。包括生成二维码图片
和相机扫描二维码图片即时解码
两部分功能。
github: https://github.com/yoojia/NextQRCode
生成二维码不建议用这个,我把json传进去到生成bitmap,大概用时1s,用android-zxingLibrary 大概500ms。
扫描二维码用的rxjava,有点问题。
二维码扫描Demo,支持扫描生成以及从相册选择图片扫描等。基于ZXing Android修改实现的QRCode扫描支持库。
github: https://github.com/5peak2me/QRCode
github:https://github.com/XuDaojie/QRCode-Android
Demo: http://git.oschina.net/zxingcode/QRCode-Android01
缺点:只有扫描一维码+二维码的功能呢,没有生成一维码+二维码的功能,扫描狂太长,需要下载library自己修改。
下面是该开源库的README.md
allprojects {
repositories {
jcenter()
maven { url "http://repo1.maven.org/maven2" }
maven { url 'https://jitpack.io' }
}
}
dependencies {
...
compile 'com.github.XuDaojie:QRCode-Android:v0.4.2'
}
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<activity android:name="io.github.xudaojie.qrcodelib.CaptureActivity"/>
CaptureActivity 对二维码扫描信息默认是将扫描结果传回上一个界面,如果你要在CaptureActivity中直接处理,可通过重写handleResult(String resultString)实现
打开扫描界面:
Intent intent = new Intent(context, CaptureActivity.class);
startActivityForResult(intent, 100);
获取扫描值:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 100 && data != null) {
String result = data.getStringExtra("result");
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
}
重写handleResult(String resultString)
public class SimpleCaptureActivity extends CaptureActivity {
@Override
protected void handleResult(String resultString) {
if (resultString.equals("")) {
Toast.makeText(mActivity, R.string.scan_failed, Toast.LENGTH_SHORT).show();
restartPreview();
} else {
// TODO: 16/9/17 ...
// restartPreview();
}
}
}
如果你的操作不会触发SimpleCaptureActivity的onPause
、onResume
生命周期,则需要在完成操作后,调用restartPreview()
以重新启动扫描
github: https://github.com/yipianfengye/android-zxingLibrary
Demo:https://git.oschina.net/zxingcode/AndroidZxingLibrary01.git
这个库功能比较全面,有
1. 扫描一维码和二维码
2. 生成二维码(可以有logo)
3. 自定义扫描页面
4. 解析二维码图片
缺点:
- 不能生成一维码
- 解析二维码图片有错误
- 默认扫描界面比较简单,需要自己添加闪光灯。
dependencies {
compile 'cn.yipianfengye.android:zxing-library:2.2'
}
还要在Application的onCreate()方法中初始化
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ZXingLibrary.initDisplayOpinion(this);
}
}
Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
startActivityForResult(intent, REQUEST_CODE);
获取扫描结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Bundle bundle = data.getExtras();
if (bundle != null) {
int resultType = bundle.getInt(CodeUtils.RESULT_TYPE);
if (resultType == CodeUtils.RESULT_SUCCESS) {
String result = bundle.getString(CodeUtils.RESULT_STRING);
Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
} else if (resultType == CodeUtils.RESULT_FAILED) {
Toast.makeText(context, "扫描失败", Toast.LENGTH_SHORT).show();
}
}
}
}
}
无logo(第三个参数就是logo的bitmap)
Bitmap image = CodeUtils.createImage(text, 300, 300, null);
iv.setImageBitmap(image);
有参数:
Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_round);
Bitmap image2 = CodeUtils.createImage(text2, 300, 300, logo);
iv.setImageBitmap(image2);
public class CustomScanActivity extends AppCompatActivity {
private Button btn_light;
private boolean isOpen = false;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
CaptureFragment fragment = new CaptureFragment();
CodeUtils.setFragmentArgs(fragment, R.layout.my_camera);
fragment.setAnalyzeCallback(analyzeCallback);
getSupportFragmentManager().beginTransaction().replace(R.id.fl_scan, fragment).commit();
btn_light = (Button) findViewById(R.id.btn_light);
btn_light.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isOpen) {
CodeUtils.isLightEnable(false);
isOpen = false;
btn_light.setText("打开闪光灯");
} else {
CodeUtils.isLightEnable(true);
isOpen = true;
btn_light.setText("关闭闪光灯");
}
}
});
}
/**
* 二维码解析回调函数
*/
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);
CustomScanActivity.this.setResult(RESULT_OK, resultIntent);
CustomScanActivity.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);
CustomScanActivity.this.setResult(RESULT_OK, resultIntent);
CustomScanActivity.this.finish();
}
};
}
R.layout.activity_scan:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/fl_scan"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="@+id/btn_light"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="30dp"
android:background="#A1887F"
android:text="打开闪光灯"/>
RelativeLayout>
R.layout.my_camera是给CaptureFragment设置的view
<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="#0effc2"
app:inner_corner_length="30dp"
app:inner_corner_width="5dp"
app:inner_scan_bitmap="@drawable/scan_image"
app:inner_scan_speed="10"
app:inner_scan_iscircle="false"
/>
FrameLayout>