blob: 866f2be3be19084bdcf82b95d738c6a28816dc35 [file] [log] [blame]
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001/*
2 * Copyright (C) 2011 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.phone;
18
19import com.android.internal.telephony.CallManager;
20import com.android.internal.telephony.Connection;
21import com.android.internal.telephony.Phone;
22import com.android.internal.telephony.PhoneConstants;
23import com.android.phone.Constants.CallStatusCode;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070024
25import android.content.Context;
26import android.content.Intent;
27import android.os.AsyncResult;
28import android.os.Handler;
29import android.os.Message;
30import android.os.PowerManager;
31import android.os.UserHandle;
32import android.provider.Settings;
33import android.telephony.ServiceState;
34import android.util.Log;
35
36
37/**
38 * Helper class for the {@link CallController} that implements special
39 * behavior related to emergency calls. Specifically, this class handles
40 * the case of the user trying to dial an emergency number while the radio
41 * is off (i.e. the device is in airplane mode), by forcibly turning the
42 * radio back on, waiting for it to come up, and then retrying the
43 * emergency call.
44 *
45 * This class is instantiated lazily (the first time the user attempts to
46 * make an emergency call from airplane mode) by the the
47 * {@link CallController} singleton.
48 */
49public class EmergencyCallHelper extends Handler {
50 private static final String TAG = "EmergencyCallHelper";
51 private static final boolean DBG = false;
52
53 // Number of times to retry the call, and time between retry attempts.
54 public static final int MAX_NUM_RETRIES = 6;
55 public static final long TIME_BETWEEN_RETRIES = 5000; // msec
56
57 // Timeout used with our wake lock (just as a safety valve to make
58 // sure we don't hold it forever).
59 public static final long WAKE_LOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes in msec
60
61 // Handler message codes; see handleMessage()
62 private static final int START_SEQUENCE = 1;
63 private static final int SERVICE_STATE_CHANGED = 2;
64 private static final int DISCONNECT = 3;
65 private static final int RETRY_TIMEOUT = 4;
66
67 private CallController mCallController;
68 private PhoneGlobals mApp;
69 private CallManager mCM;
70 private Phone mPhone;
71 private String mNumber; // The emergency number we're trying to dial
72 private int mNumRetriesSoFar;
73
74 // Wake lock we hold while running the whole sequence
75 private PowerManager.WakeLock mPartialWakeLock;
76
77 public EmergencyCallHelper(CallController callController) {
78 if (DBG) log("EmergencyCallHelper constructor...");
79 mCallController = callController;
80 mApp = PhoneGlobals.getInstance();
81 mCM = mApp.mCM;
82 }
83
84 @Override
85 public void handleMessage(Message msg) {
86 switch (msg.what) {
87 case START_SEQUENCE:
88 startSequenceInternal(msg);
89 break;
90 case SERVICE_STATE_CHANGED:
91 onServiceStateChanged(msg);
92 break;
93 case DISCONNECT:
94 onDisconnect(msg);
95 break;
96 case RETRY_TIMEOUT:
97 onRetryTimeout();
98 break;
99 default:
100 Log.wtf(TAG, "handleMessage: unexpected message: " + msg);
101 break;
102 }
103 }
104
105 /**
106 * Starts the "emergency call from airplane mode" sequence.
107 *
108 * This is the (single) external API of the EmergencyCallHelper class.
109 * This method is called from the CallController placeCall() sequence
110 * if the user dials a valid emergency number, but the radio is
111 * powered-off (presumably due to airplane mode.)
112 *
113 * This method kicks off the following sequence:
114 * - Power on the radio
115 * - Listen for the service state change event telling us the radio has come up
116 * - Then launch the emergency call
117 * - Retry if the call fails with an OUT_OF_SERVICE error
118 * - Retry if we've gone 5 seconds without any response from the radio
119 * - Finally, clean up any leftover state (progress UI, wake locks, etc.)
120 *
121 * This method is safe to call from any thread, since it simply posts
122 * a message to the EmergencyCallHelper's handler (thus ensuring that
123 * the rest of the sequence is entirely serialized, and runs only on
124 * the handler thread.)
125 *
126 * This method does *not* force the in-call UI to come up; our caller
127 * is responsible for doing that (presumably by calling
128 * PhoneApp.displayCallScreen().)
129 */
130 public void startEmergencyCallFromAirplaneModeSequence(String number) {
131 if (DBG) log("startEmergencyCallFromAirplaneModeSequence('" + number + "')...");
132 Message msg = obtainMessage(START_SEQUENCE, number);
133 sendMessage(msg);
134 }
135
136 /**
137 * Actual implementation of startEmergencyCallFromAirplaneModeSequence(),
138 * guaranteed to run on the handler thread.
139 * @see startEmergencyCallFromAirplaneModeSequence()
140 */
141 private void startSequenceInternal(Message msg) {
142 if (DBG) log("startSequenceInternal(): msg = " + msg);
143
144 // First of all, clean up any state (including mPartialWakeLock!)
145 // left over from a prior emergency call sequence.
146 // This ensures that we'll behave sanely if another
147 // startEmergencyCallFromAirplaneModeSequence() comes in while
148 // we're already in the middle of the sequence.
149 cleanup();
150
151 mNumber = (String) msg.obj;
152 if (DBG) log("- startSequenceInternal: Got mNumber: '" + mNumber + "'");
153
154 mNumRetriesSoFar = 0;
155
156 // Reset mPhone to whatever the current default phone is right now.
157 mPhone = mApp.mCM.getDefaultPhone();
158
159 // Wake lock to make sure the processor doesn't go to sleep midway
160 // through the emergency call sequence.
161 PowerManager pm = (PowerManager) mApp.getSystemService(Context.POWER_SERVICE);
162 mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
163 // Acquire with a timeout, just to be sure we won't hold the wake
164 // lock forever even if a logic bug (in this class) causes us to
165 // somehow never call cleanup().
166 if (DBG) log("- startSequenceInternal: acquiring wake lock");
167 mPartialWakeLock.acquire(WAKE_LOCK_TIMEOUT);
168
169 // No need to check the current service state here, since the only
170 // reason the CallController would call this method in the first
171 // place is if the radio is powered-off.
172 //
173 // So just go ahead and turn the radio on.
174
175 powerOnRadio(); // We'll get an onServiceStateChanged() callback
176 // when the radio successfully comes up.
177
178 // Next step: when the SERVICE_STATE_CHANGED event comes in,
179 // we'll retry the call; see placeEmergencyCall();
180 // But also, just in case, start a timer to make sure we'll retry
181 // the call even if the SERVICE_STATE_CHANGED event never comes in
182 // for some reason.
183 startRetryTimer();
184
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700185 // (Our caller is responsible for calling mApp.displayCallScreen().)
186 }
187
188 /**
189 * Handles the SERVICE_STATE_CHANGED event.
190 *
191 * (Normally this event tells us that the radio has finally come
192 * up. In that case, it's now safe to actually place the
193 * emergency call.)
194 */
195 private void onServiceStateChanged(Message msg) {
196 ServiceState state = (ServiceState) ((AsyncResult) msg.obj).result;
197 if (DBG) log("onServiceStateChanged()... new state = " + state);
198
199 // Possible service states:
200 // - STATE_IN_SERVICE // Normal operation
201 // - STATE_OUT_OF_SERVICE // Still searching for an operator to register to,
202 // // or no radio signal
203 // - STATE_EMERGENCY_ONLY // Phone is locked; only emergency numbers are allowed
204 // - STATE_POWER_OFF // Radio is explicitly powered off (airplane mode)
205
206 // Once we reach either STATE_IN_SERVICE or STATE_EMERGENCY_ONLY,
207 // it's finally OK to place the emergency call.
208 boolean okToCall = (state.getState() == ServiceState.STATE_IN_SERVICE)
209 || (state.getState() == ServiceState.STATE_EMERGENCY_ONLY);
210
211 if (okToCall) {
212 // Woo hoo! It's OK to actually place the call.
213 if (DBG) log("onServiceStateChanged: ok to call!");
214
215 // Deregister for the service state change events.
216 unregisterForServiceStateChanged();
217
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700218 placeEmergencyCall();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700219 } else {
220 // The service state changed, but we're still not ready to call yet.
221 // (This probably was the transition from STATE_POWER_OFF to
222 // STATE_OUT_OF_SERVICE, which happens immediately after powering-on
223 // the radio.)
224 //
225 // So just keep waiting; we'll probably get to either
226 // STATE_IN_SERVICE or STATE_EMERGENCY_ONLY very shortly.
227 // (Or even if that doesn't happen, we'll at least do another retry
228 // when the RETRY_TIMEOUT event fires.)
229 if (DBG) log("onServiceStateChanged: not ready to call yet, keep waiting...");
230 }
231 }
232
233 /**
234 * Handles a DISCONNECT event from the telephony layer.
235 *
236 * Even after we successfully place an emergency call (after powering
237 * on the radio), it's still possible for the call to fail with the
238 * disconnect cause OUT_OF_SERVICE. If so, schedule a retry.
239 */
240 private void onDisconnect(Message msg) {
241 Connection conn = (Connection) ((AsyncResult) msg.obj).result;
242 Connection.DisconnectCause cause = conn.getDisconnectCause();
243 if (DBG) log("onDisconnect: connection '" + conn
244 + "', addr '" + conn.getAddress() + "', cause = " + cause);
245
246 if (cause == Connection.DisconnectCause.OUT_OF_SERVICE) {
247 // Wait a bit more and try again (or just bail out totally if
248 // we've had too many failures.)
249 if (DBG) log("- onDisconnect: OUT_OF_SERVICE, need to retry...");
250 scheduleRetryOrBailOut();
251 } else {
252 // Any other disconnect cause means we're done.
253 // Either the emergency call succeeded *and* ended normally,
254 // or else there was some error that we can't retry. In either
255 // case, just clean up our internal state.)
256
257 if (DBG) log("==> Disconnect event; clean up...");
258 cleanup();
259
260 // Nothing else to do here. If the InCallScreen was visible,
261 // it would have received this disconnect event too (so it'll
262 // show the "Call ended" state and finish itself without any
263 // help from us.)
264 }
265 }
266
267 /**
268 * Handles the retry timer expiring.
269 */
270 private void onRetryTimeout() {
271 PhoneConstants.State phoneState = mCM.getState();
272 int serviceState = mPhone.getServiceState().getState();
273 if (DBG) log("onRetryTimeout(): phone state " + phoneState
274 + ", service state " + serviceState
275 + ", mNumRetriesSoFar = " + mNumRetriesSoFar);
276
277 // - If we're actually in a call, we've succeeded.
278 //
279 // - Otherwise, if the radio is now on, that means we successfully got
280 // out of airplane mode but somehow didn't get the service state
281 // change event. In that case, try to place the call.
282 //
283 // - If the radio is still powered off, try powering it on again.
284
285 if (phoneState == PhoneConstants.State.OFFHOOK) {
286 if (DBG) log("- onRetryTimeout: Call is active! Cleaning up...");
287 cleanup();
288 return;
289 }
290
291 if (serviceState != ServiceState.STATE_POWER_OFF) {
292 // Woo hoo -- we successfully got out of airplane mode.
293
294 // Deregister for the service state change events; we don't need
295 // these any more now that the radio is powered-on.
296 unregisterForServiceStateChanged();
297
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700298 placeEmergencyCall(); // If the call fails, placeEmergencyCall()
299 // will schedule a retry.
300 } else {
301 // Uh oh; we've waited the full TIME_BETWEEN_RETRIES and the
302 // radio is still not powered-on. Try again...
303
304 if (DBG) log("- Trying (again) to turn on the radio...");
305 powerOnRadio(); // Again, we'll (hopefully) get an onServiceStateChanged()
306 // callback when the radio successfully comes up.
307
308 // ...and also set a fresh retry timer (or just bail out
309 // totally if we've had too many failures.)
310 scheduleRetryOrBailOut();
311 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700312 }
313
314 /**
315 * Attempt to power on the radio (i.e. take the device out
316 * of airplane mode.)
317 *
318 * Additionally, start listening for service state changes;
319 * we'll eventually get an onServiceStateChanged() callback
320 * when the radio successfully comes up.
321 */
322 private void powerOnRadio() {
323 if (DBG) log("- powerOnRadio()...");
324
325 // We're about to turn on the radio, so arrange to be notified
326 // when the sequence is complete.
327 registerForServiceStateChanged();
328
329 // If airplane mode is on, we turn it off the same way that the
330 // Settings activity turns it off.
331 if (Settings.Global.getInt(mApp.getContentResolver(),
332 Settings.Global.AIRPLANE_MODE_ON, 0) > 0) {
333 if (DBG) log("==> Turning off airplane mode...");
334
335 // Change the system setting
336 Settings.Global.putInt(mApp.getContentResolver(),
337 Settings.Global.AIRPLANE_MODE_ON, 0);
338
339 // Post the intent
340 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
341 intent.putExtra("state", false);
342 mApp.sendBroadcastAsUser(intent, UserHandle.ALL);
343 } else {
344 // Otherwise, for some strange reason the radio is off
345 // (even though the Settings database doesn't think we're
346 // in airplane mode.) In this case just turn the radio
347 // back on.
348 if (DBG) log("==> (Apparently) not in airplane mode; manually powering radio on...");
349 mPhone.setRadioPower(true);
350 }
351 }
352
353 /**
354 * Actually initiate the outgoing emergency call.
355 * (We do this once the radio has successfully been powered-up.)
356 *
357 * If the call succeeds, we're done.
358 * If the call fails, schedule a retry of the whole sequence.
359 */
360 private void placeEmergencyCall() {
361 if (DBG) log("placeEmergencyCall()...");
362
363 // Place an outgoing call to mNumber.
364 // Note we call PhoneUtils.placeCall() directly; we don't want any
365 // of the behavior from CallController.placeCallInternal() here.
366 // (Specifically, we don't want to start the "emergency call from
367 // airplane mode" sequence from the beginning again!)
368
369 registerForDisconnect(); // Get notified when this call disconnects
370
371 if (DBG) log("- placing call to '" + mNumber + "'...");
372 int callStatus = PhoneUtils.placeCall(mApp,
373 mPhone,
374 mNumber,
375 null, // contactUri
Santos Cordon69a69192013-08-22 14:25:42 -0700376 true); // isEmergencyCall
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700377 if (DBG) log("- PhoneUtils.placeCall() returned status = " + callStatus);
378
379 boolean success;
380 // Note PhoneUtils.placeCall() returns one of the CALL_STATUS_*
381 // constants, not a CallStatusCode enum value.
382 switch (callStatus) {
383 case PhoneUtils.CALL_STATUS_DIALED:
384 success = true;
385 break;
386
387 case PhoneUtils.CALL_STATUS_DIALED_MMI:
388 case PhoneUtils.CALL_STATUS_FAILED:
389 default:
390 // Anything else is a failure, and we'll need to retry.
391 Log.w(TAG, "placeEmergencyCall(): placeCall() failed: callStatus = " + callStatus);
392 success = false;
393 break;
394 }
395
396 if (success) {
397 if (DBG) log("==> Success from PhoneUtils.placeCall()!");
398 // Ok, the emergency call is (hopefully) under way.
399
400 // We're not done yet, though, so don't call cleanup() here.
401 // (It's still possible that this call will fail, and disconnect
402 // with cause==OUT_OF_SERVICE. If so, that will trigger a retry
403 // from the onDisconnect() method.)
404 } else {
405 if (DBG) log("==> Failure.");
406 // Wait a bit more and try again (or just bail out totally if
407 // we've had too many failures.)
408 scheduleRetryOrBailOut();
409 }
410 }
411
412 /**
413 * Schedules a retry in response to some failure (either the radio
414 * failing to power on, or a failure when trying to place the call.)
415 * Or, if we've hit the retry limit, bail out of this whole sequence
416 * and display a failure message to the user.
417 */
418 private void scheduleRetryOrBailOut() {
419 mNumRetriesSoFar++;
420 if (DBG) log("scheduleRetryOrBailOut()... mNumRetriesSoFar is now " + mNumRetriesSoFar);
421
422 if (mNumRetriesSoFar > MAX_NUM_RETRIES) {
423 Log.w(TAG, "scheduleRetryOrBailOut: hit MAX_NUM_RETRIES; giving up...");
424 cleanup();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700425 } else {
426 if (DBG) log("- Scheduling another retry...");
427 startRetryTimer();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700428 }
429 }
430
431 /**
432 * Clean up when done with the whole sequence: either after
433 * successfully placing *and* ending the emergency call, or after
434 * bailing out because of too many failures.
435 *
436 * The exact cleanup steps are:
437 * - Take down any progress UI (and also ask the in-call UI to refresh itself,
438 * if it's still visible)
439 * - Double-check that we're not still registered for any telephony events
440 * - Clean up any extraneous handler messages (like retry timeouts) still in the queue
441 * - Make sure we're not still holding any wake locks
442 *
443 * Basically this method guarantees that there will be no more
444 * activity from the EmergencyCallHelper until the CallController
445 * kicks off the whole sequence again with another call to
446 * startEmergencyCallFromAirplaneModeSequence().
447 *
448 * Note we don't call this method simply after a successful call to
449 * placeCall(), since it's still possible the call will disconnect
450 * very quickly with an OUT_OF_SERVICE error.
451 */
452 private void cleanup() {
453 if (DBG) log("cleanup()...");
454
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700455 unregisterForServiceStateChanged();
456 unregisterForDisconnect();
457 cancelRetryTimer();
458
459 // Release / clean up the wake lock
460 if (mPartialWakeLock != null) {
461 if (mPartialWakeLock.isHeld()) {
462 if (DBG) log("- releasing wake lock");
463 mPartialWakeLock.release();
464 }
465 mPartialWakeLock = null;
466 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700467 }
468
469 private void startRetryTimer() {
470 removeMessages(RETRY_TIMEOUT);
471 sendEmptyMessageDelayed(RETRY_TIMEOUT, TIME_BETWEEN_RETRIES);
472 }
473
474 private void cancelRetryTimer() {
475 removeMessages(RETRY_TIMEOUT);
476 }
477
478 private void registerForServiceStateChanged() {
479 // Unregister first, just to make sure we never register ourselves
480 // twice. (We need this because Phone.registerForServiceStateChanged()
481 // does not prevent multiple registration of the same handler.)
482 mPhone.unregisterForServiceStateChanged(this); // Safe even if not currently registered
483 mPhone.registerForServiceStateChanged(this, SERVICE_STATE_CHANGED, null);
484 }
485
486 private void unregisterForServiceStateChanged() {
487 // This method is safe to call even if we haven't set mPhone yet.
488 if (mPhone != null) {
489 mPhone.unregisterForServiceStateChanged(this); // Safe even if unnecessary
490 }
491 removeMessages(SERVICE_STATE_CHANGED); // Clean up any pending messages too
492 }
493
494 private void registerForDisconnect() {
495 // Note: no need to unregister first, since
496 // CallManager.registerForDisconnect() automatically prevents
497 // multiple registration of the same handler.
498 mCM.registerForDisconnect(this, DISCONNECT, null);
499 }
500
501 private void unregisterForDisconnect() {
502 mCM.unregisterForDisconnect(this); // Safe even if not currently registered
503 removeMessages(DISCONNECT); // Clean up any pending messages too
504 }
505
506
507 //
508 // Debugging
509 //
510
511 private static void log(String msg) {
512 Log.d(TAG, msg);
513 }
514}