今天给大家带来的怎么用Android实现二维码扫描并将扫描内容取出做处理!
首先,我们要用Android实现二维码的扫描。对于初学者来说都要去膜拜大神的源代码,去论坛搜索Android实现二维码扫描,出现一大些的讲解。我写这篇文章时,我也是个初学者,我前期也去搜索过大量的有关实现Android实现二维码的博客,有简单的,有复杂的,我就从中去下了一个简单的源代码和复杂的源代码,在我实现的时候会出现一个问题,对于简单的源代码,会引用很多的文件和包,代码可以看懂,但是引用了很多各种各样的文件包,看的我一脸懵逼。对于复杂的呢,更别说了,对于我这个小白来说代码根本看不懂!
对于初学者来说,尽可能最简化易懂的代码来实现复杂的功能最理想不过了。上边所说到的都是个人在开发过程中的经历,供自己记录所用,不代表所有开发者的想法!好,废话不多说我们开始实现基于Android实现二维码扫描功能!
二维码扫描步骤:
(1)创建一个activity命名为DoScanActivity
/** * Created by Boy Baby on 2018/4/5. */ public class DoScanActivity extends CaptureActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
(2)AndroidManifest.xml文件中DoScanActivity配置如下:
<activity android:name=".DoScanActivity" android:screenOrientation="portrait" android:stateNotNeeded="true" android:windowSoftInputMode="stateAlwaysHidden" />
(3)bulid.gradle文件中添加
compile 'com.journeyapps:zxing-android-embedded:3.5.0' compile 'com.google.zxing:core:3.3.0'
(4)添加完成后的dependencies代码
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:26.+' compile 'com.android.support.constraint:constraint-layout:1.0.2' compile 'com.journeyapps:zxing-android-embedded:3.5.0' compile 'com.google.zxing:core:3.3.0' testCompile 'junit:junit:4.12' }
(5)获取扫描结果使用Activity类的成员onActivityResult方法获取;
protected void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if(result != null) { if(result.getContents() == null) { Toast.makeText(this, "扫码失败!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "扫描成功,条码值: " + result.getContents(), Toast.LENGTH_LONG).show(); String string=result.getContents(); } } else { super.onActivityResult(requestCode, resultCode, data); } }
(6)启动二维码扫描(xml文件布局)
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.boybaby.qr_code.MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="Sao_QR" android:text="扫一扫" tools:layout_editor_absoluteX="148dp" tools:layout_editor_absoluteY="110dp" /> </android.support.constraint.ConstraintLayout>
(7)给按钮添加事件监听事件(启动二维码扫描)
//扫一扫 public void Sao_QR(View view){ IntentIntegrator integrator = new IntentIntegrator(this); integrator.setCaptureActivity(DoScanActivity.class); integrator.initiateScan(); }