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.Result;
20 import com.google.zxing.client.android.Contents;
21 import com.google.zxing.client.android.Intents;
22 import com.google.zxing.client.android.LocaleManager;
23 import com.google.zxing.client.android.PreferencesActivity;
24 import com.google.zxing.client.android.R;
25 import com.google.zxing.client.android.book.SearchBookContentsActivity;
26 import com.google.zxing.client.android.wifi.WifiActivity;
27 import com.google.zxing.client.result.ParsedResult;
28 import com.google.zxing.client.result.ParsedResultType;
29 import com.google.zxing.client.result.WifiParsedResult;
31 import android.app.Activity;
32 import android.app.AlertDialog;
33 import android.app.SearchManager;
34 import android.content.ActivityNotFoundException;
35 import android.content.DialogInterface;
36 import android.content.Intent;
37 import android.content.SharedPreferences;
38 import android.content.pm.PackageManager;
39 import android.net.Uri;
40 import android.preference.PreferenceManager;
41 import android.provider.Contacts;
42 import android.view.View;
43 import android.widget.Button;
45 import java.text.DateFormat;
46 import java.text.ParsePosition;
47 import java.text.SimpleDateFormat;
48 import java.util.Calendar;
49 import java.util.Date;
50 import java.util.GregorianCalendar;
53 * A base class for the Android-specific barcode handlers. These allow the app to polymorphically
54 * suggest the appropriate actions for each data type.
56 * This class also contains a bunch of utility methods to take common actions like opening a URL.
57 * They could easily be moved into a helper object, but it can't be static because the Activity
58 * instance is needed to launch an intent.
60 * @author dswitkin@google.com (Daniel Switkin)
62 public abstract class ResultHandler {
63 private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
64 private static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
66 private static final String GOOGLE_SHOPPER_PACKAGE = "com.google.android.apps.shopper";
67 private static final String GOOGLE_SHOPPER_ACTIVITY = GOOGLE_SHOPPER_PACKAGE +
68 ".results.SearchResultsActivity";
69 private static final String MARKET_URI_PREFIX = "market://search?q=pname:";
70 private static final String MARKET_REFERRER_SUFFIX =
71 "&referrer=utm_source%3Dbarcodescanner%26utm_medium%3Dapps%26utm_campaign%3Dscan";
73 public static final int MAX_BUTTON_COUNT = 4;
75 private final ParsedResult result;
76 private final Activity activity;
77 private final Result rawResult;
78 private final String customProductSearch;
80 private final DialogInterface.OnClickListener shopperMarketListener =
81 new DialogInterface.OnClickListener() {
82 public void onClick(DialogInterface dialogInterface, int which) {
83 launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_URI_PREFIX +
84 GOOGLE_SHOPPER_PACKAGE + MARKET_REFERRER_SUFFIX)));
88 ResultHandler(Activity activity, ParsedResult result) {
89 this(activity, result, null);
92 ResultHandler(Activity activity, ParsedResult result, Result rawResult) {
94 this.activity = activity;
95 this.rawResult = rawResult;
96 this.customProductSearch = parseCustomSearchURL();
99 ParsedResult getResult() {
103 boolean hasCustomProductSearch() {
104 return customProductSearch != null;
108 * Indicates how many buttons the derived class wants shown.
110 * @return The integer button count.
112 public abstract int getButtonCount();
115 * The text of the nth action button.
117 * @param index From 0 to getButtonCount() - 1
118 * @return The button text as a resource ID
120 public abstract int getButtonText(int index);
124 * Execute the action which corresponds to the nth button.
126 * @param index The button that was clicked.
128 public abstract void handleButtonPress(int index);
131 * The Google Shopper button is special and is not handled by the abstract button methods above.
133 * @param listener The on click listener to install for this button.
135 protected void showGoogleShopperButton(View.OnClickListener listener) {
136 Button shopperButton = (Button) activity.findViewById(R.id.shopper_button);
137 shopperButton.setVisibility(View.VISIBLE);
138 shopperButton.setOnClickListener(listener);
142 * Create a possibly styled string for the contents of the current barcode.
144 * @return The text to be displayed.
146 public CharSequence getDisplayContents() {
147 String contents = result.getDisplayResult();
148 return contents.replace("\r", "");
152 * A string describing the kind of barcode that was found, e.g. "Found contact info".
154 * @return The resource ID of the string.
156 public abstract int getDisplayTitle();
159 * A convenience method to get the parsed type. Should not be overridden.
161 * @return The parsed type, e.g. URI or ISBN
163 public final ParsedResultType getType() {
164 return result.getType();
168 * Sends an intent to create a new calendar event by prepopulating the Add Event UI. Older
169 * versions of the system have a bug where the event title will not be filled out.
171 * @param summary A description of the event
172 * @param start The start time as yyyyMMdd or yyyyMMdd'T'HHmmss or yyyyMMdd'T'HHmmss'Z'
173 * @param end The end time as yyyyMMdd or yyyyMMdd'T'HHmmss or yyyyMMdd'T'HHmmss'Z'
174 * @param location a text description of the event location
175 * @param description a text description of the event itself
177 final void addCalendarEvent(String summary,
181 String description) {
182 Intent intent = new Intent(Intent.ACTION_EDIT);
183 intent.setType("vnd.android.cursor.item/event");
184 intent.putExtra("beginTime", calculateMilliseconds(start));
185 if (start.length() == 8) {
186 intent.putExtra("allDay", true);
191 intent.putExtra("endTime", calculateMilliseconds(end));
192 intent.putExtra("title", summary);
193 intent.putExtra("eventLocation", location);
194 intent.putExtra("description", description);
195 launchIntent(intent);
198 private static long calculateMilliseconds(String when) {
199 if (when.length() == 8) {
200 // Only contains year/month/day
202 synchronized (DATE_FORMAT) {
203 date = DATE_FORMAT.parse(when, new ParsePosition(0));
205 return date.getTime();
207 // The when string can be local time, or UTC if it ends with a Z
209 synchronized (DATE_TIME_FORMAT) {
210 date = DATE_TIME_FORMAT.parse(when.substring(0, 15), new ParsePosition(0));
212 long milliseconds = date.getTime();
213 if (when.length() == 16 && when.charAt(15) == 'Z') {
214 Calendar calendar = new GregorianCalendar();
215 int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
216 milliseconds += offset;
222 final void addContact(String[] names, String[] phoneNumbers, String[] emails, String note,
223 String address, String org, String title) {
225 // Only use the first name in the array, if present.
226 Intent intent = new Intent(Contacts.Intents.Insert.ACTION, Contacts.People.CONTENT_URI);
227 putExtra(intent, Contacts.Intents.Insert.NAME, names != null ? names[0] : null);
229 int phoneCount = Math.min((phoneNumbers != null) ? phoneNumbers.length : 0,
230 Contents.PHONE_KEYS.length);
231 for (int x = 0; x < phoneCount; x++) {
232 putExtra(intent, Contents.PHONE_KEYS[x], phoneNumbers[x]);
235 int emailCount = Math.min((emails != null) ? emails.length : 0, Contents.EMAIL_KEYS.length);
236 for (int x = 0; x < emailCount; x++) {
237 putExtra(intent, Contents.EMAIL_KEYS[x], emails[x]);
240 putExtra(intent, Contacts.Intents.Insert.NOTES, note);
241 putExtra(intent, Contacts.Intents.Insert.POSTAL, address);
242 putExtra(intent, Contacts.Intents.Insert.COMPANY, org);
243 putExtra(intent, Contacts.Intents.Insert.JOB_TITLE, title);
244 launchIntent(intent);
247 final void shareByEmail(String contents) {
248 sendEmailFromUri("mailto:", null, activity.getString(R.string.msg_share_subject_line), contents);
251 final void sendEmail(String address, String subject, String body) {
252 sendEmailFromUri("mailto:" + address, address, subject, body);
255 // Use public Intent fields rather than private GMail app fields to specify subject and body.
256 final void sendEmailFromUri(String uri, String email, String subject, String body) {
257 Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse(uri));
259 intent.putExtra(Intent.EXTRA_EMAIL, new String[] {email});
261 putExtra(intent, Intent.EXTRA_SUBJECT, subject);
262 putExtra(intent, Intent.EXTRA_TEXT, body);
263 intent.setType("text/plain");
264 launchIntent(intent);
267 final void shareBySMS(String contents) {
268 sendSMSFromUri("smsto:", activity.getString(R.string.msg_share_subject_line) + ":\n" +
272 final void sendSMS(String phoneNumber, String body) {
273 sendSMSFromUri("smsto:" + phoneNumber, body);
276 final void sendSMSFromUri(String uri, String body) {
277 Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
278 putExtra(intent, "sms_body", body);
279 // Exit the app once the SMS is sent
280 intent.putExtra("compose_mode", true);
281 launchIntent(intent);
284 final void sendMMS(String phoneNumber, String subject, String body) {
285 sendMMSFromUri("mmsto:" + phoneNumber, subject, body);
288 final void sendMMSFromUri(String uri, String subject, String body) {
289 Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
290 // The Messaging app needs to see a valid subject or else it will treat this an an SMS.
291 if (subject == null || subject.length() == 0) {
292 putExtra(intent, "subject", activity.getString(R.string.msg_default_mms_subject));
294 putExtra(intent, "subject", subject);
296 putExtra(intent, "sms_body", body);
297 intent.putExtra("compose_mode", true);
298 launchIntent(intent);
301 final void dialPhone(String phoneNumber) {
302 launchIntent(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));
305 final void dialPhoneFromUri(String uri) {
306 launchIntent(new Intent(Intent.ACTION_DIAL, Uri.parse(uri)));
309 final void openMap(String geoURI) {
310 launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(geoURI)));
314 * Do a geo search using the address as the query.
316 * @param address The address to find
317 * @param title An optional title, e.g. the name of the business at this address
319 final void searchMap(String address, String title) {
320 String query = address;
321 if (title != null && title.length() > 0) {
322 query = query + " (" + title + ')';
324 launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(query))));
327 final void getDirections(double latitude, double longitude) {
328 launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google." +
329 LocaleManager.getCountryTLD() + "/maps?f=d&daddr=" + latitude + ',' + longitude)));
332 // Uses the mobile-specific version of Product Search, which is formatted for small screens.
333 final void openProductSearch(String upc) {
334 Uri uri = Uri.parse("http://www.google." + LocaleManager.getProductSearchCountryTLD() +
335 "/m/products?q=" + upc + "&source=zxing");
336 launchIntent(new Intent(Intent.ACTION_VIEW, uri));
339 final void openBookSearch(String isbn) {
340 Uri uri = Uri.parse("http://books.google." + LocaleManager.getBookSearchCountryTLD() +
341 "/books?vid=isbn" + isbn);
342 launchIntent(new Intent(Intent.ACTION_VIEW, uri));
345 final void searchBookContents(String isbn) {
346 Intent intent = new Intent(Intents.SearchBookContents.ACTION);
347 intent.setClassName(activity, SearchBookContentsActivity.class.getName());
348 putExtra(intent, Intents.SearchBookContents.ISBN, isbn);
349 launchIntent(intent);
352 final void wifiConnect(WifiParsedResult wifiResult) {
353 Intent intent = new Intent(Intents.WifiConnect.ACTION);
354 intent.setClassName(activity, WifiActivity.class.getName());
355 putExtra(intent, Intents.WifiConnect.SSID, wifiResult.getSsid());
356 putExtra(intent, Intents.WifiConnect.TYPE, wifiResult.getNetworkEncryption());
357 putExtra(intent, Intents.WifiConnect.PASSWORD, wifiResult.getPassword());
358 launchIntent(intent);
361 final void openURL(String url) {
362 launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
365 final void webSearch(String query) {
366 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
367 intent.putExtra("query", query);
368 launchIntent(intent);
371 final void openGoogleShopper(String query) {
373 activity.getPackageManager().getPackageInfo(GOOGLE_SHOPPER_PACKAGE, 0);
374 // If we didn't throw, Shopper is installed, so launch it.
375 Intent intent = new Intent(Intent.ACTION_SEARCH);
376 intent.setClassName(GOOGLE_SHOPPER_PACKAGE, GOOGLE_SHOPPER_ACTIVITY);
377 intent.putExtra(SearchManager.QUERY, query);
378 activity.startActivity(intent);
379 } catch (PackageManager.NameNotFoundException e) {
380 // Otherwise offer to install it from Market.
381 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
382 builder.setTitle(R.string.msg_google_shopper_missing);
383 builder.setMessage(R.string.msg_install_google_shopper);
384 builder.setIcon(R.drawable.shopper_icon);
385 builder.setPositiveButton(R.string.button_ok, shopperMarketListener);
386 builder.setNegativeButton(R.string.button_cancel, null);
391 void launchIntent(Intent intent) {
392 if (intent != null) {
393 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
395 activity.startActivity(intent);
396 } catch (ActivityNotFoundException e) {
397 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
398 builder.setTitle(R.string.app_name);
399 builder.setMessage(R.string.msg_intent_failed);
400 builder.setPositiveButton(R.string.button_ok, null);
406 private static void putExtra(Intent intent, String key, String value) {
407 if (value != null && value.length() > 0) {
408 intent.putExtra(key, value);
412 protected void showNotOurResults(int index, AlertDialog.OnClickListener proceedListener) {
413 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
414 if (prefs.getBoolean(PreferencesActivity.KEY_NOT_OUR_RESULTS_SHOWN, false)) {
415 // already seen it, just proceed
416 proceedListener.onClick(null, index);
418 // note the user has seen it
419 prefs.edit().putBoolean(PreferencesActivity.KEY_NOT_OUR_RESULTS_SHOWN, true).commit();
420 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
421 builder.setMessage(R.string.msg_not_our_results);
422 builder.setPositiveButton(R.string.button_ok, proceedListener);
427 private String parseCustomSearchURL() {
428 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
429 String customProductSearch = prefs.getString(PreferencesActivity.KEY_CUSTOM_PRODUCT_SEARCH, null);
430 if (customProductSearch != null && customProductSearch.trim().length() == 0) {
433 return customProductSearch;
436 String fillInCustomSearchURL(String text) {
437 String url = customProductSearch.replace("%s", text);
438 if (rawResult != null) {
439 url = url.replace("%f", rawResult.getBarcodeFormat().toString());