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.BitMatrix;
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.class.getSimpleName();
56 private static final int WHITE = 0xFFFFFFFF;
57 private static final int BLACK = 0xFF000000;
59 private final Activity activity;
60 private String contents;
61 private String displayContents;
63 private BarcodeFormat format;
65 QRCodeEncoder(Activity activity, Intent intent) {
66 this.activity = activity;
68 throw new IllegalArgumentException("No valid data to encode.");
71 String action = intent.getAction();
72 if (action.equals(Intents.Encode.ACTION)) {
73 if (!encodeContentsFromZXingIntent(intent)) {
74 throw new IllegalArgumentException("No valid data to encode.");
76 } else if (action.equals(Intent.ACTION_SEND)) {
77 if (!encodeContentsFromShareIntent(intent)) {
78 throw new IllegalArgumentException("No valid data to encode.");
83 public void requestBarcode(Handler handler, int pixelResolution) {
84 Thread encodeThread = new EncodeThread(contents, handler, pixelResolution,
89 public String getContents() {
93 public String getDisplayContents() {
94 return displayContents;
97 public String getTitle() {
101 public String getFormat() {
102 return format.toString();
105 // It would be nice if the string encoding lived in the core ZXing library,
106 // but we use platform specific code like PhoneNumberUtils, so it can't.
107 private boolean encodeContentsFromZXingIntent(Intent intent) {
108 // Default to QR_CODE if no format given.
109 String formatString = intent.getStringExtra(Intents.Encode.FORMAT);
111 format = BarcodeFormat.valueOf(formatString);
112 } catch (IllegalArgumentException iae) {
117 if (format == null || BarcodeFormat.QR_CODE.equals(format)) {
118 String type = intent.getStringExtra(Intents.Encode.TYPE);
119 if (type == null || type.length() == 0) {
122 this.format = BarcodeFormat.QR_CODE;
123 encodeQRCodeContents(intent, type);
125 String data = intent.getStringExtra(Intents.Encode.DATA);
126 if (data != null && data.length() != 0) {
128 displayContents = data;
129 title = activity.getString(R.string.contents_text);
132 return contents != null && contents.length() > 0;
135 // Handles send intents from the Contacts app, retrieving a contact as a VCARD.
136 private boolean encodeContentsFromShareIntent(Intent intent) {
137 format = BarcodeFormat.QR_CODE;
139 Uri uri = (Uri)intent.getExtras().getParcelable(Intent.EXTRA_STREAM);
140 InputStream stream = activity.getContentResolver().openInputStream(uri);
141 int length = stream.available();
142 byte[] vcard = new byte[length];
143 stream.read(vcard, 0, length);
144 String vcardString = new String(vcard, "UTF-8");
145 Log.d(TAG, "Encoding share intent content: " + vcardString);
146 Result result = new Result(vcardString, vcard, null, BarcodeFormat.QR_CODE);
147 ParsedResult parsedResult = ResultParser.parseResult(result);
148 if (!(parsedResult instanceof AddressBookParsedResult)) {
151 if (!encodeQRCodeContents((AddressBookParsedResult) parsedResult)) {
154 } catch (FileNotFoundException e) {
156 } catch (IOException e) {
158 } catch (NullPointerException e) {
159 // In case the uri was not found in the Intent.
162 return contents != null && contents.length() > 0;
165 private void encodeQRCodeContents(Intent intent, String type) {
166 if (type.equals(Contents.Type.TEXT)) {
167 String data = intent.getStringExtra(Intents.Encode.DATA);
168 if (data != null && data.length() > 0) {
170 displayContents = data;
171 title = activity.getString(R.string.contents_text);
173 } else if (type.equals(Contents.Type.EMAIL)) {
174 String data = intent.getStringExtra(Intents.Encode.DATA);
175 if (data != null && data.length() > 0) {
176 contents = "mailto:" + data;
177 displayContents = data;
178 title = activity.getString(R.string.contents_email);
180 } else if (type.equals(Contents.Type.PHONE)) {
181 String data = intent.getStringExtra(Intents.Encode.DATA);
182 if (data != null && data.length() > 0) {
183 contents = "tel:" + data;
184 displayContents = PhoneNumberUtils.formatNumber(data);
185 title = activity.getString(R.string.contents_phone);
187 } else if (type.equals(Contents.Type.SMS)) {
188 String data = intent.getStringExtra(Intents.Encode.DATA);
189 if (data != null && data.length() > 0) {
190 contents = "sms:" + data;
191 displayContents = PhoneNumberUtils.formatNumber(data);
192 title = activity.getString(R.string.contents_sms);
194 } else if (type.equals(Contents.Type.CONTACT)) {
195 Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
196 if (bundle != null) {
197 StringBuilder newContents = new StringBuilder();
198 StringBuilder newDisplayContents = new StringBuilder();
199 newContents.append("MECARD:");
200 String name = bundle.getString(Contacts.Intents.Insert.NAME);
201 if (name != null && name.length() > 0) {
202 newContents.append("N:").append(name).append(';');
203 newDisplayContents.append(name);
205 String address = bundle.getString(Contacts.Intents.Insert.POSTAL);
206 if (address != null && address.length() > 0) {
207 newContents.append("ADR:").append(address).append(';');
208 newDisplayContents.append('\n').append(address);
210 for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
211 String phone = bundle.getString(Contents.PHONE_KEYS[x]);
212 if (phone != null && phone.length() > 0) {
213 newContents.append("TEL:").append(phone).append(';');
214 newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
217 for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
218 String email = bundle.getString(Contents.EMAIL_KEYS[x]);
219 if (email != null && email.length() > 0) {
220 newContents.append("EMAIL:").append(email).append(';');
221 newDisplayContents.append('\n').append(email);
224 // Make sure we've encoded at least one field.
225 if (newDisplayContents.length() > 0) {
226 newContents.append(';');
227 contents = newContents.toString();
228 displayContents = newDisplayContents.toString();
229 title = activity.getString(R.string.contents_contact);
232 displayContents = null;
235 } else if (type.equals(Contents.Type.LOCATION)) {
236 Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
237 if (bundle != null) {
238 // These must use Bundle.getFloat(), not getDouble(), it's part of the API.
239 float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
240 float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
241 if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
242 contents = "geo:" + latitude + ',' + longitude;
243 displayContents = latitude + "," + longitude;
244 title = activity.getString(R.string.contents_location);
250 private boolean encodeQRCodeContents(AddressBookParsedResult contact) {
251 StringBuilder newContents = new StringBuilder();
252 StringBuilder newDisplayContents = new StringBuilder();
253 newContents.append("MECARD:");
254 String[] names = contact.getNames();
255 if (names != null && names.length > 0) {
256 newContents.append("N:").append(names[0]).append(';');
257 newDisplayContents.append(names[0]);
259 String[] addresses = contact.getAddresses();
260 if (addresses != null) {
261 for (int x = 0; x < addresses.length; x++) {
262 if (addresses[x] != null && addresses[x].length() > 0) {
263 newContents.append("ADR:").append(addresses[x]).append(';');
264 newDisplayContents.append('\n').append(addresses[x]);
268 String[] phoneNumbers = contact.getPhoneNumbers();
269 if (phoneNumbers != null) {
270 for (int x = 0; x < phoneNumbers.length; x++) {
271 String phone = phoneNumbers[x];
272 if (phone != null && phone.length() > 0) {
273 newContents.append("TEL:").append(phone).append(';');
274 newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
278 String[] emails = contact.getEmails();
279 if (emails != null) {
280 for (int x = 0; x < emails.length; x++) {
281 String email = emails[x];
282 if (email != null && email.length() > 0) {
283 newContents.append("EMAIL:").append(email).append(';');
284 newDisplayContents.append('\n').append(email);
288 String url = contact.getURL();
289 if (url != null && url.length() > 0) {
290 newContents.append("URL:").append(url).append(';');
291 newDisplayContents.append('\n').append(url);
293 // Make sure we've encoded at least one field.
294 if (newDisplayContents.length() > 0) {
295 newContents.append(';');
296 contents = newContents.toString();
297 displayContents = newDisplayContents.toString();
298 title = activity.getString(R.string.contents_contact);
302 displayContents = null;
307 static Bitmap encodeAsBitmap(String contents,
308 BarcodeFormat format,
310 int desiredHeight) throws WriterException {
311 BitMatrix result = new MultiFormatWriter().encode(contents, format,
312 desiredWidth, desiredHeight);
313 int width = result.getWidth();
314 int height = result.getHeight();
315 int[] pixels = new int[width * height];
316 // All are 0, or black, by default
317 for (int y = 0; y < height; y++) {
318 int offset = y * width;
319 for (int x = 0; x < width; x++) {
320 pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
324 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
325 bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
329 private static final class EncodeThread extends Thread {
331 private static final String TAG = EncodeThread.class.getSimpleName();
333 private final String contents;
334 private final Handler handler;
335 private final int pixelResolution;
336 private final BarcodeFormat format;
338 EncodeThread(String contents, Handler handler, int pixelResolution,
339 BarcodeFormat format) {
340 this.contents = contents;
341 this.handler = handler;
342 this.pixelResolution = pixelResolution;
343 this.format = format;
349 Bitmap bitmap = encodeAsBitmap(contents, format, pixelResolution, pixelResolution);
350 Message message = Message.obtain(handler, R.id.encode_succeeded);
351 message.obj = bitmap;
352 message.sendToTarget();
353 } catch (WriterException e) {
354 Log.e(TAG, e.toString());
355 Message message = Message.obtain(handler, R.id.encode_failed);
356 message.sendToTarget();
357 } catch (IllegalArgumentException e) {
358 Log.e(TAG, e.toString());
359 Message message = Message.obtain(handler, R.id.encode_failed);
360 message.sendToTarget();