ZxingライブラリをAndroidアプリケーションに直接統合します
-
23-10-2019 - |
質問
私はこれを単なる絶望で書いています:)私はAndroid 1.6電話にスタンドアロンのバーコードスキャナー(概念の証明として)を作るように割り当てられました。
このために、Zxingライブラリを発見しました。
私はグーグルで検索しました。ここで関連するトピックをStackoverflowを使用して、一般的なセンスなどを使用しています。何も助けてくれなかったようで、私はこのメンテールの封鎖に穴を開けることができません:/
LIBを使用し、独自のスタンドアロンバーコードスキャナーを作成することが可能であることを知っています。 Zxingの人々が提供する「バーコードスキャナー」を使用して、(意図を介して)最も簡単なソリューションであることを読んだことがあります。残念ながら、これはオプションではなく、スタンドアロンアプリが望まれます。
だから私の問題を要約する:
- Zxing source libをEclipseを通じてAndroidコードプロジェクトに統合する方法は?
- 統合された場合... LIBを使用する方法、スキャン機能を「ロード」する方法は?
- 私はEclipseで働き始めたばかりなので、ステップトゥステップガイドがほとんど好まれます。
ZxingソースフォルダーからAndroidフォルダーにコードプロジェクトを依存させようとしました。私がそうするとき、主に「org.apache」(??)に関して、一握りのエラーが現れます
私はそれを理解することはできません...だからいくつかのヒントが最も役立つでしょう。
事前に、ありがとう:)
解決
アップデート! -Solved + Guide
私はなんとかそれを理解することができました:)そして下の下に段階的なガイドを読むことができるので、それは私と同じ問題を持つ他の人を助けることができれば幸いです;)
- ApacheAntをインストール - (設定ヘルプについては、このYouTubeビデオを参照してください)
- zxingホームページからzxingソースをダウンロードして抽出します
- Windowsコマンドライン(run-> cmd)を使用すると、ダウンロードされたルートディレクトリに移動します
zxing src
. - コマンドラインウィンドウ - タイプ
ant -f core/build.xml
Enterを押して、Apacheを動作させますそれは魔法です[問題がありますか?] - 抽出したディレクトリのAndroidフォルダーに基づいて、Eclipse->新しいAndroidプロジェクトを入力してください
- プロジェクトフォルダーを右クリックします - >プロパティ - > javaビルドパス - >ライブラリ - >外部ジャーの追加...
- 新しく抽出されたフォルダに移動し、コアディレクトリを開き、選択します
core.jar
... Enterを押してください!
これで、翻訳とandroidManifest.xmlファイルのいくつかのエラーを修正する必要があります:)これで、Zxingソースに基づいて、動作するスタンドアロンのバーコードスキャナーアプリを手に入れることができます;)
ハッピーコーディングの人たち - 私はそれが他の人を助けることができることを願っています:)
他のヒント
サードパーティアプリケーションをインストールせずにZXingライブラリを使用してQRコードを生成および表示する方法に関するステップバイステップガイドを次に示します。 ノート: アリやその他のビルドツールでZxingを構築する必要はありません。ファイル core.jar
リリースされたZIPアーカイブで利用できます(以下をお読みください)。
- ダウンロードしてください Zxingの最新リリース. -- (
ZXing-*.zip
) - このzipアーカイブを抽出して見つけます
core.jar
下core/
ディレクトリ。 - Eclipse IDEを使用している場合は、ドラッグアンドドロップ
core.jar
にlibs
Androidプロジェクトのディレクトリ。尋ねられたら、選択します コピー. - 以下に示す2つのクラスをコピーします(
Contents.java
&QRCodeEncoder.java
)Androidプロジェクトのメインパッケージへ。 - 作成します
ImageView
アクティビティのアイテムは、生成されたQRコードをまだ持っていない場合に表示します。例を以下に示します。 - 以下のコードスニペットを使用して、QRコードをビットマップ形式で生成し、
ImageView
.
これが次のとおりです ImageView
アクティビティレイアウトXMLファイルに追加する要素:
<ImageView
android:id="@+id/qrCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true"/>
コードスニペット:
// ImageView to display the QR code in. This should be defined in
// your Activity's XML layout file
ImageView imageView = (ImageView) findViewById(R.id.qrCode);
String qrData = "Data I want to encode in QR code";
int qrCodeDimention = 500;
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, null,
Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), qrCodeDimention);
try {
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
ここは Contents.java
//
// * 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
// *
// * http://www.apache.org/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.
//
import android.provider.ContactsContract;
public final class Contents {
private Contents() {
}
public static final class Type {
// Plain text. Use Intent.putExtra(DATA, string). This can be used for URLs too, but string
// must include "http://" or "https://".
public static final String TEXT = "TEXT_TYPE";
// An email type. Use Intent.putExtra(DATA, string) where string is the email address.
public static final String EMAIL = "EMAIL_TYPE";
// Use Intent.putExtra(DATA, string) where string is the phone number to call.
public static final String PHONE = "PHONE_TYPE";
// An SMS type. Use Intent.putExtra(DATA, string) where string is the number to SMS.
public static final String SMS = "SMS_TYPE";
public static final String CONTACT = "CONTACT_TYPE";
public static final String LOCATION = "LOCATION_TYPE";
private Type() {
}
}
public static final String URL_KEY = "URL_KEY";
public static final String NOTE_KEY = "NOTE_KEY";
// When using Type.CONTACT, these arrays provide the keys for adding or retrieving multiple phone numbers and addresses.
public static final String[] PHONE_KEYS = {
ContactsContract.Intents.Insert.PHONE, ContactsContract.Intents.Insert.SECONDARY_PHONE,
ContactsContract.Intents.Insert.TERTIARY_PHONE
};
public static final String[] PHONE_TYPE_KEYS = {
ContactsContract.Intents.Insert.PHONE_TYPE,
ContactsContract.Intents.Insert.SECONDARY_PHONE_TYPE,
ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE
};
public static final String[] EMAIL_KEYS = {
ContactsContract.Intents.Insert.EMAIL, ContactsContract.Intents.Insert.SECONDARY_EMAIL,
ContactsContract.Intents.Insert.TERTIARY_EMAIL
};
public static final String[] EMAIL_TYPE_KEYS = {
ContactsContract.Intents.Insert.EMAIL_TYPE,
ContactsContract.Intents.Insert.SECONDARY_EMAIL_TYPE,
ContactsContract.Intents.Insert.TERTIARY_EMAIL_TYPE
};
}
と QRCodeEncoder.java
/*
* 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
*
* http://www.apache.org/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.
*/
import android.provider.ContactsContract;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
public final class QRCodeEncoder {
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
private int dimension = Integer.MIN_VALUE;
private String contents = null;
private String displayContents = null;
private String title = null;
private BarcodeFormat format = null;
private boolean encoded = false;
public QRCodeEncoder(String data, Bundle bundle, String type, String format, int dimension) {
this.dimension = dimension;
encoded = encodeContents(data, bundle, type, format);
}
public String getContents() {
return contents;
}
public String getDisplayContents() {
return displayContents;
}
public String getTitle() {
return title;
}
private boolean encodeContents(String data, Bundle bundle, String type, String formatString) {
// Default to QR_CODE if no format given.
format = null;
if (formatString != null) {
try {
format = BarcodeFormat.valueOf(formatString);
} catch (IllegalArgumentException iae) {
// Ignore it then
}
}
if (format == null || format == BarcodeFormat.QR_CODE) {
this.format = BarcodeFormat.QR_CODE;
encodeQRCodeContents(data, bundle, type);
} else if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "Text";
}
return contents != null && contents.length() > 0;
}
private void encodeQRCodeContents(String data, Bundle bundle, String type) {
if (type.equals(Contents.Type.TEXT)) {
if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "Text";
}
} else if (type.equals(Contents.Type.EMAIL)) {
data = trim(data);
if (data != null) {
contents = "mailto:" + data;
displayContents = data;
title = "E-Mail";
}
} else if (type.equals(Contents.Type.PHONE)) {
data = trim(data);
if (data != null) {
contents = "tel:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "Phone";
}
} else if (type.equals(Contents.Type.SMS)) {
data = trim(data);
if (data != null) {
contents = "sms:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "SMS";
}
} else if (type.equals(Contents.Type.CONTACT)) {
if (bundle != null) {
StringBuilder newContents = new StringBuilder(100);
StringBuilder newDisplayContents = new StringBuilder(100);
newContents.append("MECARD:");
String name = trim(bundle.getString(ContactsContract.Intents.Insert.NAME));
if (name != null) {
newContents.append("N:").append(escapeMECARD(name)).append(';');
newDisplayContents.append(name);
}
String address = trim(bundle.getString(ContactsContract.Intents.Insert.POSTAL));
if (address != null) {
newContents.append("ADR:").append(escapeMECARD(address)).append(';');
newDisplayContents.append('\n').append(address);
}
Collection<String> uniquePhones = new HashSet<String>(Contents.PHONE_KEYS.length);
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
String phone = trim(bundle.getString(Contents.PHONE_KEYS[x]));
if (phone != null) {
uniquePhones.add(phone);
}
}
for (String phone : uniquePhones) {
newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
}
Collection<String> uniqueEmails = new HashSet<String>(Contents.EMAIL_KEYS.length);
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
String email = trim(bundle.getString(Contents.EMAIL_KEYS[x]));
if (email != null) {
uniqueEmails.add(email);
}
}
for (String email : uniqueEmails) {
newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
newDisplayContents.append('\n').append(email);
}
String url = trim(bundle.getString(Contents.URL_KEY));
if (url != null) {
// escapeMECARD(url) -> wrong escape e.g. http\://zxing.google.com
newContents.append("URL:").append(url).append(';');
newDisplayContents.append('\n').append(url);
}
String note = trim(bundle.getString(Contents.NOTE_KEY));
if (note != null) {
newContents.append("NOTE:").append(escapeMECARD(note)).append(';');
newDisplayContents.append('\n').append(note);
}
// Make sure we've encoded at least one field.
if (newDisplayContents.length() > 0) {
newContents.append(';');
contents = newContents.toString();
displayContents = newDisplayContents.toString();
title = "Contact";
} else {
contents = null;
displayContents = null;
}
}
} else if (type.equals(Contents.Type.LOCATION)) {
if (bundle != null) {
// These must use Bundle.getFloat(), not getDouble(), it's part of the API.
float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
contents = "geo:" + latitude + ',' + longitude;
displayContents = latitude + "," + longitude;
title = "Location";
}
}
}
}
public Bitmap encodeAsBitmap() throws WriterException {
if (!encoded) return null;
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contents);
if (encoding != null) {
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result = writer.encode(contents, format, dimension, dimension, hints);
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) { return "UTF-8"; }
}
return null;
}
private static String trim(String s) {
if (s == null) { return null; }
String result = s.trim();
return result.length() == 0 ? null : result;
}
private static String escapeMECARD(String input) {
if (input == null || (input.indexOf(':') < 0 && input.indexOf(';') < 0)) { return input; }
int length = input.length();
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (c == ':' || c == ';') {
result.append('\\');
}
result.append(c);
}
return result.toString();
}
}
compile 'com.google.zxing:core:2.3.0'
残念ながら私のためにはうまくいきませんでした。
これが私のために働いたものです:
dependencies {
compile 'com.journeyapps:zxing-android-embedded:3.0.1@aar'
compile 'com.google.zxing:core:3.2.0'
}
ここでリンクを見つけてください:https://github.com/journeyApps/zxing-android-embedded
アリで構築する問題がありますか?読み続けます
もしも ant -f core/build.xml
次のようなことを言う
Unable to locate tools.jar. Expected to find it in
C:\Program Files\Java\jre6\lib\tools.jar
次に、あなたを設定します JAVA_HOME
適切なJavaフォルダーの環境変数。 (Windows用)にTools.jarを見つけました:
C:\Program Files\Java\jdk1.6.0_21\lib
だから私は私を設定します JAVA_HOME
に:
C:\Progra~1\Java\jdk1.6.0_25
いくつかのサイトで見つけた短い構文の理由:
「パス名にスペースが含まれていないインストールディレクトリを選択することを強くお勧めします(たとえば、C:プログラムファイルにインストールしないでください)。Javaがそのようなディレクトリにインストールされている場合、java_homeを設定することが重要です環境変数スペースを含まないパス(例:c: progra〜1);これを行わないと、Java_homeの価値に依存するいくつかのプログラムによってスローされる例外が発生します。」
次に、CMDをリニューアルしました(DOSシェルは起動時にEnv varを読み取るだけなので、Env varを変更するには、更新された値を取得するために新しいシェルを使用する必要があります)
そして最後に ant -f core/build.xml
働いた。
いくつかの答えは時代遅れなので、私は自分自身を提供したいと思います -
ZxingライブラリをAndroidアプリに統合するために提案されているように 彼らのウィキ, 、プロジェクトに2つのJavaファイルを追加する必要があります。
その後 Android Studio 次の行を追加します build.gradle ファイル:
dependencies {
....
compile 'com.google.zxing:core:3.2.1'
}
またはまだ使用している場合 ADT-Pluginとの日食 追加 core.jar にファイル libs プロジェクトのサブディレクトリ(こちら フルスクリーンウィンドウ と フルスクリーンMac):
最後に、このコードをあなたに追加します mainActivity.java:
public void scanQRCode(View v) {
IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
integrator.initiateScan(IntentIntegrator.QR_CODE_TYPES);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult result =
IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (result != null) {
String contents = result.getContents();
if (contents != null) {
showDialog(R.string.result_succeeded, result.toString());
} else {
showDialog(R.string.result_failed,
getString(R.string.result_failed_why));
}
}
}
private void showDialog(int title, CharSequence message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(R.string.ok_button, null);
builder.show();
}
結果のアプリは、インストールと起動を求めます Zxingによるバーコードスキャナーアプリ (スキャン後に自動的にアプリに戻ります):
さらに、構築して実行したい場合 zxingテストアプリ あなた自身のアプリのインスピレーションとして:
その後、4つのJavaファイルが必要です github:
- benchmarkactivity.java
- Benchmarkasynctask.java
- benchmarkitem.java
- zxingtestactivity.java
からの3つのjarファイル Mavenリポジトリ:
- core.jar
- Android-Core.jar
- Android-Integration.jar
(JARファイルを自分で作成できます mvn package
- githubからzxingをチェックしてインストールする場合 蟻 と メイベン コンピューターのツール)。
注:プロジェクトがJARファイルを認識していない場合は、プロジェクトプロパティでJavaバージョンをアップする必要がある場合があります。
見たことがありますか wikiページ Zxing Webサイトで?あなたが見つけるかもしれないようです 入門, DeveloperNotes と スキャンビアインスト 役に立った。
置く
compile 'com.google.zxing:core:2.3.0'
Gradle依存関係に。それと同じくらい簡単です。 Android StudioおよびGradleビルドシステムを使用する前。
Zxingのcore.jarが必要な場合は、そのプロセスをスキップして、事前に構築された瓶を取得できます。 Wikiページを開始します
最新のzxing(2.2)はコアフォルダーの下にcore.jarを持っていませんが、zxingからcore.jarを取得できます。 Mavenリポジトリはこちら
EclipseでZxing 3.2.1をセットアップするためのステップバイステップ
- zxing-master.zipをダウンロードしてください」https://github.com/zxing/zxing"
- zxing-master.zipを解凍し、eclipseを使用してzxing-masterで「android」プロジェクトをインポートします
- core-3.2.1.jarをダウンロードしてください」http://repo1.maven.org/maven2/com/google/zxing/core/3.2.1/"
- 「Android」プロジェクトに「libs」フォルダーを作成し、cor-3.2.1.jarをlibsフォルダーに貼り付けます
- プロジェクトをクリックします:「プロパティ」 - >「Javaコンパイラ」を選択して、レベルを1.7に変更します。次に、1.7を使用するにはAndroid 4.4とコンパイルが必要なため、「Android」「Android」Change "Project" Build "ターゲットをBuild" "をAndroid 4.4.2+にクリックします。
- 「cameraconfigurationutils.java」が「zxing-master/android/app/src/main/java/com/google/zxing/client/android/camera/」に存在しない場合。 「zxing-master/android-core/src/main/java/com/google/zxing/client/android/camera/」からコピーして、プロジェクトに貼り付けることができます。
- プロジェクトを清掃して構築します。プロジェクトが「スイッチ - ケース」に関するエラーを示している場合、それらを「if -else」に変更する必要があります。
- 完了しました。プロジェクトを清掃して構築します。
- 参照リンク: Zxingを使用して、Androidバーコードスキャンアプリを作成します
私はこれを達成するためにすべての可能な方法を試しました、そして、私はJourneyAppsによるXzingのミニファイドバージョンを発見しました。私はそれをEclipseのために移植し、Githubで共有しました。
Eclipseを使用している場合は、このプロジェクトを使用してください。
https://github.com/hiteshsahu/xzing-barcode-scanner-minified-eclipse
スタジオを使用している場合は、このプロジェクトを使用してください。
https://github.com/journeyApps/zxing-android-embedded
利点
アプリに組み込まれたバーコードスキャナーは、PlayStoreを使用してサードパーティのアプリをインストールする必要はありません。
コア、Androidクライアントなどの間で混乱する必要はありません。必要な瓶のみです com.google.zxing:core:3.2.0 これからダウンロードできます
http://mvnrepository.com/artifact/com.google.zxing/core/3.2.0
大量のパッケージを追加する必要はありません 比較については、以下の画像を参照してください
前 :-
後 :-
最も重要な部分は、それらです 高度にカスタマイズ可能 すなわち。フラッシュライトを追加し、フラグメントで使用し、サポートオリエンテーションの変更を使用できます。
このキャプチャアクティビティをで使用できます Cordovaアプリ バーコードスキャンの場合。
アプリマニフェストでのキャプチャアクティビティは次のようになります
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:clearTaskOnLaunch="true"
android:configChanges="orientation|keyboardHidden"
android:exported="false"
android:screenOrientation="fullSensor"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="stateAlwaysHidden" >
<intent-filter>
<action android:name="com.google.zxing.client.android.SCAN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
プラグインは次のようになります
public class BarcodeScanner extends CordovaPlugin {
public static final int REQUEST_CODE = 0x0ba7c0de;
private static final String SCAN = "scan";
private static final String CANCELLED = "cancelled";
private static final String FORMAT = "format";
private static final String TEXT = "text";
private static final String SCAN_INTENT = "com.google.zxing.client.android.SCAN";
private static final String LOG_TAG = "BarcodeScanner";
private CallbackContext callbackContext;
/**
* Constructor.
*/
public BarcodeScanner() {
}
/**
* Executes the request.
*
* This method is called from the WebView thread. To do a non-trivial amount of work, use:
* cordova.getThreadPool().execute(runnable);
*
* To run on the UI thread, use:
* cordova.getActivity().runOnUiThread(runnable);
*
* @param action The action to execute.
* @param args The exec() arguments.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return Whether the action was valid.
*
* @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java
*/
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
this.callbackContext = callbackContext;
if (action.equals(SCAN)) {
scan(args);
} else {
return false;
}
return true;
}
/**
* Starts an intent to scan and decode a barcode.
*/
public void scan(JSONArray args) {
Intent intentScan = new Intent(SCAN_INTENT);
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
// add config as intent extras
if(args.length() > 0) {
JSONObject obj;
JSONArray names;
String key;
Object value;
for(int i=0; i<args.length(); i++) {
try {
obj = args.getJSONObject(i);
} catch(JSONException e) {
Log.i("CordovaLog", e.getLocalizedMessage());
continue;
}
names = obj.names();
for(int j=0; j<names.length(); j++) {
try {
key = names.getString(j);
value = obj.get(key);
if(value instanceof Integer) {
intentScan.putExtra(key, (Integer)value);
} else if(value instanceof String) {
intentScan.putExtra(key, (String)value);
}
} catch(JSONException e) {
Log.i("CordovaLog", e.getLocalizedMessage());
continue;
}
}
}
}
// avoid calling other phonegap apps
intentScan.setPackage(this.cordova.getActivity().getApplicationContext().getPackageName());
this.cordova.startActivityForResult((CordovaPlugin) this, intentScan, REQUEST_CODE);
}
/**
* Called when the barcode scanner intent completes.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
JSONObject obj = new JSONObject();
try {
obj.put(TEXT, intent.getStringExtra("SCAN_RESULT"));
obj.put(FORMAT, intent.getStringExtra("SCAN_RESULT_FORMAT"));
obj.put(CANCELLED, false);
} catch (JSONException e) {
Log.d(LOG_TAG, "JSONException "+e.getMessage());
}
this.callbackContext.success(obj);
} else if (resultCode == Activity.RESULT_CANCELED) {
this.callbackContext.success("");
} else {
this.callbackContext.error("Technical Problem");
}
}
}
}
幸せな統合!!
Zxingの人たちは、1.7でAndroidプロジェクトを簡単に作成できるようになりました。それは以前ほど苦痛ではありません。これは、Android向けのZxingプロジェクトをすばやく作成したい人のための簡単なブログです。
- zxing.orgのzxingソースをチェックアウトします
- EclipseでAndroidプロジェクトを作成します
- main.xmlを削除します
- 「SRC」ディレクトリを右クリックして、インポートを押します。言及された順序で次のディレクトリを閲覧します。インポート用にそれらを1つずつ追加するときは、インポートウィザードの編集フィールドにSRCディレクトリがあることを確認してください。また、左ディレクトリツリーに「com」ディレクトリのみを選択します。 SRCを選択しないでください。
- 芯
- Android-Integration
- アンドロイド
- Android SDKバージョンが9であることを確認してください。
- 言語の1つのstrings.xmlはベビーベッドになります。
Zxing 1.7のAndroidプロジェクト(6月20日チェックアウト)。
http://www.4shared.com/file/bfx8y5ys/zxingjune2010.html (もう利用できません)
Google Play Services(バージョン以降、外部LIBを使用する理由 7.8.0)バーコードデコーダーが含まれています。
生成されたバーコードを解読する方法を書きました。 Bitmap
に String
.
それは正確に要求されていることをします、ただ CaptureActivity
...
したがって、スキップできます android-integration
のライブラリ build.gradle
:
dependencies {
// https://mvnrepository.com/artifact/com.google.zxing
compile('com.google.zxing:core:3.3.0')
compile('com.google.zxing:android-core:3.3.0')
}
次のような方法(実際に生成されたバーコード、Junitテスト内でデコード):
import android.graphics.Bitmap;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.Result;
protected String decode(Bitmap bitmap) {
MultiFormatReader reader = new MultiFormatReader();
String barcode = null;
int[] intArray = new int[bitmap.getWidth() * bitmap.getHeight()];
bitmap.getPixels(intArray, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
LuminanceSource source = new RGBLuminanceSource(bitmap.getWidth(), bitmap.getHeight(), intArray);
BinaryBitmap binary = new BinaryBitmap(new HybridBinarizer(source));
try {
Result result = reader.decode(binary);
// BarcodeFormat format = result.getBarcodeFormat();
// ResultPoint[] points = result.getResultPoints();
// byte[] bytes = result.getRawBytes();
barcode = result.getText();
} catch (NotFoundException e) {
e.printStackTrace();
}
return barcode;
}
最近、iOSとAndroidの両方でGoogle Mobile Visionを使用しました。 Googleバーコードスキャンを使用することを強くお勧めします。どんな方向でもかなり敏感で、処理時間はかなり速いです。 Google Mobile Visionと呼ばれます。
バーコードスキャナーAPIは、あらゆる方向でバーコードをリアルタイムで検出します。また、複数のバーコードを異なる形式で同時に検出および解析することもできます。
https://developers.google.com/vision/
https://codelabs.developers.google.com/codelabs/bar-codes/#0
はるかに簡単なアプローチ。
アプリレベルのGradleファイルに依存関係を含めるだけです
compile 'com.journeyapps:zxing-android-embedded:3.0.1@aar'
compile 'com.google.zxing:core:3.2.0'
XMLファイルに1つのボタンを定義し、oncreate()のJavaファイルのコードを下回るボタンの内側にボタンのonclickリスナーの内側に書き込みます
new IntentIntegrator(this).initiateScan();
javaファイルのoncreate()の後に以下のコードを書く
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
String st_scanned_result = result.getContents();
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
}
}