zxing是github上一個二維碼處理開源項目,我們使用這個庫來處理二維碼
如果你使用的是Android Studio,可以參考本文進行配置。並附一個小例子。
首先在build.gradle(Moudle:app)中添加下列依賴:
repositories {
mavenCentral()
maven {
url "http://dl.bintray.com/journeyapps/maven"
}
}
dependencies {
// Supports Android 4.0.3 and later (API level 15)
compile 'com.journeyapps:zxing-android-embedded:2.0.1@aar'
// Supports Android 2.1 and later (API level 7), but not optimal for later Android versions.
// If you only plan on supporting Android 4.0.3 and up, you don't need to include this.
compile 'com.journeyapps:zxing-android-legacy:2.0.1@aar'
// Convenience library to launch the scanning and encoding Activities.
// It automatically picks the best scanning library from the above two, depending on the
// Android version and what is available.
compile 'com.journeyapps:zxing-android-integration:2.0.1@aar'
// Version 3.0.x of zxing core contains some code that is not compatible on Android 2.2 and earlier.
// This mostly affects encoding, but you should test if you plan to support these versions.
// Older versions e.g. 2.2 may also work if you need support for older Android versions.
compile 'com.google.zxing:core:3.0.1'
}
然后在AndroidManifest.xml文件<manifest>標簽內部,<application>標簽前面加入以下代碼,申請權限
- <uses-permission android:name="android.permission.CAMERA"/>
- <uses-permission android:name="android.permission.VIBRATE"/>
- <uses-permission android:name="android.permission.INTERNET"/>
這樣就行了!
接下來是用法:
在按鈕的onClick事件中添加代碼,點擊后會跳轉到掃描界面:
- @Override
- public void onClick(View v) {
- //掃描操作
- IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
- integrator.initiateScan();
- }
然后重寫下列函數,用來處理解碼后的信息:
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
- if (scanResult != null) {
- String result = scanResult.getContents();
- Log.d("code", result);
- Toast.makeText(this,result, Toast.LENGTH_LONG).show();
- }
- }
變量result就是二維碼解碼后的信息。
請用真機調試。
另外,zxing中設置的是掃描時橫屏。通常我們不希望橫屏,網上一般的修改方法是直接修改源代碼。但是現在我們用的是gradle添加依賴的方式,所以我現在暫時沒有想到辦法。如果有知道的盆友望不吝賜教!
原文: http://blog.csdn.net/AeroYoung/article/details/51144758