Added support for encoding multiple email addresses and phone numbers using the new...
[zxing.git] / android / src / com / google / zxing / client / android / result / ResultHandler.java
1 /*
2  * Copyright (C) 2008 ZXing authors
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.google.zxing.client.android.result;
18
19 import android.app.Activity;
20 import android.content.Intent;
21 import android.net.Uri;
22 import android.provider.Contacts;
23 import com.google.zxing.client.android.Intents;
24 import com.google.zxing.client.android.R;
25 import com.google.zxing.client.android.SearchBookContentsActivity;
26 import com.google.zxing.client.android.LocaleManager;
27 import com.google.zxing.client.android.Contents;
28 import com.google.zxing.client.result.ParsedResult;
29 import com.google.zxing.client.result.ParsedResultType;
30
31 import java.text.ParsePosition;
32 import java.text.SimpleDateFormat;
33 import java.util.Calendar;
34 import java.text.DateFormat;
35 import java.util.Date;
36 import java.util.GregorianCalendar;
37
38 public abstract class ResultHandler {
39
40   public static final int MAX_BUTTON_COUNT = 4;
41
42   protected final ParsedResult mResult;
43   private final Activity mActivity;
44
45   public ResultHandler(Activity activity, ParsedResult result) {
46     mResult = result;
47     mActivity = activity;
48   }
49
50   /**
51    * Indicates how many buttons the derived class wants shown.
52    *
53    * @return The integer button count.
54    */
55   public abstract int getButtonCount();
56
57   /**
58    * The text of the nth action button.
59    *
60    * @param index From 0 to getButtonCount() - 1
61    * @return The button text as a resource ID
62    */
63   public abstract int getButtonText(int index);
64
65
66   /**
67    * Execute the action which corresponds to the nth button.
68    *
69    * @param index The button that was clicked.
70    */
71   public abstract void handleButtonPress(int index);
72
73   /**
74    * Create a possibly styled string for the contents of the current barcode.
75    *
76    * @return The text to be displayed.
77    */
78   public CharSequence getDisplayContents() {
79     String contents = mResult.getDisplayResult();
80     return contents.replace("\r", "");
81   }
82
83   /**
84    * A string describing the kind of barcode that was found, e.g. "Found contact info".
85    *
86    * @return The resource ID of the string.
87    */
88   public abstract int getDisplayTitle();
89
90   /**
91    * A convenience method to get the parsed type. Should not be overridden.
92    *
93    * @return The parsed type, e.g. URI or ISBN
94    */
95   public final ParsedResultType getType() {
96     return mResult.getType();
97   }
98
99   /**
100    * Sends an intent to create a new calendar event by prepopulating the Add Event UI. Older
101    * versions of the system have a bug where the event title will not be filled out.
102    *
103    * @param summary A description of the event
104    * @param start   The start time as yyyyMMdd or yyyyMMdd'T'HHmmss or yyyyMMdd'T'HHmmss'Z'
105    * @param end     The end time as yyyyMMdd or yyyyMMdd'T'HHmmss or yyyyMMdd'T'HHmmss'Z'
106    */
107   public final void addCalendarEvent(String summary, String start, String end) {
108     Intent intent = new Intent(Intent.ACTION_EDIT);
109     intent.setType("vnd.android.cursor.item/event");
110     intent.putExtra("beginTime", calculateMilliseconds(start));
111     if (start.length() == 8) {
112       intent.putExtra("allDay", true);
113     }
114     intent.putExtra("endTime", calculateMilliseconds(end));
115     intent.putExtra("title", summary);
116     launchIntent(intent);
117   }
118
119   private long calculateMilliseconds(String when) {
120     if (when.length() == 8) {
121       // Only contains year/month/day
122       DateFormat format = new SimpleDateFormat("yyyyMMdd");
123       Date date = format.parse(when, new ParsePosition(0));
124       return date.getTime();
125     } else {
126       // The when string can be local time, or UTC if it ends with a Z
127       DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
128       Date date = format.parse(when.substring(0, 15), new ParsePosition(0));
129       long milliseconds = date.getTime();
130       if (when.length() == 16 && when.charAt(15) == 'Z') {
131         Calendar calendar = new GregorianCalendar();
132         int offset = (calendar.get(java.util.Calendar.ZONE_OFFSET) +
133             calendar.get(java.util.Calendar.DST_OFFSET));
134         milliseconds += offset;
135       }
136       return milliseconds;
137     }
138   }
139
140   public final void addContact(String[] names, String[] phoneNumbers, String[] emails, String note,
141                          String address, String org, String title) {
142
143     Intent intent = new Intent(Contacts.Intents.Insert.ACTION, Contacts.People.CONTENT_URI);
144     putExtra(intent, Contacts.Intents.Insert.NAME, names);
145
146     int phoneCount = Math.min((phoneNumbers != null) ? phoneNumbers.length : 0,
147         Contents.PHONE_KEYS.length);
148     for (int x = 0; x < phoneCount; x++) {
149       putExtra(intent, Contents.PHONE_KEYS[x], phoneNumbers[x]);
150     }
151
152     int emailCount = Math.min((emails != null) ? emails.length : 0, Contents.EMAIL_KEYS.length);
153     for (int x = 0; x < emailCount; x++) {
154       putExtra(intent, Contents.EMAIL_KEYS[x], emails[x]);
155     }
156
157     putExtra(intent, Contacts.Intents.Insert.NOTES, note);
158     putExtra(intent, Contacts.Intents.Insert.POSTAL, address);
159     putExtra(intent, Contacts.Intents.Insert.COMPANY, org);
160     putExtra(intent, Contacts.Intents.Insert.JOB_TITLE, title);
161     launchIntent(intent);
162   }
163
164   public final void shareByEmail(String contents) {
165     sendEmailFromUri("mailto:", mActivity.getString(R.string.msg_share_subject_line), contents);
166   }
167
168   public final void sendEmail(String address, String subject, String body) {
169     sendEmailFromUri("mailto:" + address, subject, body);
170   }
171
172   public final void sendEmailFromUri(String uri, String subject, String body) {
173     Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
174     putExtra(intent, "subject", subject);
175     putExtra(intent, "body", body);
176     launchIntent(intent);
177   }
178
179   public final void shareBySMS(String contents) {
180     sendSMSFromUri("smsto:", mActivity.getString(R.string.msg_share_subject_line) + ":\n" + contents);
181   }
182
183   public final void sendSMS(String phoneNumber, String body) {
184     sendSMSFromUri("smsto:" + phoneNumber, body);
185   }
186
187   public final void sendSMSFromUri(String uri, String body) {
188     Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
189     putExtra(intent, "sms_body", body);
190     // Exit the app once the SMS is sent
191     intent.putExtra("compose_mode", true);
192     launchIntent(intent);
193   }
194
195   public final void sendMMS(String phoneNumber, String subject, String body) {
196     sendMMSFromUri("mmsto:" + phoneNumber, subject, body);
197   }
198
199   public final void sendMMSFromUri(String uri, String subject, String body) {
200     Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
201     // The Messaging app needs to see a valid subject or else it will treat this an an SMS.
202     if (subject == null || subject.length() == 0) {
203       putExtra(intent, "subject", mActivity.getString(R.string.msg_default_mms_subject));
204     } else {
205       putExtra(intent, "subject", subject);
206     }
207     putExtra(intent, "sms_body", body);
208     intent.putExtra("compose_mode", true);
209     launchIntent(intent);
210   }
211
212   public final void dialPhone(String phoneNumber) {
213     launchIntent(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));
214   }
215
216   public final void dialPhoneFromUri(String uri) {
217     launchIntent(new Intent(Intent.ACTION_DIAL, Uri.parse(uri)));
218   }
219
220   public final void openMap(String geoURI) {
221     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(geoURI)));
222   }
223
224   /**
225    * Do a geo search using the address as the query.
226    *
227    * @param address The address to find
228    * @param title An optional title, e.g. the name of the business at this address
229    */
230   public final void searchMap(String address, String title) {
231     String query = address;
232     if (title != null && title.length() > 0) {
233       query = query + " (" + title + ")";
234     }
235     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(query))));
236   }
237
238   public final void getDirections(float latitude, float longitude) {
239     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google." +
240         LocaleManager.getCountryTLD() + "/maps?f=d&daddr=" + latitude + "," + longitude)));
241   }
242
243   public final void openProductSearch(String upc) {
244     Uri uri = Uri.parse("http://www.google." + LocaleManager.getCountryTLD() + "/products?q=" + upc);
245     launchIntent(new Intent(Intent.ACTION_VIEW, uri));
246   }
247
248   public final void openBookSearch(String isbn) {
249     Uri uri = Uri.parse("http://books.google." + LocaleManager.getCountryTLD() + "/books?vid=isbn" +
250         isbn);
251     launchIntent(new Intent(Intent.ACTION_VIEW, uri));
252   }
253
254   public final void searchBookContents(String isbn) {
255     Intent intent = new Intent(Intents.SearchBookContents.ACTION);
256     intent.setClassName(mActivity, SearchBookContentsActivity.class.getName());
257     putExtra(intent, Intents.SearchBookContents.ISBN, isbn);
258     launchIntent(intent);
259   }
260
261   public final void openURL(String url) {
262     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
263   }
264
265   public final void webSearch(String query) {
266     Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
267     intent.putExtra("query", query);
268     launchIntent(intent);
269   }
270
271   private void launchIntent(Intent intent) {
272     if (intent != null) {
273       mActivity.startActivity(intent);
274     }
275   }
276
277   private static void putExtra(Intent intent, String key, String value) {
278     if (value != null && value.length() > 0) {
279       intent.putExtra(key, value);
280     }
281   }
282
283   // TODO: This is only used by the names field, and only the first name will be taken.
284   private static void putExtra(Intent intent, String key, String[] value) {
285     if (value != null && value.length > 0) {
286       putExtra(intent, key, value[0]);
287     }
288   }
289
290 }