blob: 0b44facd8a4084230e037f252bcd467d47222692 [file] [log] [blame]
Chiao Cheng91197042012-08-24 14:19:37 -07001/*
2 * Copyright (C) 2006 The Android Open Source Project
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
17package com.android.dialer;
18
19import android.app.AlertDialog;
20import android.app.KeyguardManager;
21import android.app.ProgressDialog;
Jake Hamby1d6fb572013-04-09 15:49:56 -070022import android.content.ActivityNotFoundException;
23import android.content.ComponentName;
Chiao Cheng91197042012-08-24 14:19:37 -070024import android.content.ContentResolver;
25import android.content.Context;
26import android.content.DialogInterface;
27import android.content.Intent;
28import android.database.Cursor;
29import android.net.Uri;
30import android.os.Looper;
31import android.os.RemoteException;
32import android.os.ServiceManager;
33import android.telephony.PhoneNumberUtils;
34import android.telephony.TelephonyManager;
35import android.util.Log;
36import android.view.WindowManager;
37import android.widget.EditText;
38import android.widget.Toast;
39
Chiao Cheng07af7642012-09-14 12:05:14 -070040import com.android.contacts.common.database.NoNullCursorAsyncQueryHandler;
Chiao Cheng91197042012-08-24 14:19:37 -070041import com.android.internal.telephony.ITelephony;
Chiao Cheng91197042012-08-24 14:19:37 -070042
43/**
44 * Helper class to listen for some magic character sequences
45 * that are handled specially by the dialer.
46 *
47 * Note the Phone app also handles these sequences too (in a couple of
Jake Hamby1d6fb572013-04-09 15:49:56 -070048 * relatively obscure places in the UI), so there's a separate version of
Chiao Cheng91197042012-08-24 14:19:37 -070049 * this class under apps/Phone.
50 *
51 * TODO: there's lots of duplicated code between this class and the
52 * corresponding class under apps/Phone. Let's figure out a way to
53 * unify these two classes (in the framework? in a common shared library?)
54 */
55public class SpecialCharSequenceMgr {
56 private static final String TAG = "SpecialCharSequenceMgr";
Jake Hamby1d6fb572013-04-09 15:49:56 -070057
Yorke Leef90dada2013-12-09 11:50:28 -080058 private static final String SECRET_CODE_ACTION = "android.provider.Telephony.SECRET_CODE";
Chiao Cheng91197042012-08-24 14:19:37 -070059 private static final String MMI_IMEI_DISPLAY = "*#06#";
Jake Hamby1d6fb572013-04-09 15:49:56 -070060 private static final String MMI_REGULATORY_INFO_DISPLAY = "*#07#";
Chiao Cheng91197042012-08-24 14:19:37 -070061
62 /**
63 * Remembers the previous {@link QueryHandler} and cancel the operation when needed, to
64 * prevent possible crash.
65 *
66 * QueryHandler may call {@link ProgressDialog#dismiss()} when the screen is already gone,
67 * which will cause the app crash. This variable enables the class to prevent the crash
68 * on {@link #cleanup()}.
69 *
70 * TODO: Remove this and replace it (and {@link #cleanup()}) with better implementation.
Jake Hamby1d6fb572013-04-09 15:49:56 -070071 * One complication is that we have SpecialCharSequenceMgr in Phone package too, which has
Chiao Cheng91197042012-08-24 14:19:37 -070072 * *slightly* different implementation. Note that Phone package doesn't have this problem,
73 * so the class on Phone side doesn't have this functionality.
74 * Fundamental fix would be to have one shared implementation and resolve this corner case more
75 * gracefully.
76 */
77 private static QueryHandler sPreviousAdnQueryHandler;
78
79 /** This class is never instantiated. */
80 private SpecialCharSequenceMgr() {
81 }
82
83 public static boolean handleChars(Context context, String input, EditText textField) {
84 return handleChars(context, input, false, textField);
85 }
86
87 static boolean handleChars(Context context, String input) {
88 return handleChars(context, input, false, null);
89 }
90
91 static boolean handleChars(Context context, String input, boolean useSystemWindow,
92 EditText textField) {
93
94 //get rid of the separators so that the string gets parsed correctly
95 String dialString = PhoneNumberUtils.stripSeparators(input);
96
97 if (handleIMEIDisplay(context, dialString, useSystemWindow)
Jake Hamby1d6fb572013-04-09 15:49:56 -070098 || handleRegulatoryInfoDisplay(context, dialString)
Chiao Cheng91197042012-08-24 14:19:37 -070099 || handlePinEntry(context, dialString)
100 || handleAdnEntry(context, dialString, textField)
101 || handleSecretCode(context, dialString)) {
102 return true;
103 }
104
105 return false;
106 }
107
108 /**
109 * Cleanup everything around this class. Must be run inside the main thread.
110 *
111 * This should be called when the screen becomes background.
112 */
113 public static void cleanup() {
114 if (Looper.myLooper() != Looper.getMainLooper()) {
115 Log.wtf(TAG, "cleanup() is called outside the main thread");
116 return;
117 }
118
119 if (sPreviousAdnQueryHandler != null) {
120 sPreviousAdnQueryHandler.cancel();
121 sPreviousAdnQueryHandler = null;
122 }
123 }
124
125 /**
126 * Handles secret codes to launch arbitrary activities in the form of *#*#<code>#*#*.
127 * If a secret code is encountered an Intent is started with the android_secret_code://<code>
128 * URI.
129 *
130 * @param context the context to use
131 * @param input the text to check for a secret code in
132 * @return true if a secret code was encountered
133 */
134 static boolean handleSecretCode(Context context, String input) {
135 // Secret codes are in the form *#*#<code>#*#*
136 int len = input.length();
137 if (len > 8 && input.startsWith("*#*#") && input.endsWith("#*#*")) {
Yorke Leef90dada2013-12-09 11:50:28 -0800138 final Intent intent = new Intent(SECRET_CODE_ACTION,
Chiao Cheng91197042012-08-24 14:19:37 -0700139 Uri.parse("android_secret_code://" + input.substring(4, len - 4)));
140 context.sendBroadcast(intent);
141 return true;
142 }
143
144 return false;
145 }
146
147 /**
148 * Handle ADN requests by filling in the SIM contact number into the requested
149 * EditText.
150 *
151 * This code works alongside the Asynchronous query handler {@link QueryHandler}
152 * and query cancel handler implemented in {@link SimContactQueryCookie}.
153 */
154 static boolean handleAdnEntry(Context context, String input, EditText textField) {
155 /* ADN entries are of the form "N(N)(N)#" */
156
157 TelephonyManager telephonyManager =
158 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
159 if (telephonyManager == null
Yorke Lee62280c72013-11-22 18:24:59 -0800160 || telephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_GSM) {
Chiao Cheng91197042012-08-24 14:19:37 -0700161 return false;
162 }
163
164 // if the phone is keyguard-restricted, then just ignore this
165 // input. We want to make sure that sim card contacts are NOT
166 // exposed unless the phone is unlocked, and this code can be
167 // accessed from the emergency dialer.
168 KeyguardManager keyguardManager =
169 (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
170 if (keyguardManager.inKeyguardRestrictedInputMode()) {
171 return false;
172 }
173
174 int len = input.length();
175 if ((len > 1) && (len < 5) && (input.endsWith("#"))) {
176 try {
177 // get the ordinal number of the sim contact
178 int index = Integer.parseInt(input.substring(0, len-1));
179
180 // The original code that navigated to a SIM Contacts list view did not
181 // highlight the requested contact correctly, a requirement for PTCRB
182 // certification. This behaviour is consistent with the UI paradigm
183 // for touch-enabled lists, so it does not make sense to try to work
184 // around it. Instead we fill in the the requested phone number into
185 // the dialer text field.
186
187 // create the async query handler
188 QueryHandler handler = new QueryHandler (context.getContentResolver());
189
190 // create the cookie object
191 SimContactQueryCookie sc = new SimContactQueryCookie(index - 1, handler,
192 ADN_QUERY_TOKEN);
193
194 // setup the cookie fields
195 sc.contactNum = index - 1;
196 sc.setTextField(textField);
197
198 // create the progress dialog
199 sc.progressDialog = new ProgressDialog(context);
200 sc.progressDialog.setTitle(R.string.simContacts_title);
201 sc.progressDialog.setMessage(context.getText(R.string.simContacts_emptyLoading));
202 sc.progressDialog.setIndeterminate(true);
203 sc.progressDialog.setCancelable(true);
204 sc.progressDialog.setOnCancelListener(sc);
205 sc.progressDialog.getWindow().addFlags(
206 WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
207
208 // display the progress dialog
209 sc.progressDialog.show();
210
211 // run the query.
212 handler.startQuery(ADN_QUERY_TOKEN, sc, Uri.parse("content://icc/adn"),
213 new String[]{ADN_PHONE_NUMBER_COLUMN_NAME}, null, null, null);
214
215 if (sPreviousAdnQueryHandler != null) {
216 // It is harmless to call cancel() even after the handler's gone.
217 sPreviousAdnQueryHandler.cancel();
218 }
219 sPreviousAdnQueryHandler = handler;
220 return true;
221 } catch (NumberFormatException ex) {
222 // Ignore
223 }
224 }
225 return false;
226 }
227
228 static boolean handlePinEntry(Context context, String input) {
229 if ((input.startsWith("**04") || input.startsWith("**05")) && input.endsWith("#")) {
230 try {
231 return ITelephony.Stub.asInterface(ServiceManager.getService("phone"))
232 .handlePinMmi(input);
233 } catch (RemoteException e) {
234 Log.e(TAG, "Failed to handlePinMmi due to remote exception");
235 return false;
236 }
237 }
238 return false;
239 }
240
241 static boolean handleIMEIDisplay(Context context, String input, boolean useSystemWindow) {
242 TelephonyManager telephonyManager =
243 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
244 if (telephonyManager != null && input.equals(MMI_IMEI_DISPLAY)) {
Yorke Lee62280c72013-11-22 18:24:59 -0800245 int phoneType = telephonyManager.getPhoneType();
Chiao Cheng91197042012-08-24 14:19:37 -0700246 if (phoneType == TelephonyManager.PHONE_TYPE_GSM) {
247 showIMEIPanel(context, useSystemWindow, telephonyManager);
248 return true;
249 } else if (phoneType == TelephonyManager.PHONE_TYPE_CDMA) {
250 showMEIDPanel(context, useSystemWindow, telephonyManager);
251 return true;
252 }
253 }
254
255 return false;
256 }
257
Jake Hamby1d6fb572013-04-09 15:49:56 -0700258 private static boolean handleRegulatoryInfoDisplay(Context context, String input) {
259 if (input.equals(MMI_REGULATORY_INFO_DISPLAY)) {
260 Log.d(TAG, "handleRegulatoryInfoDisplay() sending intent to settings app");
261 ComponentName regInfoDisplayActivity = new ComponentName(
262 "com.android.settings", "com.android.settings.RegulatoryInfoDisplayActivity");
263 Intent showRegInfoIntent = new Intent("android.settings.SHOW_REGULATORY_INFO");
264 showRegInfoIntent.setComponent(regInfoDisplayActivity);
265 try {
266 context.startActivity(showRegInfoIntent);
267 } catch (ActivityNotFoundException e) {
268 Log.e(TAG, "startActivity() failed: " + e);
269 }
270 return true;
271 }
272 return false;
273 }
274
Chiao Cheng91197042012-08-24 14:19:37 -0700275 // TODO: Combine showIMEIPanel() and showMEIDPanel() into a single
276 // generic "showDeviceIdPanel()" method, like in the apps/Phone
277 // version of SpecialCharSequenceMgr.java. (This will require moving
278 // the phone app's TelephonyCapabilities.getDeviceIdLabel() method
279 // into the telephony framework, though.)
280
281 private static void showIMEIPanel(Context context, boolean useSystemWindow,
282 TelephonyManager telephonyManager) {
283 String imeiStr = telephonyManager.getDeviceId();
284
285 AlertDialog alert = new AlertDialog.Builder(context)
286 .setTitle(R.string.imei)
287 .setMessage(imeiStr)
288 .setPositiveButton(android.R.string.ok, null)
289 .setCancelable(false)
290 .show();
291 }
292
293 private static void showMEIDPanel(Context context, boolean useSystemWindow,
294 TelephonyManager telephonyManager) {
295 String meidStr = telephonyManager.getDeviceId();
296
297 AlertDialog alert = new AlertDialog.Builder(context)
298 .setTitle(R.string.meid)
299 .setMessage(meidStr)
300 .setPositiveButton(android.R.string.ok, null)
301 .setCancelable(false)
302 .show();
303 }
304
305 /*******
306 * This code is used to handle SIM Contact queries
307 *******/
308 private static final String ADN_PHONE_NUMBER_COLUMN_NAME = "number";
309 private static final String ADN_NAME_COLUMN_NAME = "name";
310 private static final int ADN_QUERY_TOKEN = -1;
311
312 /**
313 * Cookie object that contains everything we need to communicate to the
314 * handler's onQuery Complete, as well as what we need in order to cancel
315 * the query (if requested).
316 *
317 * Note, access to the textField field is going to be synchronized, because
318 * the user can request a cancel at any time through the UI.
319 */
320 private static class SimContactQueryCookie implements DialogInterface.OnCancelListener{
321 public ProgressDialog progressDialog;
322 public int contactNum;
323
324 // Used to identify the query request.
325 private int mToken;
326 private QueryHandler mHandler;
327
328 // The text field we're going to update
329 private EditText textField;
330
331 public SimContactQueryCookie(int number, QueryHandler handler, int token) {
332 contactNum = number;
333 mHandler = handler;
334 mToken = token;
335 }
336
337 /**
338 * Synchronized getter for the EditText.
339 */
340 public synchronized EditText getTextField() {
341 return textField;
342 }
343
344 /**
345 * Synchronized setter for the EditText.
346 */
347 public synchronized void setTextField(EditText text) {
348 textField = text;
349 }
350
351 /**
352 * Cancel the ADN query by stopping the operation and signaling
353 * the cookie that a cancel request is made.
354 */
355 public synchronized void onCancel(DialogInterface dialog) {
356 // close the progress dialog
357 if (progressDialog != null) {
358 progressDialog.dismiss();
359 }
360
361 // setting the textfield to null ensures that the UI does NOT get
362 // updated.
363 textField = null;
364
365 // Cancel the operation if possible.
366 mHandler.cancelOperation(mToken);
367 }
368 }
369
370 /**
371 * Asynchronous query handler that services requests to look up ADNs
372 *
Jake Hamby1d6fb572013-04-09 15:49:56 -0700373 * Queries originate from {@link #handleAdnEntry}.
Chiao Cheng91197042012-08-24 14:19:37 -0700374 */
Chiao Cheng07af7642012-09-14 12:05:14 -0700375 private static class QueryHandler extends NoNullCursorAsyncQueryHandler {
Chiao Cheng91197042012-08-24 14:19:37 -0700376
377 private boolean mCanceled;
378
379 public QueryHandler(ContentResolver cr) {
380 super(cr);
381 }
382
383 /**
384 * Override basic onQueryComplete to fill in the textfield when
385 * we're handed the ADN cursor.
386 */
387 @Override
Chiao Cheng07af7642012-09-14 12:05:14 -0700388 protected void onNotNullableQueryComplete(int token, Object cookie, Cursor c) {
Chiao Cheng91197042012-08-24 14:19:37 -0700389 sPreviousAdnQueryHandler = null;
390 if (mCanceled) {
391 return;
392 }
393
394 SimContactQueryCookie sc = (SimContactQueryCookie) cookie;
395
396 // close the progress dialog.
397 sc.progressDialog.dismiss();
398
399 // get the EditText to update or see if the request was cancelled.
400 EditText text = sc.getTextField();
401
402 // if the textview is valid, and the cursor is valid and postionable
403 // on the Nth number, then we update the text field and display a
404 // toast indicating the caller name.
405 if ((c != null) && (text != null) && (c.moveToPosition(sc.contactNum))) {
406 String name = c.getString(c.getColumnIndexOrThrow(ADN_NAME_COLUMN_NAME));
407 String number = c.getString(c.getColumnIndexOrThrow(ADN_PHONE_NUMBER_COLUMN_NAME));
408
409 // fill the text in.
410 text.getText().replace(0, 0, number);
411
412 // display the name as a toast
413 Context context = sc.progressDialog.getContext();
414 name = context.getString(R.string.menu_callNumber, name);
415 Toast.makeText(context, name, Toast.LENGTH_SHORT)
416 .show();
417 }
418 }
419
420 public void cancel() {
421 mCanceled = true;
422 // Ask AsyncQueryHandler to cancel the whole request. This will fails when the
423 // query already started.
424 cancelOperation(ADN_QUERY_TOKEN);
425 }
426 }
427}