QR code scanning is now a relatively large application scenario. The open source project of android ZXing provides a complete and mature solution. If it is just for the purpose of rapid development, you can cut the projects provided by ZXing according to your project needs and quickly integrate them into your project. The following is a detailed demonstration and description of how to implement the solution based on the source code provided by ZXing and quickly integrate the QR code scanning function into your own project.
(Step 1):Go to ZXing’s official homepage to download the latest project code package. ZXing’s official homepage on github:/zxing, download and unzip. After decompression, there are several project directories in the root directory, among which: android is the project we need, import it into Eclispse.
(Step 2):ZXing's Android project needs to reference two key library files:and, which indicates the version number. As of the time of publication, the version is already 3.2.0. These two key and \ files can actually be compiled and generated by themselves from the source code downloaded in the first step. There are specific compilation solutions online, but during the simple period, you can also directly download the compiled files from ZXing's official official. The download link of android-core is:/maven2/com/google/zxing/android-core/, Another ZXing core download link is:/maven2/com/google/zxing/core/, select the latest version of the library file or the version number you need. After downloading, it is similar to importing the library file in other Android projects. Import it into the libs directory in the Android project. If there is no libs, create a new directory called libs and put two library files in it.
(Step 3):As a demonstration, we create a new MainActivy ourselves, as the project launcher Activity, and the App will start our own MainActivity. Observe the documents provided by ZXing:
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2008 ZXing authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at /licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <manifest xmlns:andro package="" android:versionName="4.7.3" android:versionCode="103" android:installLocation="auto"> <uses-permission android:name=""/> <uses-permission android:name=""/> <uses-permission android:name=""/> <uses-permission android:name=""/> <uses-permission android:name=".READ_CONTACTS"/> <uses-permission android:name=".READ_HISTORY_BOOKMARKS"/> <uses-permission android:name=".WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name=".CHANGE_WIFI_STATE"/> <uses-permission android:name=".ACCESS_WIFI_STATE"/> <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="21"/> <!-- Don't require camera, as this requires a rear camera. This allows it to work on the Nexus 7 --> <uses-feature android:name="" android:required="false"/> <uses-feature android:name="" android:required="false"/> <!-- TODO replace above two with next line after Android 4.2 --> <!-- <uses-feature android:name=""/> --> <uses-feature android:name="" android:required="false"/> <uses-feature android:name="" android:required="false"/> <uses-feature android:name=""/> <uses-feature android:name="" android:required="false"/> <!-- This excludes Google TV, which is unfortunately included by virtue of not requiring a camera --> <uses-feature android:name=""/> <!-- TODO make this not required again after is available --> <supports-screens android:xlargeScreens="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:anyDensity="true"/> <application android:icon="@drawable/launcher_icon" android:logo="@drawable/launcher_icon" android:label="@string/app_name" android:allowBackup="true"> <activity android:name=".CaptureActivity" android:screenOrientation="sensorLandscape" android:clearTaskOnLaunch="true" android:stateNotNeeded="true" android:theme="@style/CaptureTheme" android:windowSoftInputMode="stateAlwaysHidden"> <intent-filter> <action android:name=""/> <category android:name=""/> </intent-filter> <intent-filter> <action android:name=""/> <category android:name=""/> </intent-filter> <!-- Allow web apps to launch Barcode Scanner by linking to /scan. --> <intent-filter> <action android:name=""/> <category android:name=""/> <category android:name=""/> <data android:scheme="http" android:host="" android:path="/scan"/> </intent-filter> <!-- We also support a Google Product Search URL. --> <intent-filter> <action android:name=""/> <category android:name=""/> <category android:name=""/> <data android:scheme="http" android:host="" android:path="/m/products/scan"/> </intent-filter> <!-- And the UK version. --> <intent-filter> <action android:name=""/> <category android:name=""/> <category android:name=""/> <data android:scheme="http" android:host="" android:path="/m/products/scan"/> </intent-filter> <!-- Support zxing://scan/?... like iPhone app --> <intent-filter> <action android:name=""/> <category android:name=""/> <category android:name=""/> <data android:scheme="zxing" android:host="scan" android:path="/"/> </intent-filter> </activity> <activity android:name=".PreferencesActivity" android:label="@string/preferences_name" android:stateNotNeeded="true"/> <activity android:name="." android:stateNotNeeded="true"> <intent-filter> <action android:name=""/> <category android:name=""/> </intent-filter> <!-- This allows us to handle the Share button in Contacts. --> <intent-filter> <action android:name=""/> <category android:name=""/> <data android:mimeType="text/x-vcard"/> </intent-filter> <!-- This allows us to handle sharing any plain text . --> <intent-filter> <action android:name=""/> <category android:name=""/> <data android:mimeType="text/plain"/> </intent-filter> </activity> <activity android:name="." android:label="@string/sbc_name" android:stateNotNeeded="true" android:screenOrientation="sensorLandscape"> <intent-filter> <action android:name=".SEARCH_BOOK_CONTENTS"/> <category android:name=""/> </intent-filter> </activity> <activity android:name="." android:stateNotNeeded="true" android:screenOrientation="user"> <intent-filter> <action android:name=""/> <category android:name=""/> </intent-filter> </activity> <activity android:name="." android:label="@string/history_title" android:stateNotNeeded="true"/> <activity android:name="." android:label="@string/bookmark_picker_name" android:stateNotNeeded="true"/> <activity android:name="." android:label="@string/app_picker_name" android:stateNotNeeded="true"/> <activity android:name=".HelpActivity" android:label="@string/menu_help" android:screenOrientation="user" android:stateNotNeeded="true"/> </application> </manifest>
In fact, ZXing's official project has already provided integrated code for third parties, such as the key Activity: .\src\com\google\zxing\client\android\. The Intent Action that is accessed from various entrances has been provided in the declaration. So in the newly created MainActivity we directly implicitly specify an Intent Action and start it:
package ; import ; import ; import ; import ; public class MainActivity extends Activity { private final int REQUEST_CODE = 0xa1; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); Intent intent = new Intent(); //Implicitly specified (""); //The CaptureActivity that has been written and we have made a small amount of modified CaptureActivity. startActivityForResult(intent, REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { (requestCode, resultCode, data); //Return the result we need if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) { //result is the result of QR code scanning. String result = ("RESULT"); (getApplicationContext(), result, Toast.LENGTH_SHORT) .show(); } } }
Because we start ZXing's CaptureActivity is not the purpose, the real purpose is to start ZXing's CaptureActivity to get the QR code scan result, so start in the way of startActivityForResult(). Correspondingly, we need to rewrite: protected void onActivityResult(int requestCode, int resultCode, Intent data) to wait for the result to be passed back.
(Step 4):This step is the key point. Methods in the .\src\com\google\zxing\client\android\ directory: public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor); This method is a callback function. The scan module written in the ZXing project returns to callback this method after scanning. ZXing's official original public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) method is as follows:
/** * A valid barcode has been found, so give an indication of success and show the results. * * @param rawResult The contents of the barcode. * @param scaleFactor amount by which thumbnail was scaled * @param barcode A greyscale bitmap of the camera data which was decoded. */ public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) { (); lastResult = rawResult; ResultHandler resultHandler = (this, rawResult); boolean fromLiveScan = barcode != null; if (fromLiveScan) { (rawResult, resultHandler); // Then not from history, so beep/vibrate and we have an image to draw on (); drawResultPoints(barcode, scaleFactor, rawResult); } switch (source) { case NATIVE_APP_INTENT: case PRODUCT_SEARCH_LINK: handleDecodeExternally(rawResult, resultHandler, barcode); break; case ZXING_LINK: if (scanFromWebPageManager == null || !()) { handleDecodeInternally(rawResult, resultHandler, barcode); } else { handleDecodeExternally(rawResult, resultHandler, barcode); } break; case NONE: SharedPreferences prefs = (this); if (fromLiveScan && (PreferencesActivity.KEY_BULK_MODE, false)) { (getApplicationContext(), getResources().getString(.msg_bulk_mode_scanned) + " (" + () + ')', Toast.LENGTH_SHORT).show(); // Wait a moment or else it will scan the same barcode continuously about 3 times restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS); } else { handleDecodeInternally(rawResult, resultHandler, barcode); } break; } }
We will streamline this method and customize the content we need. To meet the needs of our own projects, the modified code of this method is:
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) { (); lastResult = rawResult; ResultHandler resultHandler = (this, rawResult); boolean fromLiveScan = barcode != null; if (fromLiveScan) { (rawResult, resultHandler); // Then not from history, so beep/vibrate and we have an image to draw on (); drawResultPoints(barcode, scaleFactor, rawResult); } //Add our code here, the purpose is to make the minimum amount of modifications, and to integrate the CaptureActivity provided by ZXing into our own project as an intermediate activity. //Start the QR code scanning and return a result. //Then end this activity. Intent intent=new Intent(); //<key,value> store the QR code results. //() is the QR code result. ("RESULT", ()); (Activity.RESULT_OK, intent); (); /** The following is the source code provided by ZXing, which can be deleted and used according to the needs of the project. During the simple period, we only need to scan the QR code and return a scanned string result. So comment out temporarily this time. switch (source) { case NATIVE_APP_INTENT: case PRODUCT_SEARCH_LINK: handleDecodeExternally(rawResult, resultHandler, barcode); break; case ZXING_LINK: if (scanFromWebPageManager == null || !()) { handleDecodeInternally(rawResult, resultHandler, barcode); } else { handleDecodeExternally(rawResult, resultHandler, barcode); } break; case NONE: SharedPreferences prefs = (this); if (fromLiveScan && (PreferencesActivity.KEY_BULK_MODE, false)) { (getApplicationContext(), getResources().getString(.msg_bulk_mode_scanned) + " (" + () + ')', Toast.LENGTH_SHORT).show(); // Wait a moment or else it will scan the same barcode continuously about 3 times restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS); } else { handleDecodeInternally(rawResult, resultHandler, barcode); } break; } **/ }
(Step 5):This step is relatively simple, and it is the rest of the finishing work, modify the file, and start our MainActivity as the main Activity. Take ZXing's CaptureActivity as a normal activity.
Modified file:
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2008 ZXing authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at /licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <manifest xmlns:andro package="" android:versionName="4.7.3" android:versionCode="103" android:installLocation="auto"> <uses-permission android:name=""/> <uses-permission android:name=""/> <uses-permission android:name=""/> <uses-permission android:name=""/> <uses-permission android:name=".READ_CONTACTS"/> <uses-permission android:name=".READ_HISTORY_BOOKMARKS"/> <uses-permission android:name=".WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name=".CHANGE_WIFI_STATE"/> <uses-permission android:name=".ACCESS_WIFI_STATE"/> <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="21"/> <!-- Don't require camera, as this requires a rear camera. This allows it to work on the Nexus 7 --> <uses-feature android:name="" android:required="false"/> <uses-feature android:name="" android:required="false"/> <!-- TODO replace above two with next line after Android 4.2 --> <!-- <uses-feature android:name=""/> --> <uses-feature android:name="" android:required="false"/> <uses-feature android:name="" android:required="false"/> <uses-feature android:name=""/> <uses-feature android:name="" android:required="false"/> <!-- This excludes Google TV, which is unfortunately included by virtue of not requiring a camera --> <uses-feature android:name=""/> <!-- TODO make this not required again after is available --> <supports-screens android:xlargeScreens="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:anyDensity="true"/> <application android:icon="@drawable/launcher_icon" android:logo="@drawable/launcher_icon" android:label="@string/app_name" android:allowBackup="true"> <!-- Newly added our ownMainActiviyAs a startupActivity --> <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="" /> <category android:name="" /> </intent-filter> </activity> <activity android:name=".CaptureActivity" android:screenOrientation="sensorLandscape" android:clearTaskOnLaunch="true" android:stateNotNeeded="true" android:theme="@style/CaptureTheme" android:windowSoftInputMode="stateAlwaysHidden"> <!-- BundleZXingOfficially provided main activityStartedCaptureActivityAs a normalActiviy。 <intent-filter> <action android:name=""/> <category android:name=""/> </intent-filter> --> <intent-filter> <action android:name=""/> <category android:name=""/> </intent-filter> <!-- Allow web apps to launch Barcode Scanner by linking to /scan. --> <intent-filter> <action android:name=""/> <category android:name=""/> <category android:name=""/> <data android:scheme="http" android:host="" android:path="/scan"/> </intent-filter> <!-- We also support a Google Product Search URL. --> <intent-filter> <action android:name=""/> <category android:name=""/> <category android:name=""/> <data android:scheme="http" android:host="" android:path="/m/products/scan"/> </intent-filter> <!-- And the UK version. --> <intent-filter> <action android:name=""/> <category android:name=""/> <category android:name=""/> <data android:scheme="http" android:host="" android:path="/m/products/scan"/> </intent-filter> <!-- Support zxing://scan/?... like iPhone app --> <intent-filter> <action android:name=""/> <category android:name=""/> <category android:name=""/> <data android:scheme="zxing" android:host="scan" android:path="/"/> </intent-filter> </activity> <activity android:name=".PreferencesActivity" android:label="@string/preferences_name" android:stateNotNeeded="true"/> <activity android:name="." android:stateNotNeeded="true"> <intent-filter> <action android:name=""/> <category android:name=""/> </intent-filter> <!-- This allows us to handle the Share button in Contacts. --> <intent-filter> <action android:name=""/> <category android:name=""/> <data android:mimeType="text/x-vcard"/> </intent-filter> <!-- This allows us to handle sharing any plain text . --> <intent-filter> <action android:name=""/> <category android:name=""/> <data android:mimeType="text/plain"/> </intent-filter> </activity> <activity android:name="." android:label="@string/sbc_name" android:stateNotNeeded="true" android:screenOrientation="sensorLandscape"> <intent-filter> <action android:name=".SEARCH_BOOK_CONTENTS"/> <category android:name=""/> </intent-filter> </activity> <activity android:name="." android:stateNotNeeded="true" android:screenOrientation="user"> <intent-filter> <action android:name=""/> <category android:name=""/> </intent-filter> </activity> <activity android:name="." android:label="@string/history_title" android:stateNotNeeded="true"/> <activity android:name="." android:label="@string/bookmark_picker_name" android:stateNotNeeded="true"/> <activity android:name="." android:label="@string/app_picker_name" android:stateNotNeeded="true"/> <activity android:name=".HelpActivity" android:label="@string/menu_help" android:screenOrientation="user" android:stateNotNeeded="true"/> </application> </manifest>
Note: This article is just the simplest example, demonstrating how to make the smallest changes based on the complete code provided by the ZXing official project in your project, and quickly integrate the QR code scanning function into your project for my use. If more detailed adjustments are needed, you need to deeply customize and adapt the source code.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.