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