2 * Copyright (C) 2008 ZXing authors
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.google.zxing.client.android.encode;
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.MultiFormatWriter;
21 import com.google.zxing.Result;
22 import com.google.zxing.WriterException;
23 import com.google.zxing.client.android.Contents;
24 import com.google.zxing.client.android.Intents;
25 import com.google.zxing.client.android.R;
26 import com.google.zxing.client.result.AddressBookParsedResult;
27 import com.google.zxing.client.result.ParsedResult;
28 import com.google.zxing.client.result.ResultParser;
29 import com.google.zxing.common.ByteMatrix;
31 import android.app.Activity;
32 import android.content.Intent;
33 import android.graphics.Bitmap;
34 import android.net.Uri;
35 import android.os.Bundle;
36 import android.os.Handler;
37 import android.os.Message;
38 import android.provider.Contacts;
39 import android.telephony.PhoneNumberUtils;
40 import android.util.Log;
42 import java.io.FileNotFoundException;
43 import java.io.IOException;
44 import java.io.InputStream;
47 * This class does the work of decoding the user's request and extracting all the data
48 * to be encoded in a barcode.
50 * @author dswitkin@google.com (Daniel Switkin)
52 final class QRCodeEncoder {
54 private static final String TAG = "QRCodeEncoder";
56 private final Activity activity;
57 private String contents;
58 private String displayContents;
60 private BarcodeFormat format;
62 QRCodeEncoder(Activity activity, Intent intent) {
63 this.activity = activity;
65 throw new IllegalArgumentException("No valid data to encode.");
68 String action = intent.getAction();
69 if (action.equals(Intents.Encode.ACTION)) {
70 if (!encodeContentsFromZXingIntent(intent)) {
71 throw new IllegalArgumentException("No valid data to encode.");
73 } else if (action.equals(Intent.ACTION_SEND)) {
74 if (!encodeContentsFromShareIntent(intent)) {
75 throw new IllegalArgumentException("No valid data to encode.");
80 public void requestBarcode(Handler handler, int pixelResolution) {
81 Thread encodeThread = new EncodeThread(contents, handler, pixelResolution,
86 public String getContents() {
90 public String getDisplayContents() {
91 return displayContents;
94 public String getTitle() {
98 public String getFormat() {
99 return format.toString();
102 // It would be nice if the string encoding lived in the core ZXing library,
103 // but we use platform specific code like PhoneNumberUtils, so it can't.
104 private boolean encodeContentsFromZXingIntent(Intent intent) {
105 // Default to QR_CODE if no format given.
106 String format = intent.getStringExtra(Intents.Encode.FORMAT);
107 if (format == null || format.length() == 0 ||
108 format.equals(Contents.Format.QR_CODE)) {
109 String type = intent.getStringExtra(Intents.Encode.TYPE);
110 if (type == null || type.length() == 0) {
113 this.format = BarcodeFormat.QR_CODE;
114 encodeQRCodeContents(intent, type);
116 String data = intent.getStringExtra(Intents.Encode.DATA);
117 if (data != null && data.length() != 0) {
119 displayContents = data;
120 title = activity.getString(R.string.contents_text);
121 if (format.equals(Contents.Format.CODE_128)) {
122 this.format = BarcodeFormat.CODE_128;
123 } else if (format.equals(Contents.Format.CODE_39)) {
124 this.format = BarcodeFormat.CODE_39;
125 } else if (format.equals(Contents.Format.EAN_8)) {
126 this.format = BarcodeFormat.EAN_8;
127 } else if (format.equals(Contents.Format.EAN_13)) {
128 this.format = BarcodeFormat.EAN_13;
129 } else if (format.equals(Contents.Format.UPC_A)) {
130 this.format = BarcodeFormat.UPC_A;
131 } else if (format.equals(Contents.Format.UPC_E)) {
132 this.format = BarcodeFormat.UPC_E;
136 return contents != null && contents.length() > 0;
139 // Handles send intents from the Contacts app, retrieving a contact as a VCARD.
140 private boolean encodeContentsFromShareIntent(Intent intent) {
141 format = BarcodeFormat.QR_CODE;
143 Uri uri = (Uri)intent.getExtras().getParcelable(Intent.EXTRA_STREAM);
144 InputStream stream = activity.getContentResolver().openInputStream(uri);
145 int length = stream.available();
146 byte[] vcard = new byte[length];
147 stream.read(vcard, 0, length);
148 String vcardString = new String(vcard, "UTF-8");
149 Log.d(TAG, "Encoding share intent content: " + vcardString);
150 Result result = new Result(vcardString, vcard, null, BarcodeFormat.QR_CODE);
151 ParsedResult parsedResult = ResultParser.parseResult(result);
152 if (!(parsedResult instanceof AddressBookParsedResult)) {
155 if (!encodeQRCodeContents((AddressBookParsedResult) parsedResult)) {
158 } catch (FileNotFoundException e) {
160 } catch (IOException e) {
162 } catch (NullPointerException e) {
163 // In case the uri was not found in the Intent.
166 return contents != null && contents.length() > 0;
169 private void encodeQRCodeContents(Intent intent, String type) {
170 if (type.equals(Contents.Type.TEXT)) {
171 String data = intent.getStringExtra(Intents.Encode.DATA);
172 if (data != null && data.length() > 0) {
174 displayContents = data;
175 title = activity.getString(R.string.contents_text);
177 } else if (type.equals(Contents.Type.EMAIL)) {
178 String data = intent.getStringExtra(Intents.Encode.DATA);
179 if (data != null && data.length() > 0) {
180 contents = "mailto:" + data;
181 displayContents = data;
182 title = activity.getString(R.string.contents_email);
184 } else if (type.equals(Contents.Type.PHONE)) {
185 String data = intent.getStringExtra(Intents.Encode.DATA);
186 if (data != null && data.length() > 0) {
187 contents = "tel:" + data;
188 displayContents = PhoneNumberUtils.formatNumber(data);
189 title = activity.getString(R.string.contents_phone);
191 } else if (type.equals(Contents.Type.SMS)) {
192 String data = intent.getStringExtra(Intents.Encode.DATA);
193 if (data != null && data.length() > 0) {
194 contents = "sms:" + data;
195 displayContents = PhoneNumberUtils.formatNumber(data);
196 title = activity.getString(R.string.contents_sms);
198 } else if (type.equals(Contents.Type.CONTACT)) {
199 Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
200 if (bundle != null) {
201 StringBuilder newContents = new StringBuilder();
202 StringBuilder newDisplayContents = new StringBuilder();
203 newContents.append("MECARD:");
204 String name = bundle.getString(Contacts.Intents.Insert.NAME);
205 if (name != null && name.length() > 0) {
206 newContents.append("N:").append(name).append(';');
207 newDisplayContents.append(name);
209 String address = bundle.getString(Contacts.Intents.Insert.POSTAL);
210 if (address != null && address.length() > 0) {
211 newContents.append("ADR:").append(address).append(';');
212 newDisplayContents.append('\n').append(address);
214 for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
215 String phone = bundle.getString(Contents.PHONE_KEYS[x]);
216 if (phone != null && phone.length() > 0) {
217 newContents.append("TEL:").append(phone).append(';');
218 newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
221 for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
222 String email = bundle.getString(Contents.EMAIL_KEYS[x]);
223 if (email != null && email.length() > 0) {
224 newContents.append("EMAIL:").append(email).append(';');
225 newDisplayContents.append('\n').append(email);
228 // Make sure we've encoded at least one field.
229 if (newDisplayContents.length() > 0) {
230 newContents.append(';');
231 contents = newContents.toString();
232 displayContents = newDisplayContents.toString();
233 title = activity.getString(R.string.contents_contact);
236 displayContents = null;
239 } else if (type.equals(Contents.Type.LOCATION)) {
240 Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
241 if (bundle != null) {
242 // These must use Bundle.getFloat(), not getDouble(), it's part of the API.
243 float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
244 float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
245 if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
246 contents = "geo:" + latitude + ',' + longitude;
247 displayContents = latitude + "," + longitude;
248 title = activity.getString(R.string.contents_location);
254 private boolean encodeQRCodeContents(AddressBookParsedResult contact) {
255 StringBuilder newContents = new StringBuilder();
256 StringBuilder newDisplayContents = new StringBuilder();
257 newContents.append("MECARD:");
258 String[] names = contact.getNames();
259 if (names != null && names.length > 0) {
260 newContents.append("N:").append(names[0]).append(';');
261 newDisplayContents.append(names[0]);
263 String[] addresses = contact.getAddresses();
264 if (addresses != null) {
265 for (int x = 0; x < addresses.length; x++) {
266 if (addresses[x] != null && addresses[x].length() > 0) {
267 newContents.append("ADR:").append(addresses[x]).append(';');
268 newDisplayContents.append('\n').append(addresses[x]);
272 String[] phoneNumbers = contact.getPhoneNumbers();
273 if (phoneNumbers != null) {
274 for (int x = 0; x < phoneNumbers.length; x++) {
275 String phone = phoneNumbers[x];
276 if (phone != null && phone.length() > 0) {
277 newContents.append("TEL:").append(phone).append(';');
278 newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
282 String[] emails = contact.getEmails();
283 if (emails != null) {
284 for (int x = 0; x < emails.length; x++) {
285 String email = emails[x];
286 if (email != null && email.length() > 0) {
287 newContents.append("EMAIL:").append(email).append(';');
288 newDisplayContents.append('\n').append(email);
292 String url = contact.getURL();
293 if (url != null && url.length() > 0) {
294 newContents.append("URL:").append(url).append(';');
295 newDisplayContents.append('\n').append(url);
297 // Make sure we've encoded at least one field.
298 if (newDisplayContents.length() > 0) {
299 newContents.append(';');
300 contents = newContents.toString();
301 displayContents = newDisplayContents.toString();
302 title = activity.getString(R.string.contents_contact);
306 displayContents = null;
311 private static final class EncodeThread extends Thread {
312 private static final String TAG = "EncodeThread";
314 private final String contents;
315 private final Handler handler;
316 private final int pixelResolution;
317 private final BarcodeFormat format;
319 EncodeThread(String contents, Handler handler, int pixelResolution,
320 BarcodeFormat format) {
321 this.contents = contents;
322 this.handler = handler;
323 this.pixelResolution = pixelResolution;
324 this.format = format;
330 ByteMatrix result = new MultiFormatWriter().encode(contents, format,
331 pixelResolution, pixelResolution);
332 int width = result.getWidth();
333 int height = result.getHeight();
334 byte[][] array = result.getArray();
335 int[] pixels = new int[width * height];
336 for (int y = 0; y < height; y++) {
337 for (int x = 0; x < width; x++) {
338 int grey = array[y][x] & 0xff;
339 // pixels[y * width + x] = (0xff << 24) | (grey << 16) | (grey << 8) | grey;
340 pixels[y * width + x] = 0xff000000 | (0x00010101 * grey);
344 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
345 bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
346 Message message = Message.obtain(handler, R.id.encode_succeeded);
347 message.obj = bitmap;
348 message.sendToTarget();
349 } catch (WriterException e) {
350 Log.e(TAG, e.toString());
351 Message message = Message.obtain(handler, R.id.encode_failed);
352 message.sendToTarget();
353 } catch (IllegalArgumentException e) {
354 Log.e(TAG, e.toString());
355 Message message = Message.obtain(handler, R.id.encode_failed);
356 message.sendToTarget();