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.result;
19 import com.google.zxing.client.android.Contents;
20 import com.google.zxing.client.android.Intents;
21 import com.google.zxing.client.android.LocaleManager;
22 import com.google.zxing.client.android.PreferencesActivity;
23 import com.google.zxing.client.android.R;
24 import com.google.zxing.client.android.book.SearchBookContentsActivity;
25 import com.google.zxing.client.result.ParsedResult;
26 import com.google.zxing.client.result.ParsedResultType;
28 import android.app.Activity;
29 import android.app.AlertDialog;
30 import android.app.SearchManager;
31 import android.content.ActivityNotFoundException;
32 import android.content.DialogInterface;
33 import android.content.Intent;
34 import android.content.SharedPreferences;
35 import android.content.pm.PackageManager;
36 import android.net.Uri;
37 import android.preference.PreferenceManager;
38 import android.provider.Contacts;
40 import java.text.DateFormat;
41 import java.text.ParsePosition;
42 import java.text.SimpleDateFormat;
43 import java.util.Calendar;
44 import java.util.Date;
45 import java.util.GregorianCalendar;
48 * A base class for the Android-specific barcode handlers. These allow the app to polymorphically
49 * suggest the appropriate actions for each data type.
51 * This class also contains a bunch of utility methods to take common actions like opening a URL.
52 * They could easily be moved into a helper object, but it can't be static because the Activity
53 * instance is needed to launch an intent.
55 * @author dswitkin@google.com (Daniel Switkin)
57 public abstract class ResultHandler {
58 private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
59 private static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
61 private static final String GOOGLE_SHOPPER_PACKAGE = "com.google.android.apps.shopper";
62 private static final String GOOGLE_SHOPPER_ACTIVITY = GOOGLE_SHOPPER_PACKAGE +
63 ".results.SearchResultsActivity";
64 private static final String MARKET_URI_PREFIX = "market://search?q=pname:";
65 private static final String MARKET_REFERRER_SUFFIX =
66 "&referrer=utm_source%3Dbarcodescanner%26utm_medium%3Dapps%26utm_campaign%3Dscan";
68 public static final int MAX_BUTTON_COUNT = 4;
70 private final ParsedResult result;
71 private final Activity activity;
73 private final DialogInterface.OnClickListener shopperMarketListener =
74 new DialogInterface.OnClickListener() {
75 public void onClick(DialogInterface dialogInterface, int which) {
76 launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_URI_PREFIX +
77 GOOGLE_SHOPPER_PACKAGE + MARKET_REFERRER_SUFFIX)));
81 ResultHandler(Activity activity, ParsedResult result) {
83 this.activity = activity;
86 ParsedResult getResult() {
91 * Indicates how many buttons the derived class wants shown.
93 * @return The integer button count.
95 public abstract int getButtonCount();
98 * The text of the nth action button.
100 * @param index From 0 to getButtonCount() - 1
101 * @return The button text as a resource ID
103 public abstract int getButtonText(int index);
107 * Execute the action which corresponds to the nth button.
109 * @param index The button that was clicked.
111 public abstract void handleButtonPress(int index);
114 * Create a possibly styled string for the contents of the current barcode.
116 * @return The text to be displayed.
118 public CharSequence getDisplayContents() {
119 String contents = result.getDisplayResult();
120 return contents.replace("\r", "");
124 * A string describing the kind of barcode that was found, e.g. "Found contact info".
126 * @return The resource ID of the string.
128 public abstract int getDisplayTitle();
131 * A convenience method to get the parsed type. Should not be overridden.
133 * @return The parsed type, e.g. URI or ISBN
135 public final ParsedResultType getType() {
136 return result.getType();
140 * Sends an intent to create a new calendar event by prepopulating the Add Event UI. Older
141 * versions of the system have a bug where the event title will not be filled out.
143 * @param summary A description of the event
144 * @param start The start time as yyyyMMdd or yyyyMMdd'T'HHmmss or yyyyMMdd'T'HHmmss'Z'
145 * @param end The end time as yyyyMMdd or yyyyMMdd'T'HHmmss or yyyyMMdd'T'HHmmss'Z'
147 final void addCalendarEvent(String summary, String start, String end) {
148 Intent intent = new Intent(Intent.ACTION_EDIT);
149 intent.setType("vnd.android.cursor.item/event");
150 intent.putExtra("beginTime", calculateMilliseconds(start));
151 if (start.length() == 8) {
152 intent.putExtra("allDay", true);
154 intent.putExtra("endTime", calculateMilliseconds(end));
155 intent.putExtra("title", summary);
156 launchIntent(intent);
159 private static long calculateMilliseconds(String when) {
160 if (when.length() == 8) {
161 // Only contains year/month/day
163 synchronized (DATE_FORMAT) {
164 date = DATE_FORMAT.parse(when, new ParsePosition(0));
166 return date.getTime();
168 // The when string can be local time, or UTC if it ends with a Z
170 synchronized (DATE_TIME_FORMAT) {
171 date = DATE_TIME_FORMAT.parse(when.substring(0, 15), new ParsePosition(0));
173 long milliseconds = date.getTime();
174 if (when.length() == 16 && when.charAt(15) == 'Z') {
175 Calendar calendar = new GregorianCalendar();
176 int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
177 milliseconds += offset;
183 final void addContact(String[] names, String[] phoneNumbers, String[] emails, String note,
184 String address, String org, String title) {
186 // Only use the first name in the array, if present.
187 Intent intent = new Intent(Contacts.Intents.Insert.ACTION, Contacts.People.CONTENT_URI);
188 putExtra(intent, Contacts.Intents.Insert.NAME, names != null ? names[0] : null);
190 int phoneCount = Math.min((phoneNumbers != null) ? phoneNumbers.length : 0,
191 Contents.PHONE_KEYS.length);
192 for (int x = 0; x < phoneCount; x++) {
193 putExtra(intent, Contents.PHONE_KEYS[x], phoneNumbers[x]);
196 int emailCount = Math.min((emails != null) ? emails.length : 0, Contents.EMAIL_KEYS.length);
197 for (int x = 0; x < emailCount; x++) {
198 putExtra(intent, Contents.EMAIL_KEYS[x], emails[x]);
201 putExtra(intent, Contacts.Intents.Insert.NOTES, note);
202 putExtra(intent, Contacts.Intents.Insert.POSTAL, address);
203 putExtra(intent, Contacts.Intents.Insert.COMPANY, org);
204 putExtra(intent, Contacts.Intents.Insert.JOB_TITLE, title);
205 launchIntent(intent);
208 final void shareByEmail(String contents) {
209 sendEmailFromUri("mailto:", activity.getString(R.string.msg_share_subject_line), contents);
212 final void sendEmail(String address, String subject, String body) {
213 sendEmailFromUri("mailto:" + address, subject, body);
216 // Use public Intent fields rather than private GMail app fields to specify subject and body.
217 final void sendEmailFromUri(String uri, String subject, String body) {
218 Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse(uri));
219 putExtra(intent, Intent.EXTRA_SUBJECT, subject);
220 putExtra(intent, Intent.EXTRA_TEXT, body);
221 intent.setType("text/plain");
222 launchIntent(intent);
225 final void shareBySMS(String contents) {
226 sendSMSFromUri("smsto:", activity.getString(R.string.msg_share_subject_line) + ":\n" +
230 final void sendSMS(String phoneNumber, String body) {
231 sendSMSFromUri("smsto:" + phoneNumber, body);
234 final void sendSMSFromUri(String uri, String body) {
235 Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
236 putExtra(intent, "sms_body", body);
237 // Exit the app once the SMS is sent
238 intent.putExtra("compose_mode", true);
239 launchIntent(intent);
242 final void sendMMS(String phoneNumber, String subject, String body) {
243 sendMMSFromUri("mmsto:" + phoneNumber, subject, body);
246 final void sendMMSFromUri(String uri, String subject, String body) {
247 Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
248 // The Messaging app needs to see a valid subject or else it will treat this an an SMS.
249 if (subject == null || subject.length() == 0) {
250 putExtra(intent, "subject", activity.getString(R.string.msg_default_mms_subject));
252 putExtra(intent, "subject", subject);
254 putExtra(intent, "sms_body", body);
255 intent.putExtra("compose_mode", true);
256 launchIntent(intent);
259 final void dialPhone(String phoneNumber) {
260 launchIntent(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));
263 final void dialPhoneFromUri(String uri) {
264 launchIntent(new Intent(Intent.ACTION_DIAL, Uri.parse(uri)));
267 final void openMap(String geoURI) {
268 launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(geoURI)));
272 * Do a geo search using the address as the query.
274 * @param address The address to find
275 * @param title An optional title, e.g. the name of the business at this address
277 final void searchMap(String address, String title) {
278 String query = address;
279 if (title != null && title.length() > 0) {
280 query = query + " (" + title + ')';
282 launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(query))));
285 final void getDirections(double latitude, double longitude) {
286 launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google." +
287 LocaleManager.getCountryTLD() + "/maps?f=d&daddr=" + latitude + ',' + longitude)));
290 // Uses the mobile-specific version of Product Search, which is formatted for small screens.
291 final void openProductSearch(String upc) {
292 Uri uri = Uri.parse("http://www.google." + LocaleManager.getProductSearchCountryTLD() +
293 "/m/products?q=" + upc + "&source=zxing");
294 launchIntent(new Intent(Intent.ACTION_VIEW, uri));
297 final void openBookSearch(String isbn) {
298 Uri uri = Uri.parse("http://books.google." + LocaleManager.getBookSearchCountryTLD() +
299 "/books?vid=isbn" + isbn);
300 launchIntent(new Intent(Intent.ACTION_VIEW, uri));
303 final void searchBookContents(String isbn) {
304 Intent intent = new Intent(Intents.SearchBookContents.ACTION);
305 intent.setClassName(activity, SearchBookContentsActivity.class.getName());
306 putExtra(intent, Intents.SearchBookContents.ISBN, isbn);
307 launchIntent(intent);
310 final void openURL(String url) {
311 launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
314 final void webSearch(String query) {
315 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
316 intent.putExtra("query", query);
317 launchIntent(intent);
320 final void openGoogleShopper(String query) {
322 activity.getPackageManager().getPackageInfo(GOOGLE_SHOPPER_PACKAGE, 0);
323 // If we didn't throw, Shopper is installed, so launch it.
324 Intent intent = new Intent(Intent.ACTION_SEARCH);
325 intent.setClassName(GOOGLE_SHOPPER_PACKAGE, GOOGLE_SHOPPER_ACTIVITY);
326 intent.putExtra(SearchManager.QUERY, query);
327 activity.startActivity(intent);
328 } catch (PackageManager.NameNotFoundException e) {
329 // Otherwise offer to install it from Market.
330 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
331 builder.setTitle(R.string.msg_google_shopper_missing);
332 builder.setMessage(R.string.msg_install_google_shopper);
333 builder.setIcon(R.drawable.shopper_icon);
334 builder.setPositiveButton(R.string.button_ok, shopperMarketListener);
335 builder.setNegativeButton(R.string.button_cancel, null);
340 void launchIntent(Intent intent) {
341 if (intent != null) {
343 activity.startActivity(intent);
344 } catch (ActivityNotFoundException e) {
345 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
346 builder.setTitle(R.string.app_name);
347 builder.setMessage(R.string.msg_intent_failed);
348 builder.setPositiveButton(R.string.button_ok, null);
354 private static void putExtra(Intent intent, String key, String value) {
355 if (value != null && value.length() > 0) {
356 intent.putExtra(key, value);
360 protected void showNotOurResults(int index, AlertDialog.OnClickListener proceedListener) {
361 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
362 if (prefs.getBoolean(PreferencesActivity.KEY_NOT_OUR_RESULTS_SHOWN, false)) {
363 // already seen it, just proceed
364 proceedListener.onClick(null, index);
366 // note the user has seen it
367 prefs.edit().putBoolean(PreferencesActivity.KEY_NOT_OUR_RESULTS_SHOWN, true).commit();
368 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
369 builder.setMessage(R.string.msg_not_our_results);
370 builder.setPositiveButton(R.string.button_ok, proceedListener);