一、实现对二维码的扫描
使用步骤:
1.在module的build.gradle中dependencies添加
compile 'cn.yipianfengye.android:zxing-library:2.1'
个人认为这个依赖非常强大,封装了用到的所有方法提供调用
2.在Application中执行初始化操作
提示:在清单文件中注册Application
public class MyApplication extends Application{ @Override public void onCreate() { super.onCreate(); //初始化二维码工具类 ZXingLibrary.initDisplayOpinion(this); } }3. 在清单文件配置权限(别忘了android 6.0以上版本动态权限的添加)
<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" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INTERNET" />
Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
startActivityForResult(intent, REQUEST_CODE);
这里的
REQUEST_CODE是自己定义的变量,用于
onActivityResult回传数据
/**
* 扫描跳转Activity RequestCode
*/
public static final int REQUEST_CODE = 111;
/**
* 选择系统图片Request Code
*/
public static final int REQUEST_IMAGE = 112;
@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();
}
}
}
/**
* 选择系统图片并解析
*/
else if (requestCode == REQUEST_IMAGE) {
if (data != null) {
Uri uri = data.getData();
try {
CodeUtils.analyzeBitmap(ImageUtil.getImageAbsolutePath(this, uri), 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();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 请求CAMERA权限码
*/
public static final int REQUEST_CAMERA_PERM = 101;
/**
* EsayPermissions接管权限处理逻辑
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@AfterPermissionGranted(REQUEST_CAMERA_PERM)
public void cameraTask(int viewId) {
if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
// Have permission, do the thing!
onClick(viewId);
} else {
// Ask for one permission
EasyPermissions.requestPermissions(this, "需要请求camera权限",
REQUEST_CAMERA_PERM, Manifest.permission.CAMERA);
}
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
Toast.makeText(this, "执行onPermissionsGranted()...", Toast.LENGTH_SHORT).show();
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
Toast.makeText(this, "执行onPermissionsDenied()...", Toast.LENGTH_SHORT).show();
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
new AppSettingsDialog.Builder(this, "当前App需要申请camera权限,需要打开设置页面么?")
.setTitle("权限申请")
.setPositiveButton("确认")
.setNegativeButton("取消", null /* click listener */)
.setRequestCode(REQUEST_CAMERA_PERM)
.build()
.show();
}
}
/**
* 按钮点击监听
*/
class ButtonOnClickListener implements View.OnClickListener{
private int buttonId;
public ButtonOnClickListener(int buttonId) {
this.buttonId = buttonId;
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.button2) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_IMAGE);
} else if (v.getId() == R.id.button4) {
Intent intent = new Intent(MainActivity.this, ThreeActivity.class);
startActivity(intent);
} else {
cameraTask(buttonId);
}
}
}
/**
* 按钮点击事件处理逻辑
* @param buttonId
*/
private void onClick(int buttonId) {
switch (buttonId) {
case R.id.button1:
Intent intent = new Intent(getApplication(), CaptureActivity.class);
startActivityForResult(intent, REQUEST_CODE);
break;
case R.id.button3:
intent = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, REQUEST_CODE);
break;
default:
break;
}
}
对应的布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="简单模式,加载默认二维码扫描界面"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="选择图片并解析"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_below="@+id/button1"
/>
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="定制化扫描界面"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_below="@+id/button2"
/>
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="测试生成二维码图片"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_below="@+id/button3"
/>
</RelativeLayout>
这样就简单实现了二维码的扫描识别功能,当然,我们的需求不仅仅如此,还可以自定义扫描界面
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.LinearLayout;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;
/**
* 定制化显示扫描界面
*/
public class SecondActivity extends BaseActivity {
private CaptureFragment captureFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
captureFragment = new CaptureFragment();
// 为二维码扫描界面设置定制化界面
CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera);
captureFragment.setAnalyzeCallback(analyzeCallback);
getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
initView();
}
public static boolean isOpen = false;
private void initView() {
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear1);
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isOpen) {
CodeUtils.isLightEnable(true);
isOpen = true;
} else {
CodeUtils.isLightEnable(false);
isOpen = false;
}
}
});
}
/**
* 二维码解析回调函数
*/
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);
SecondActivity.this.setResult(RESULT_OK, resultIntent);
SecondActivity.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);
SecondActivity.this.setResult(RESULT_OK, resultIntent);
SecondActivity.this.finish();
}
};
}
对应的布局文件
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_second"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/fl_my_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
></FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="15dp"
android:paddingTop="15dp"
android:layout_gravity="bottom|center_horizontal"
android:orientation="horizontal"
android:background="#AA333333"
>
<LinearLayout
android:id="@+id/linear1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:gravity="center_horizontal"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="闪光灯"
android:layout_marginTop="10dp"
android:textColor="#FFFFFF"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:gravity="center_horizontal"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="封面"
android:layout_marginTop="10dp"
android:textColor="#FFFFFF"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:gravity="center_horizontal"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="街景"
android:layout_marginTop="10dp"
android:textColor="#FFFFFF"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="翻译"
android:layout_marginTop="10dp"
android:textColor="#FFFFFF"
/>
</LinearLayout>
</LinearLayout>
</FrameLayout>
接下来,我们还可以自己生成二维码
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.uuzuche.lib_zxing.activity.CodeUtils;
public class ThreeActivity extends BaseActivity {
public EditText editText = null;
public Button button = null;
public Button button1 = null;
public ImageView imageView = null;
public Bitmap mBitmap = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_three);
initView();
}
/**
* 初始化组件
*/
private void initView() {
editText = (EditText) findViewById(R.id.edit_content);
button = (Button) findViewById(R.id.button_content);
button1 = (Button) findViewById(R.id.button1_content);
imageView = (ImageView) findViewById(R.id.image_content);
/**
* 生成二维码图片
*/
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String textContent = editText.getText().toString();
if (TextUtils.isEmpty(textContent)) {
Toast.makeText(ThreeActivity.this, "您的输入为空!", Toast.LENGTH_SHORT).show();
return;
}
editText.setText("");
mBitmap = CodeUtils.createImage(textContent, 400, 400, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
imageView.setImageBitmap(mBitmap);
}
});
/**
* 生成不带logo的二维码图片
*/
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String textContent = editText.getText().toString();
if (TextUtils.isEmpty(textContent)) {
Toast.makeText(ThreeActivity.this, "您的输入为空!", Toast.LENGTH_SHORT).show();
return;
}
editText.setText("");
mBitmap = CodeUtils.createImage(textContent, 400, 400, null);
imageView.setImageBitmap(mBitmap);
}
});
}
对应的布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<EditText
android:id="@+id/edit_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minLines="3"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
/>
<Button
android:id="@+id/button_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_below="@+id/edit_content"
android:text="生成logo二维码图片"
/>
<Button
android:id="@+id/button1_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_below="@+id/button_content"
android:text="生成普通二维码图片"
/>
<ImageView
android:id="@+id/image_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1_content"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
最后附上我的github地址 https://github.com/liugang0324/android-zxingLibrary-master