blob: a38fbbfbac3c1e022210e8368442743cfd9672e2 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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 android.app;
18
Dianne Hackborn3e82ba12013-07-16 13:23:55 -070019import android.util.ArrayMap;
Adam Powell14874662013-07-18 19:42:41 -070020import android.util.SuperNotCalledException;
Adam Powell6e346362010-07-23 10:18:23 -070021import com.android.internal.app.ActionBarImpl;
22import com.android.internal.policy.PolicyManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070023
Dianne Hackbornc68c9132011-07-29 01:25:18 -070024import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.ComponentName;
26import android.content.ContentResolver;
27import android.content.Context;
Jason parks6ed50de2010-08-25 10:18:50 -050028import android.content.CursorLoader;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070029import android.content.IIntentSender;
Adam Powell33b97432010-04-20 10:01:14 -070030import android.content.Intent;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070031import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.SharedPreferences;
33import android.content.pm.ActivityInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070034import android.content.pm.PackageManager;
35import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.res.Configuration;
37import android.content.res.Resources;
Dianne Hackbornba51c3d2010-05-05 18:49:48 -070038import android.content.res.TypedArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.database.Cursor;
40import android.graphics.Bitmap;
41import android.graphics.Canvas;
42import android.graphics.drawable.Drawable;
43import android.media.AudioManager;
44import android.net.Uri;
Dianne Hackborn8d374262009-09-14 21:21:52 -070045import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.Handler;
48import android.os.IBinder;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -080049import android.os.Looper;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -070050import android.os.Parcelable;
svetoslavganov75986cf2009-05-14 22:28:01 -070051import android.os.RemoteException;
Brad Fitzpatrick75803572011-01-13 14:21:03 -080052import android.os.StrictMode;
Dianne Hackbornf1c26e22012-08-23 13:54:58 -070053import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.text.Selection;
55import android.text.SpannableStringBuilder;
svetoslavganov75986cf2009-05-14 22:28:01 -070056import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.text.method.TextKeyListener;
58import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.util.EventLog;
60import android.util.Log;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070061import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.util.SparseArray;
Adam Powell6e346362010-07-23 10:18:23 -070063import android.view.ActionMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.ContextMenu;
Adam Powell6e346362010-07-23 10:18:23 -070065import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.view.ContextThemeWrapper;
67import android.view.KeyEvent;
68import android.view.LayoutInflater;
69import android.view.Menu;
70import android.view.MenuInflater;
71import android.view.MenuItem;
72import android.view.MotionEvent;
73import android.view.View;
Adam Powell6e346362010-07-23 10:18:23 -070074import android.view.View.OnCreateContextMenuListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.view.ViewGroup;
Adam Powell6e346362010-07-23 10:18:23 -070076import android.view.ViewGroup.LayoutParams;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.view.ViewManager;
78import android.view.Window;
79import android.view.WindowManager;
Jeff Brown98365d72012-08-19 20:30:52 -070080import android.view.WindowManagerGlobal;
svetoslavganov75986cf2009-05-14 22:28:01 -070081import android.view.accessibility.AccessibilityEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.widget.AdapterView;
83
Dianne Hackborn625ac272010-09-17 18:29:22 -070084import java.io.FileDescriptor;
85import java.io.PrintWriter;
Adam Powell6e346362010-07-23 10:18:23 -070086import java.util.ArrayList;
87import java.util.HashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
89/**
90 * An activity is a single, focused thing that the user can do. Almost all
91 * activities interact with the user, so the Activity class takes care of
92 * creating a window for you in which you can place your UI with
93 * {@link #setContentView}. While activities are often presented to the user
94 * as full-screen windows, they can also be used in other ways: as floating
95 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
96 * or embedded inside of another activity (using {@link ActivityGroup}).
97 *
98 * There are two methods almost all subclasses of Activity will implement:
99 *
100 * <ul>
101 * <li> {@link #onCreate} is where you initialize your activity. Most
102 * importantly, here you will usually call {@link #setContentView(int)}
103 * with a layout resource defining your UI, and using {@link #findViewById}
104 * to retrieve the widgets in that UI that you need to interact with
105 * programmatically.
106 *
107 * <li> {@link #onPause} is where you deal with the user leaving your
108 * activity. Most importantly, any changes made by the user should at this
109 * point be committed (usually to the
110 * {@link android.content.ContentProvider} holding the data).
111 * </ul>
112 *
113 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
114 * activity classes must have a corresponding
115 * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
116 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
117 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 * <p>Topics covered here:
119 * <ol>
Dianne Hackborn291905e2010-08-17 15:17:15 -0700120 * <li><a href="#Fragments">Fragments</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
122 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
123 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
124 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
125 * <li><a href="#Permissions">Permissions</a>
126 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
127 * </ol>
Joe Fernandezb54e7a32011-10-03 15:09:50 -0700128 *
129 * <div class="special reference">
130 * <h3>Developer Guides</h3>
131 * <p>The Activity class is an important part of an application's overall lifecycle,
132 * and the way activities are launched and put together is a fundamental
133 * part of the platform's application model. For a detailed perspective on the structure of an
134 * Android application and how activities behave, please read the
135 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and
136 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
137 * developer guides.</p>
138 *
139 * <p>You can also find a detailed discussion about how to create activities in the
140 * <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a>
141 * developer guide.</p>
142 * </div>
143 *
Dianne Hackborn291905e2010-08-17 15:17:15 -0700144 * <a name="Fragments"></a>
145 * <h3>Fragments</h3>
146 *
147 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
148 * implementations can make use of the {@link Fragment} class to better
149 * modularize their code, build more sophisticated user interfaces for larger
150 * screens, and help scale their application between small and large screens.
151 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 * <a name="ActivityLifecycle"></a>
153 * <h3>Activity Lifecycle</h3>
154 *
155 * <p>Activities in the system are managed as an <em>activity stack</em>.
156 * When a new activity is started, it is placed on the top of the stack
157 * and becomes the running activity -- the previous activity always remains
158 * below it in the stack, and will not come to the foreground again until
159 * the new activity exits.</p>
160 *
161 * <p>An activity has essentially four states:</p>
162 * <ul>
163 * <li> If an activity in the foreground of the screen (at the top of
164 * the stack),
165 * it is <em>active</em> or <em>running</em>. </li>
166 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
167 * or transparent activity has focus on top of your activity), it
168 * is <em>paused</em>. A paused activity is completely alive (it
169 * maintains all state and member information and remains attached to
170 * the window manager), but can be killed by the system in extreme
171 * low memory situations.
172 * <li>If an activity is completely obscured by another activity,
173 * it is <em>stopped</em>. It still retains all state and member information,
174 * however, it is no longer visible to the user so its window is hidden
175 * and it will often be killed by the system when memory is needed
176 * elsewhere.</li>
177 * <li>If an activity is paused or stopped, the system can drop the activity
178 * from memory by either asking it to finish, or simply killing its
179 * process. When it is displayed again to the user, it must be
180 * completely restarted and restored to its previous state.</li>
181 * </ul>
182 *
183 * <p>The following diagram shows the important state paths of an Activity.
184 * The square rectangles represent callback methods you can implement to
185 * perform operations when the Activity moves between states. The colored
186 * ovals are major states the Activity can be in.</p>
187 *
188 * <p><img src="../../../images/activity_lifecycle.png"
189 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
190 *
191 * <p>There are three key loops you may be interested in monitoring within your
192 * activity:
193 *
194 * <ul>
195 * <li>The <b>entire lifetime</b> of an activity happens between the first call
196 * to {@link android.app.Activity#onCreate} through to a single final call
197 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
198 * of "global" state in onCreate(), and release all remaining resources in
199 * onDestroy(). For example, if it has a thread running in the background
200 * to download data from the network, it may create that thread in onCreate()
201 * and then stop the thread in onDestroy().
202 *
203 * <li>The <b>visible lifetime</b> of an activity happens between a call to
204 * {@link android.app.Activity#onStart} until a corresponding call to
205 * {@link android.app.Activity#onStop}. During this time the user can see the
206 * activity on-screen, though it may not be in the foreground and interacting
207 * with the user. Between these two methods you can maintain resources that
208 * are needed to show the activity to the user. For example, you can register
209 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
Ken Wakasaf76a50c2012-03-09 19:56:35 +0900210 * that impact your UI, and unregister it in onStop() when the user no
211 * longer sees what you are displaying. The onStart() and onStop() methods
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 * can be called multiple times, as the activity becomes visible and hidden
213 * to the user.
214 *
215 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
216 * {@link android.app.Activity#onResume} until a corresponding call to
217 * {@link android.app.Activity#onPause}. During this time the activity is
218 * in front of all other activities and interacting with the user. An activity
219 * can frequently go between the resumed and paused states -- for example when
220 * the device goes to sleep, when an activity result is delivered, when a new
221 * intent is delivered -- so the code in these methods should be fairly
222 * lightweight.
223 * </ul>
224 *
225 * <p>The entire lifecycle of an activity is defined by the following
226 * Activity methods. All of these are hooks that you can override
227 * to do appropriate work when the activity changes state. All
228 * activities will implement {@link android.app.Activity#onCreate}
229 * to do their initial setup; many will also implement
230 * {@link android.app.Activity#onPause} to commit changes to data and
231 * otherwise prepare to stop interacting with the user. You should always
232 * call up to your superclass when implementing these methods.</p>
233 *
234 * </p>
235 * <pre class="prettyprint">
236 * public class Activity extends ApplicationContext {
237 * protected void onCreate(Bundle savedInstanceState);
238 *
239 * protected void onStart();
240 *
241 * protected void onRestart();
242 *
243 * protected void onResume();
244 *
245 * protected void onPause();
246 *
247 * protected void onStop();
248 *
249 * protected void onDestroy();
250 * }
251 * </pre>
252 *
253 * <p>In general the movement through an activity's lifecycle looks like
254 * this:</p>
255 *
256 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
257 * <colgroup align="left" span="3" />
258 * <colgroup align="left" />
259 * <colgroup align="center" />
260 * <colgroup align="center" />
261 *
262 * <thead>
263 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
264 * </thead>
265 *
266 * <tbody>
267 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
268 * <td>Called when the activity is first created.
269 * This is where you should do all of your normal static set up:
270 * create views, bind data to lists, etc. This method also
271 * provides you with a Bundle containing the activity's previously
272 * frozen state, if there was one.
273 * <p>Always followed by <code>onStart()</code>.</td>
274 * <td align="center">No</td>
275 * <td align="center"><code>onStart()</code></td>
276 * </tr>
277 *
278 * <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
279 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
280 * <td>Called after your activity has been stopped, prior to it being
281 * started again.
282 * <p>Always followed by <code>onStart()</code></td>
283 * <td align="center">No</td>
284 * <td align="center"><code>onStart()</code></td>
285 * </tr>
286 *
287 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
288 * <td>Called when the activity is becoming visible to the user.
289 * <p>Followed by <code>onResume()</code> if the activity comes
290 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
291 * <td align="center">No</td>
292 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
293 * </tr>
294 *
295 * <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
296 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
297 * <td>Called when the activity will start
298 * interacting with the user. At this point your activity is at
299 * the top of the activity stack, with user input going to it.
300 * <p>Always followed by <code>onPause()</code>.</td>
301 * <td align="center">No</td>
302 * <td align="center"><code>onPause()</code></td>
303 * </tr>
304 *
305 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
306 * <td>Called when the system is about to start resuming a previous
307 * activity. This is typically used to commit unsaved changes to
308 * persistent data, stop animations and other things that may be consuming
309 * CPU, etc. Implementations of this method must be very quick because
310 * the next activity will not be resumed until this method returns.
311 * <p>Followed by either <code>onResume()</code> if the activity
312 * returns back to the front, or <code>onStop()</code> if it becomes
313 * invisible to the user.</td>
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800314 * <td align="center"><font color="#800000"><strong>Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB}</strong></font></td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 * <td align="center"><code>onResume()</code> or<br>
316 * <code>onStop()</code></td>
317 * </tr>
318 *
319 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
320 * <td>Called when the activity is no longer visible to the user, because
321 * another activity has been resumed and is covering this one. This
322 * may happen either because a new activity is being started, an existing
323 * one is being brought in front of this one, or this one is being
324 * destroyed.
325 * <p>Followed by either <code>onRestart()</code> if
326 * this activity is coming back to interact with the user, or
327 * <code>onDestroy()</code> if this activity is going away.</td>
328 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
329 * <td align="center"><code>onRestart()</code> or<br>
330 * <code>onDestroy()</code></td>
331 * </tr>
332 *
333 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
334 * <td>The final call you receive before your
335 * activity is destroyed. This can happen either because the
336 * activity is finishing (someone called {@link Activity#finish} on
337 * it, or because the system is temporarily destroying this
338 * instance of the activity to save space. You can distinguish
339 * between these two scenarios with the {@link
340 * Activity#isFinishing} method.</td>
341 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
342 * <td align="center"><em>nothing</em></td>
343 * </tr>
344 * </tbody>
345 * </table>
346 *
347 * <p>Note the "Killable" column in the above table -- for those methods that
348 * are marked as being killable, after that method returns the process hosting the
349 * activity may killed by the system <em>at any time</em> without another line
350 * of its code being executed. Because of this, you should use the
351 * {@link #onPause} method to write any persistent data (such as user edits)
352 * to storage. In addition, the method
353 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
354 * in such a background state, allowing you to save away any dynamic instance
355 * state in your activity into the given Bundle, to be later received in
356 * {@link #onCreate} if the activity needs to be re-created.
357 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
358 * section for more information on how the lifecycle of a process is tied
359 * to the activities it is hosting. Note that it is important to save
360 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
Daisuke Miyakawa5c40f3f2011-02-15 13:24:36 -0800361 * because the latter is not part of the lifecycle callbacks, so will not
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 * be called in every situation as described in its documentation.</p>
363 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800364 * <p class="note">Be aware that these semantics will change slightly between
365 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
366 * vs. those targeting prior platforms. Starting with Honeycomb, an application
367 * is not in the killable state until its {@link #onStop} has returned. This
368 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
369 * safely called after {@link #onPause()} and allows and application to safely
370 * wait until {@link #onStop()} to save persistent state.</p>
371 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 * <p>For those methods that are not marked as being killable, the activity's
373 * process will not be killed by the system starting from the time the method
374 * is called and continuing after it returns. Thus an activity is in the killable
375 * state, for example, between after <code>onPause()</code> to the start of
376 * <code>onResume()</code>.</p>
377 *
378 * <a name="ConfigurationChanges"></a>
379 * <h3>Configuration Changes</h3>
380 *
381 * <p>If the configuration of the device (as defined by the
382 * {@link Configuration Resources.Configuration} class) changes,
383 * then anything displaying a user interface will need to update to match that
384 * configuration. Because Activity is the primary mechanism for interacting
385 * with the user, it includes special support for handling configuration
386 * changes.</p>
387 *
388 * <p>Unless you specify otherwise, a configuration change (such as a change
389 * in screen orientation, language, input devices, etc) will cause your
390 * current activity to be <em>destroyed</em>, going through the normal activity
391 * lifecycle process of {@link #onPause},
392 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
393 * had been in the foreground or visible to the user, once {@link #onDestroy} is
394 * called in that instance then a new instance of the activity will be
395 * created, with whatever savedInstanceState the previous instance had generated
396 * from {@link #onSaveInstanceState}.</p>
397 *
398 * <p>This is done because any application resource,
399 * including layout files, can change based on any configuration value. Thus
400 * the only safe way to handle a configuration change is to re-retrieve all
401 * resources, including layouts, drawables, and strings. Because activities
402 * must already know how to save their state and re-create themselves from
403 * that state, this is a convenient way to have an activity restart itself
404 * with a new configuration.</p>
405 *
406 * <p>In some special cases, you may want to bypass restarting of your
407 * activity based on one or more types of configuration changes. This is
408 * done with the {@link android.R.attr#configChanges android:configChanges}
409 * attribute in its manifest. For any types of configuration changes you say
410 * that you handle there, you will receive a call to your current activity's
411 * {@link #onConfigurationChanged} method instead of being restarted. If
412 * a configuration change involves any that you do not handle, however, the
413 * activity will still be restarted and {@link #onConfigurationChanged}
414 * will not be called.</p>
415 *
416 * <a name="StartingActivities"></a>
417 * <h3>Starting Activities and Getting Results</h3>
418 *
419 * <p>The {@link android.app.Activity#startActivity}
420 * method is used to start a
421 * new activity, which will be placed at the top of the activity stack. It
422 * takes a single argument, an {@link android.content.Intent Intent},
423 * which describes the activity
424 * to be executed.</p>
425 *
426 * <p>Sometimes you want to get a result back from an activity when it
427 * ends. For example, you may start an activity that lets the user pick
428 * a person in a list of contacts; when it ends, it returns the person
429 * that was selected. To do this, you call the
430 * {@link android.app.Activity#startActivityForResult(Intent, int)}
431 * version with a second integer parameter identifying the call. The result
432 * will come back through your {@link android.app.Activity#onActivityResult}
433 * method.</p>
434 *
435 * <p>When an activity exits, it can call
436 * {@link android.app.Activity#setResult(int)}
437 * to return data back to its parent. It must always supply a result code,
438 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
439 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
440 * return back an Intent containing any additional data it wants. All of this
441 * information appears back on the
442 * parent's <code>Activity.onActivityResult()</code>, along with the integer
443 * identifier it originally supplied.</p>
444 *
445 * <p>If a child activity fails for any reason (such as crashing), the parent
446 * activity will receive a result with the code RESULT_CANCELED.</p>
447 *
448 * <pre class="prettyprint">
449 * public class MyActivity extends Activity {
450 * ...
451 *
452 * static final int PICK_CONTACT_REQUEST = 0;
453 *
454 * protected boolean onKeyDown(int keyCode, KeyEvent event) {
455 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
456 * // When the user center presses, let them pick a contact.
457 * startActivityForResult(
458 * new Intent(Intent.ACTION_PICK,
459 * new Uri("content://contacts")),
460 * PICK_CONTACT_REQUEST);
461 * return true;
462 * }
463 * return false;
464 * }
465 *
466 * protected void onActivityResult(int requestCode, int resultCode,
467 * Intent data) {
468 * if (requestCode == PICK_CONTACT_REQUEST) {
469 * if (resultCode == RESULT_OK) {
470 * // A contact was picked. Here we will just display it
471 * // to the user.
472 * startActivity(new Intent(Intent.ACTION_VIEW, data));
473 * }
474 * }
475 * }
476 * }
477 * </pre>
478 *
479 * <a name="SavingPersistentState"></a>
480 * <h3>Saving Persistent State</h3>
481 *
482 * <p>There are generally two kinds of persistent state than an activity
483 * will deal with: shared document-like data (typically stored in a SQLite
484 * database using a {@linkplain android.content.ContentProvider content provider})
485 * and internal state such as user preferences.</p>
486 *
487 * <p>For content provider data, we suggest that activities use a
488 * "edit in place" user model. That is, any edits a user makes are effectively
489 * made immediately without requiring an additional confirmation step.
490 * Supporting this model is generally a simple matter of following two rules:</p>
491 *
492 * <ul>
493 * <li> <p>When creating a new document, the backing database entry or file for
494 * it is created immediately. For example, if the user chooses to write
495 * a new e-mail, a new entry for that e-mail is created as soon as they
496 * start entering data, so that if they go to any other activity after
497 * that point this e-mail will now appear in the list of drafts.</p>
498 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
499 * commit to the backing content provider or file any changes the user
500 * has made. This ensures that those changes will be seen by any other
501 * activity that is about to run. You will probably want to commit
502 * your data even more aggressively at key times during your
503 * activity's lifecycle: for example before starting a new
504 * activity, before finishing your own activity, when the user
505 * switches between input fields, etc.</p>
506 * </ul>
507 *
508 * <p>This model is designed to prevent data loss when a user is navigating
509 * between activities, and allows the system to safely kill an activity (because
510 * system resources are needed somewhere else) at any time after it has been
511 * paused. Note this implies
512 * that the user pressing BACK from your activity does <em>not</em>
513 * mean "cancel" -- it means to leave the activity with its current contents
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800514 * saved away. Canceling edits in an activity must be provided through
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
516 *
517 * <p>See the {@linkplain android.content.ContentProvider content package} for
518 * more information about content providers. These are a key aspect of how
519 * different activities invoke and propagate data between themselves.</p>
520 *
521 * <p>The Activity class also provides an API for managing internal persistent state
522 * associated with an activity. This can be used, for example, to remember
523 * the user's preferred initial display in a calendar (day view or week view)
524 * or the user's default home page in a web browser.</p>
525 *
526 * <p>Activity persistent state is managed
527 * with the method {@link #getPreferences},
528 * allowing you to retrieve and
529 * modify a set of name/value pairs associated with the activity. To use
530 * preferences that are shared across multiple application components
531 * (activities, receivers, services, providers), you can use the underlying
532 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
533 * to retrieve a preferences
534 * object stored under a specific name.
535 * (Note that it is not possible to share settings data across application
536 * packages -- for that you will need a content provider.)</p>
537 *
538 * <p>Here is an excerpt from a calendar activity that stores the user's
539 * preferred view mode in its persistent settings:</p>
540 *
541 * <pre class="prettyprint">
542 * public class CalendarActivity extends Activity {
543 * ...
544 *
545 * static final int DAY_VIEW_MODE = 0;
546 * static final int WEEK_VIEW_MODE = 1;
547 *
548 * private SharedPreferences mPrefs;
549 * private int mCurViewMode;
550 *
551 * protected void onCreate(Bundle savedInstanceState) {
552 * super.onCreate(savedInstanceState);
553 *
554 * SharedPreferences mPrefs = getSharedPreferences();
Quddus Chong3fa98cb2012-04-13 11:17:24 -0700555 * mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 * }
557 *
558 * protected void onPause() {
559 * super.onPause();
560 *
561 * SharedPreferences.Editor ed = mPrefs.edit();
562 * ed.putInt("view_mode", mCurViewMode);
563 * ed.commit();
564 * }
565 * }
566 * </pre>
567 *
568 * <a name="Permissions"></a>
569 * <h3>Permissions</h3>
570 *
571 * <p>The ability to start a particular Activity can be enforced when it is
572 * declared in its
573 * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
574 * tag. By doing so, other applications will need to declare a corresponding
575 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
576 * element in their own manifest to be able to start that activity.
Dianne Hackborn21c241e2012-03-08 13:57:23 -0800577 *
578 * <p>When starting an Activity you can set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
579 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
580 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the
581 * Activity access to the specific URIs in the Intent. Access will remain
582 * until the Activity has finished (it will remain across the hosting
583 * process being killed and other temporary destruction). As of
584 * {@link android.os.Build.VERSION_CODES#GINGERBREAD}, if the Activity
585 * was already created and a new Intent is being delivered to
586 * {@link #onNewIntent(Intent)}, any newly granted URI permissions will be added
587 * to the existing ones it holds.
588 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
590 * document for more information on permissions and security in general.
591 *
592 * <a name="ProcessLifecycle"></a>
593 * <h3>Process Lifecycle</h3>
594 *
595 * <p>The Android system attempts to keep application process around for as
596 * long as possible, but eventually will need to remove old processes when
597 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
598 * Lifecycle</a>, the decision about which process to remove is intimately
599 * tied to the state of the user's interaction with it. In general, there
600 * are four states a process can be in based on the activities running in it,
601 * listed here in order of importance. The system will kill less important
602 * processes (the last ones) before it resorts to killing more important
603 * processes (the first ones).
604 *
605 * <ol>
606 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
607 * that the user is currently interacting with) is considered the most important.
608 * Its process will only be killed as a last resort, if it uses more memory
609 * than is available on the device. Generally at this point the device has
610 * reached a memory paging state, so this is required in order to keep the user
611 * interface responsive.
612 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
613 * but not in the foreground, such as one sitting behind a foreground dialog)
614 * is considered extremely important and will not be killed unless that is
615 * required to keep the foreground activity running.
616 * <li> <p>A <b>background activity</b> (an activity that is not visible to
617 * the user and has been paused) is no longer critical, so the system may
618 * safely kill its process to reclaim memory for other foreground or
619 * visible processes. If its process needs to be killed, when the user navigates
620 * back to the activity (making it visible on the screen again), its
621 * {@link #onCreate} method will be called with the savedInstanceState it had previously
622 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
623 * state as the user last left it.
624 * <li> <p>An <b>empty process</b> is one hosting no activities or other
625 * application components (such as {@link Service} or
626 * {@link android.content.BroadcastReceiver} classes). These are killed very
627 * quickly by the system as memory becomes low. For this reason, any
628 * background operation you do outside of an activity must be executed in the
629 * context of an activity BroadcastReceiver or Service to ensure that the system
630 * knows it needs to keep your process around.
631 * </ol>
632 *
633 * <p>Sometimes an Activity may need to do a long-running operation that exists
634 * independently of the activity lifecycle itself. An example may be a camera
635 * application that allows you to upload a picture to a web site. The upload
636 * may take a long time, and the application should allow the user to leave
637 * the application will it is executing. To accomplish this, your Activity
638 * should start a {@link Service} in which the upload takes place. This allows
639 * the system to properly prioritize your process (considering it to be more
640 * important than other non-visible applications) for the duration of the
641 * upload, independent of whether the original activity is paused, stopped,
642 * or finished.
643 */
644public class Activity extends ContextThemeWrapper
Dianne Hackborn625ac272010-09-17 18:29:22 -0700645 implements LayoutInflater.Factory2,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 Window.Callback, KeyEvent.Callback,
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700647 OnCreateContextMenuListener, ComponentCallbacks2 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 private static final String TAG = "Activity";
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700649 private static final boolean DEBUG_LIFECYCLE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650
651 /** Standard activity result: operation canceled. */
652 public static final int RESULT_CANCELED = 0;
653 /** Standard activity result: operation succeeded. */
654 public static final int RESULT_OK = -1;
655 /** Start of user-defined activity results. */
656 public static final int RESULT_FIRST_USER = 1;
657
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700658 static final String FRAGMENTS_TAG = "android:fragments";
659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
661 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
662 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
663 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800664 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800666 private static class ManagedDialog {
667 Dialog mDialog;
668 Bundle mArgs;
669 }
670 private SparseArray<ManagedDialog> mManagedDialogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671
672 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
673 private Instrumentation mInstrumentation;
674 private IBinder mToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700675 private int mIdent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 /*package*/ String mEmbeddedID;
677 private Application mApplication;
Christopher Tateb70f3df2009-04-07 16:07:59 -0700678 /*package*/ Intent mIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 private ComponentName mComponent;
680 /*package*/ ActivityInfo mActivityInfo;
681 /*package*/ ActivityThread mMainThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 Activity mParent;
683 boolean mCalled;
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700684 boolean mCheckedForLoaderManager;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700685 boolean mLoadersStarted;
Jeff Hamilton52d32032011-01-08 15:31:26 -0600686 /*package*/ boolean mResumed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 private boolean mStopped;
688 boolean mFinished;
689 boolean mStartedActivity;
Dianne Hackborn6d9dcbc2012-10-02 17:51:13 -0700690 private boolean mDestroyed;
Dianne Hackborn2286cdc2013-07-01 19:10:06 -0700691 private boolean mDoReportFullyDrawn = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700692 /** true if the activity is going through a transient pause */
693 /*package*/ boolean mTemporaryPause = false;
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -0500694 /** true if the activity is being destroyed in order to recreate it with a new configuration */
695 /*package*/ boolean mChangingConfigurations = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 /*package*/ int mConfigChangeFlags;
697 /*package*/ Configuration mCurrentConfig;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +0100698 private SearchManager mSearchManager;
Adam Powell88ab6972011-07-28 11:25:01 -0700699 private MenuInflater mMenuInflater;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700701 static final class NonConfigurationInstances {
702 Object activity;
703 HashMap<String, Object> children;
704 ArrayList<Fragment> fragments;
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700705 ArrayMap<String, LoaderManagerImpl> loaders;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700706 }
707 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 private Window mWindow;
710
711 private WindowManager mWindowManager;
712 /*package*/ View mDecor = null;
713 /*package*/ boolean mWindowAdded = false;
714 /*package*/ boolean mVisibleFromServer = false;
715 /*package*/ boolean mVisibleFromClient = true;
Adam Powellac695c62010-07-20 18:19:27 -0700716 /*package*/ ActionBarImpl mActionBar = null;
Adam Powelldd8fab22012-03-22 17:47:27 -0700717 private boolean mEnableDefaultActionBarUp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718
719 private CharSequence mTitle;
720 private int mTitleColor = 0;
721
Dianne Hackbornb7a2e472010-08-12 16:20:42 -0700722 final FragmentManagerImpl mFragments = new FragmentManagerImpl();
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700723 final FragmentContainer mContainer = new FragmentContainer() {
724 @Override
725 public View findViewById(int id) {
726 return Activity.this.findViewById(id);
727 }
728 };
Dianne Hackborn2dedce62010-04-15 14:45:25 -0700729
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700730 ArrayMap<String, LoaderManagerImpl> mAllLoaderManagers;
Dianne Hackborn4911b782010-07-15 12:54:39 -0700731 LoaderManagerImpl mLoaderManager;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 private static final class ManagedCursor {
734 ManagedCursor(Cursor cursor) {
735 mCursor = cursor;
736 mReleased = false;
737 mUpdated = false;
738 }
739
740 private final Cursor mCursor;
741 private boolean mReleased;
742 private boolean mUpdated;
743 }
744 private final ArrayList<ManagedCursor> mManagedCursors =
745 new ArrayList<ManagedCursor>();
746
747 // protected by synchronized (this)
748 int mResultCode = RESULT_CANCELED;
749 Intent mResultData = null;
Craig Mautner5eda9b32013-07-02 11:58:16 -0700750 private TranslucentConversionListener mTranslucentCallback;
Craig Mautnerbc57cd12013-08-19 15:47:42 -0700751 private boolean mChangeCanvasToTranslucent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752
753 private boolean mTitleReady = false;
754
755 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
756 private SpannableStringBuilder mDefaultKeySsb = null;
757
758 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
759
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700760 @SuppressWarnings("unused")
Jeff Brown7e442832011-06-10 18:00:16 -0700761 private final Object mInstanceTracker = StrictMode.trackActivity(this);
762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 private Thread mUiThread;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700764 final Handler mHandler = new Handler();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 /** Return the intent that started this activity. */
767 public Intent getIntent() {
768 return mIntent;
769 }
770
771 /**
772 * Change the intent returned by {@link #getIntent}. This holds a
773 * reference to the given intent; it does not copy it. Often used in
774 * conjunction with {@link #onNewIntent}.
775 *
776 * @param newIntent The new Intent object to return from getIntent
777 *
778 * @see #getIntent
779 * @see #onNewIntent
780 */
781 public void setIntent(Intent newIntent) {
782 mIntent = newIntent;
783 }
784
785 /** Return the application that owns this activity. */
786 public final Application getApplication() {
787 return mApplication;
788 }
789
790 /** Is this activity embedded inside of another activity? */
791 public final boolean isChild() {
792 return mParent != null;
793 }
794
795 /** Return the parent activity if this view is an embedded child. */
796 public final Activity getParent() {
797 return mParent;
798 }
799
800 /** Retrieve the window manager for showing custom windows. */
801 public WindowManager getWindowManager() {
802 return mWindowManager;
803 }
804
805 /**
806 * Retrieve the current {@link android.view.Window} for the activity.
807 * This can be used to directly access parts of the Window API that
808 * are not available through Activity/Screen.
809 *
810 * @return Window The current window, or null if the activity is not
811 * visual.
812 */
813 public Window getWindow() {
814 return mWindow;
815 }
816
817 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -0700818 * Return the LoaderManager for this fragment, creating it if needed.
819 */
820 public LoaderManager getLoaderManager() {
821 if (mLoaderManager != null) {
822 return mLoaderManager;
823 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700824 mCheckedForLoaderManager = true;
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700825 mLoaderManager = getLoaderManager("(root)", mLoadersStarted, true);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700826 return mLoaderManager;
827 }
828
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700829 LoaderManagerImpl getLoaderManager(String who, boolean started, boolean create) {
Dianne Hackbornc8017682010-07-06 13:34:38 -0700830 if (mAllLoaderManagers == null) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700831 mAllLoaderManagers = new ArrayMap<String, LoaderManagerImpl>();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700832 }
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700833 LoaderManagerImpl lm = mAllLoaderManagers.get(who);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700834 if (lm == null) {
835 if (create) {
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700836 lm = new LoaderManagerImpl(who, this, started);
837 mAllLoaderManagers.put(who, lm);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700838 }
839 } else {
840 lm.updateActivity(this);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700841 }
842 return lm;
843 }
844
845 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 * Calls {@link android.view.Window#getCurrentFocus} on the
847 * Window of this Activity to return the currently focused view.
848 *
849 * @return View The current View with focus or null.
850 *
851 * @see #getWindow
852 * @see android.view.Window#getCurrentFocus
853 */
854 public View getCurrentFocus() {
855 return mWindow != null ? mWindow.getCurrentFocus() : null;
856 }
857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 /**
859 * Called when the activity is starting. This is where most initialization
860 * should go: calling {@link #setContentView(int)} to inflate the
861 * activity's UI, using {@link #findViewById} to programmatically interact
862 * with widgets in the UI, calling
863 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
864 * cursors for data being displayed, etc.
865 *
866 * <p>You can call {@link #finish} from within this function, in
867 * which case onDestroy() will be immediately called without any of the rest
868 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
869 * {@link #onPause}, etc) executing.
870 *
871 * <p><em>Derived classes must call through to the super class's
872 * implementation of this method. If they do not, an exception will be
873 * thrown.</em></p>
874 *
875 * @param savedInstanceState If the activity is being re-initialized after
876 * previously being shut down then this Bundle contains the data it most
877 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
878 *
879 * @see #onStart
880 * @see #onSaveInstanceState
881 * @see #onRestoreInstanceState
882 * @see #onPostCreate
883 */
884 protected void onCreate(Bundle savedInstanceState) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700885 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700886 if (mLastNonConfigurationInstances != null) {
887 mAllLoaderManagers = mLastNonConfigurationInstances.loaders;
888 }
Adam Powelldd8fab22012-03-22 17:47:27 -0700889 if (mActivityInfo.parentActivityName != null) {
890 if (mActionBar == null) {
891 mEnableDefaultActionBarUp = true;
892 } else {
893 mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
894 }
895 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700896 if (savedInstanceState != null) {
897 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
898 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
899 ? mLastNonConfigurationInstances.fragments : null);
900 }
901 mFragments.dispatchCreate();
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700902 getApplication().dispatchActivityCreated(this, savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 mCalled = true;
904 }
905
906 /**
907 * The hook for {@link ActivityThread} to restore the state of this activity.
908 *
909 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
910 * {@link #restoreManagedDialogs(android.os.Bundle)}.
911 *
912 * @param savedInstanceState contains the saved state
913 */
914 final void performRestoreInstanceState(Bundle savedInstanceState) {
915 onRestoreInstanceState(savedInstanceState);
916 restoreManagedDialogs(savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
918
919 /**
920 * This method is called after {@link #onStart} when the activity is
921 * being re-initialized from a previously saved state, given here in
Mike LeBeau305de9d2010-03-11 09:21:08 -0800922 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 * to restore their state, but it is sometimes convenient to do it here
924 * after all of the initialization has been done or to allow subclasses to
925 * decide whether to use your default implementation. The default
926 * implementation of this method performs a restore of any view state that
927 * had previously been frozen by {@link #onSaveInstanceState}.
928 *
929 * <p>This method is called between {@link #onStart} and
930 * {@link #onPostCreate}.
931 *
932 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
933 *
934 * @see #onCreate
935 * @see #onPostCreate
936 * @see #onResume
937 * @see #onSaveInstanceState
938 */
939 protected void onRestoreInstanceState(Bundle savedInstanceState) {
940 if (mWindow != null) {
941 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
942 if (windowState != null) {
943 mWindow.restoreHierarchyState(windowState);
944 }
945 }
946 }
947
948 /**
949 * Restore the state of any saved managed dialogs.
950 *
951 * @param savedInstanceState The bundle to restore from.
952 */
953 private void restoreManagedDialogs(Bundle savedInstanceState) {
954 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
955 if (b == null) {
956 return;
957 }
958
959 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
960 final int numDialogs = ids.length;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800961 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 for (int i = 0; i < numDialogs; i++) {
963 final Integer dialogId = ids[i];
964 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
965 if (dialogState != null) {
Romain Guye35c2352009-06-19 13:18:12 -0700966 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
967 // so tell createDialog() not to do it, otherwise we get an exception
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800968 final ManagedDialog md = new ManagedDialog();
969 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
970 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
971 if (md.mDialog != null) {
972 mManagedDialogs.put(dialogId, md);
973 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
974 md.mDialog.onRestoreInstanceState(dialogState);
975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
977 }
978 }
979
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800980 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
981 final Dialog dialog = onCreateDialog(dialogId, args);
Romain Guy764d5332009-06-17 16:52:22 -0700982 if (dialog == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800983 return null;
Romain Guy764d5332009-06-17 16:52:22 -0700984 }
Romain Guy6de4aed2009-07-08 10:54:45 -0700985 dialog.dispatchOnCreate(state);
Romain Guy764d5332009-06-17 16:52:22 -0700986 return dialog;
987 }
988
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800989 private static String savedDialogKeyFor(int key) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 return SAVED_DIALOG_KEY_PREFIX + key;
991 }
992
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800993 private static String savedDialogArgsKeyFor(int key) {
994 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996
997 /**
998 * Called when activity start-up is complete (after {@link #onStart}
999 * and {@link #onRestoreInstanceState} have been called). Applications will
1000 * generally not implement this method; it is intended for system
1001 * classes to do final initialization after application code has run.
1002 *
1003 * <p><em>Derived classes must call through to the super class's
1004 * implementation of this method. If they do not, an exception will be
1005 * thrown.</em></p>
1006 *
1007 * @param savedInstanceState If the activity is being re-initialized after
1008 * previously being shut down then this Bundle contains the data it most
1009 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
1010 * @see #onCreate
1011 */
1012 protected void onPostCreate(Bundle savedInstanceState) {
1013 if (!isChild()) {
1014 mTitleReady = true;
1015 onTitleChanged(getTitle(), getTitleColor());
1016 }
1017 mCalled = true;
1018 }
1019
1020 /**
1021 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
1022 * the activity had been stopped, but is now again being displayed to the
1023 * user. It will be followed by {@link #onResume}.
1024 *
1025 * <p><em>Derived classes must call through to the super class's
1026 * implementation of this method. If they do not, an exception will be
1027 * thrown.</em></p>
1028 *
1029 * @see #onCreate
1030 * @see #onStop
1031 * @see #onResume
1032 */
1033 protected void onStart() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001034 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 mCalled = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001036
1037 if (!mLoadersStarted) {
1038 mLoadersStarted = true;
1039 if (mLoaderManager != null) {
1040 mLoaderManager.doStart();
1041 } else if (!mCheckedForLoaderManager) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -07001042 mLoaderManager = getLoaderManager("(root)", mLoadersStarted, false);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001043 }
1044 mCheckedForLoaderManager = true;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001045 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001046
1047 getApplication().dispatchActivityStarted(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 }
1049
1050 /**
1051 * Called after {@link #onStop} when the current activity is being
1052 * re-displayed to the user (the user has navigated back to it). It will
1053 * be followed by {@link #onStart} and then {@link #onResume}.
1054 *
1055 * <p>For activities that are using raw {@link Cursor} objects (instead of
1056 * creating them through
1057 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1058 * this is usually the place
1059 * where the cursor should be requeried (because you had deactivated it in
1060 * {@link #onStop}.
1061 *
1062 * <p><em>Derived classes must call through to the super class's
1063 * implementation of this method. If they do not, an exception will be
1064 * thrown.</em></p>
1065 *
1066 * @see #onStop
1067 * @see #onStart
1068 * @see #onResume
1069 */
1070 protected void onRestart() {
1071 mCalled = true;
1072 }
1073
1074 /**
1075 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1076 * {@link #onPause}, for your activity to start interacting with the user.
1077 * This is a good place to begin animations, open exclusive-access devices
1078 * (such as the camera), etc.
1079 *
1080 * <p>Keep in mind that onResume is not the best indicator that your activity
1081 * is visible to the user; a system window such as the keyguard may be in
1082 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1083 * activity is visible to the user (for example, to resume a game).
1084 *
1085 * <p><em>Derived classes must call through to the super class's
1086 * implementation of this method. If they do not, an exception will be
1087 * thrown.</em></p>
1088 *
1089 * @see #onRestoreInstanceState
1090 * @see #onRestart
1091 * @see #onPostResume
1092 * @see #onPause
1093 */
1094 protected void onResume() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001095 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001096 getApplication().dispatchActivityResumed(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 mCalled = true;
1098 }
1099
1100 /**
1101 * Called when activity resume is complete (after {@link #onResume} has
1102 * been called). Applications will generally not implement this method;
1103 * it is intended for system classes to do final setup after application
1104 * resume code has run.
1105 *
1106 * <p><em>Derived classes must call through to the super class's
1107 * implementation of this method. If they do not, an exception will be
1108 * thrown.</em></p>
1109 *
1110 * @see #onResume
1111 */
1112 protected void onPostResume() {
1113 final Window win = getWindow();
1114 if (win != null) win.makeActive();
Adam Powell50efbed2011-02-08 16:20:15 -08001115 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 mCalled = true;
1117 }
1118
1119 /**
1120 * This is called for activities that set launchMode to "singleTop" in
1121 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1122 * flag when calling {@link #startActivity}. In either case, when the
1123 * activity is re-launched while at the top of the activity stack instead
1124 * of a new instance of the activity being started, onNewIntent() will be
1125 * called on the existing instance with the Intent that was used to
1126 * re-launch it.
1127 *
1128 * <p>An activity will always be paused before receiving a new intent, so
1129 * you can count on {@link #onResume} being called after this method.
1130 *
1131 * <p>Note that {@link #getIntent} still returns the original Intent. You
1132 * can use {@link #setIntent} to update it to this new Intent.
1133 *
1134 * @param intent The new intent that was started for the activity.
1135 *
1136 * @see #getIntent
1137 * @see #setIntent
1138 * @see #onResume
1139 */
1140 protected void onNewIntent(Intent intent) {
1141 }
1142
1143 /**
1144 * The hook for {@link ActivityThread} to save the state of this activity.
1145 *
1146 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1147 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1148 *
1149 * @param outState The bundle to save the state to.
1150 */
1151 final void performSaveInstanceState(Bundle outState) {
1152 onSaveInstanceState(outState);
1153 saveManagedDialogs(outState);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001154 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
1156
1157 /**
1158 * Called to retrieve per-instance state from an activity before being killed
1159 * so that the state can be restored in {@link #onCreate} or
1160 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1161 * will be passed to both).
1162 *
1163 * <p>This method is called before an activity may be killed so that when it
1164 * comes back some time in the future it can restore its state. For example,
1165 * if activity B is launched in front of activity A, and at some point activity
1166 * A is killed to reclaim resources, activity A will have a chance to save the
1167 * current state of its user interface via this method so that when the user
1168 * returns to activity A, the state of the user interface can be restored
1169 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1170 *
1171 * <p>Do not confuse this method with activity lifecycle callbacks such as
1172 * {@link #onPause}, which is always called when an activity is being placed
1173 * in the background or on its way to destruction, or {@link #onStop} which
1174 * is called before destruction. One example of when {@link #onPause} and
1175 * {@link #onStop} is called and not this method is when a user navigates back
1176 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1177 * on B because that particular instance will never be restored, so the
1178 * system avoids calling it. An example when {@link #onPause} is called and
1179 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1180 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1181 * killed during the lifetime of B since the state of the user interface of
1182 * A will stay intact.
1183 *
1184 * <p>The default implementation takes care of most of the UI per-instance
1185 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1186 * view in the hierarchy that has an id, and by saving the id of the currently
1187 * focused view (all of which is restored by the default implementation of
1188 * {@link #onRestoreInstanceState}). If you override this method to save additional
1189 * information not captured by each individual view, you will likely want to
1190 * call through to the default implementation, otherwise be prepared to save
1191 * all of the state of each view yourself.
1192 *
1193 * <p>If called, this method will occur before {@link #onStop}. There are
1194 * no guarantees about whether it will occur before or after {@link #onPause}.
1195 *
1196 * @param outState Bundle in which to place your saved state.
1197 *
1198 * @see #onCreate
1199 * @see #onRestoreInstanceState
1200 * @see #onPause
1201 */
1202 protected void onSaveInstanceState(Bundle outState) {
1203 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001204 Parcelable p = mFragments.saveAllState();
1205 if (p != null) {
1206 outState.putParcelable(FRAGMENTS_TAG, p);
1207 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001208 getApplication().dispatchActivitySaveInstanceState(this, outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
1210
1211 /**
1212 * Save the state of any managed dialogs.
1213 *
1214 * @param outState place to store the saved state.
1215 */
1216 private void saveManagedDialogs(Bundle outState) {
1217 if (mManagedDialogs == null) {
1218 return;
1219 }
1220
1221 final int numDialogs = mManagedDialogs.size();
1222 if (numDialogs == 0) {
1223 return;
1224 }
1225
1226 Bundle dialogState = new Bundle();
1227
1228 int[] ids = new int[mManagedDialogs.size()];
1229
1230 // save each dialog's bundle, gather the ids
1231 for (int i = 0; i < numDialogs; i++) {
1232 final int key = mManagedDialogs.keyAt(i);
1233 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001234 final ManagedDialog md = mManagedDialogs.valueAt(i);
1235 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1236 if (md.mArgs != null) {
1237 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 }
1240
1241 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1242 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1243 }
1244
1245
1246 /**
1247 * Called as part of the activity lifecycle when an activity is going into
1248 * the background, but has not (yet) been killed. The counterpart to
1249 * {@link #onResume}.
1250 *
1251 * <p>When activity B is launched in front of activity A, this callback will
1252 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1253 * so be sure to not do anything lengthy here.
1254 *
1255 * <p>This callback is mostly used for saving any persistent state the
1256 * activity is editing, to present a "edit in place" model to the user and
1257 * making sure nothing is lost if there are not enough resources to start
1258 * the new activity without first killing this one. This is also a good
1259 * place to do things like stop animations and other things that consume a
Pin Ting14a93102012-04-25 11:27:03 +08001260 * noticeable amount of CPU in order to make the switch to the next activity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 * as fast as possible, or to close resources that are exclusive access
1262 * such as the camera.
1263 *
1264 * <p>In situations where the system needs more memory it may kill paused
1265 * processes to reclaim resources. Because of this, you should be sure
1266 * that all of your state is saved by the time you return from
1267 * this function. In general {@link #onSaveInstanceState} is used to save
1268 * per-instance state in the activity and this method is used to store
1269 * global persistent data (in content providers, files, etc.)
1270 *
1271 * <p>After receiving this call you will usually receive a following call
1272 * to {@link #onStop} (after the next activity has been resumed and
1273 * displayed), however in some cases there will be a direct call back to
1274 * {@link #onResume} without going through the stopped state.
1275 *
1276 * <p><em>Derived classes must call through to the super class's
1277 * implementation of this method. If they do not, an exception will be
1278 * thrown.</em></p>
1279 *
1280 * @see #onResume
1281 * @see #onSaveInstanceState
1282 * @see #onStop
1283 */
1284 protected void onPause() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001285 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001286 getApplication().dispatchActivityPaused(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 mCalled = true;
1288 }
1289
1290 /**
1291 * Called as part of the activity lifecycle when an activity is about to go
1292 * into the background as the result of user choice. For example, when the
1293 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1294 * when an incoming phone call causes the in-call Activity to be automatically
1295 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1296 * the activity being interrupted. In cases when it is invoked, this method
1297 * is called right before the activity's {@link #onPause} callback.
1298 *
1299 * <p>This callback and {@link #onUserInteraction} are intended to help
1300 * activities manage status bar notifications intelligently; specifically,
1301 * for helping activities determine the proper time to cancel a notfication.
1302 *
1303 * @see #onUserInteraction()
1304 */
1305 protected void onUserLeaveHint() {
1306 }
1307
1308 /**
1309 * Generate a new thumbnail for this activity. This method is called before
1310 * pausing the activity, and should draw into <var>outBitmap</var> the
1311 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1312 * can use the given <var>canvas</var>, which is configured to draw into the
1313 * bitmap, for rendering if desired.
1314 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001315 * <p>The default implementation returns fails and does not draw a thumbnail;
1316 * this will result in the platform creating its own thumbnail if needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 *
1318 * @param outBitmap The bitmap to contain the thumbnail.
1319 * @param canvas Can be used to render into the bitmap.
1320 *
1321 * @return Return true if you have drawn into the bitmap; otherwise after
1322 * you return it will be filled with a default thumbnail.
1323 *
1324 * @see #onCreateDescription
1325 * @see #onSaveInstanceState
1326 * @see #onPause
1327 */
1328 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001329 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 }
1331
1332 /**
1333 * Generate a new description for this activity. This method is called
1334 * before pausing the activity and can, if desired, return some textual
1335 * description of its current state to be displayed to the user.
1336 *
1337 * <p>The default implementation returns null, which will cause you to
1338 * inherit the description from the previous activity. If all activities
1339 * return null, generally the label of the top activity will be used as the
1340 * description.
1341 *
1342 * @return A description of what the user is doing. It should be short and
1343 * sweet (only a few words).
1344 *
1345 * @see #onCreateThumbnail
1346 * @see #onSaveInstanceState
1347 * @see #onPause
1348 */
1349 public CharSequence onCreateDescription() {
1350 return null;
1351 }
1352
1353 /**
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001354 * This is called when the user is requesting an assist, to build a full
1355 * {@link Intent#ACTION_ASSIST} Intent with all of the context of the current
1356 * application. You can override this method to place into the bundle anything
1357 * you would like to appear in the {@link Intent#EXTRA_ASSIST_CONTEXT} part
1358 * of the assist Intent. The default implementation does nothing.
1359 *
1360 * <p>This function will be called after any global assist callbacks that had
Ying Wang4e0eb222013-04-18 20:39:48 -07001361 * been registered with {@link Application#registerOnProvideAssistDataListener
1362 * Application.registerOnProvideAssistDataListener}.
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001363 */
1364 public void onProvideAssistData(Bundle data) {
1365 }
1366
1367 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 * Called when you are no longer visible to the user. You will next
1369 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1370 * depending on later user activity.
1371 *
1372 * <p>Note that this method may never be called, in low memory situations
1373 * where the system does not have enough memory to keep your activity's
1374 * process running after its {@link #onPause} method is called.
1375 *
1376 * <p><em>Derived classes must call through to the super class's
1377 * implementation of this method. If they do not, an exception will be
1378 * thrown.</em></p>
1379 *
1380 * @see #onRestart
1381 * @see #onResume
1382 * @see #onSaveInstanceState
1383 * @see #onDestroy
1384 */
1385 protected void onStop() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001386 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
Adam Powell50efbed2011-02-08 16:20:15 -08001387 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001388 getApplication().dispatchActivityStopped(this);
Craig Mautner5eda9b32013-07-02 11:58:16 -07001389 mTranslucentCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 mCalled = true;
1391 }
1392
1393 /**
1394 * Perform any final cleanup before an activity is destroyed. This can
1395 * happen either because the activity is finishing (someone called
1396 * {@link #finish} on it, or because the system is temporarily destroying
1397 * this instance of the activity to save space. You can distinguish
1398 * between these two scenarios with the {@link #isFinishing} method.
1399 *
1400 * <p><em>Note: do not count on this method being called as a place for
1401 * saving data! For example, if an activity is editing data in a content
1402 * provider, those edits should be committed in either {@link #onPause} or
1403 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1404 * free resources like threads that are associated with an activity, so
1405 * that a destroyed activity does not leave such things around while the
1406 * rest of its application is still running. There are situations where
1407 * the system will simply kill the activity's hosting process without
1408 * calling this method (or any others) in it, so it should not be used to
1409 * do things that are intended to remain around after the process goes
1410 * away.
1411 *
1412 * <p><em>Derived classes must call through to the super class's
1413 * implementation of this method. If they do not, an exception will be
1414 * thrown.</em></p>
1415 *
1416 * @see #onPause
1417 * @see #onStop
1418 * @see #finish
1419 * @see #isFinishing
1420 */
1421 protected void onDestroy() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001422 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 mCalled = true;
1424
1425 // dismiss any dialogs we are managing.
1426 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 final int numDialogs = mManagedDialogs.size();
1428 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001429 final ManagedDialog md = mManagedDialogs.valueAt(i);
1430 if (md.mDialog.isShowing()) {
1431 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 }
1433 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001434 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436
1437 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001438 synchronized (mManagedCursors) {
1439 int numCursors = mManagedCursors.size();
1440 for (int i = 0; i < numCursors; i++) {
1441 ManagedCursor c = mManagedCursors.get(i);
1442 if (c != null) {
1443 c.mCursor.close();
1444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001446 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 }
Amith Yamasani49860442010-03-17 20:54:10 -07001448
1449 // Close any open search dialog
1450 if (mSearchManager != null) {
1451 mSearchManager.stopSearch();
1452 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001453
1454 getApplication().dispatchActivityDestroyed(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 }
1456
1457 /**
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07001458 * Report to the system that your app is now fully drawn. This is only used
1459 * to help instrument app launch times, so that the app can report when it is
1460 * fully in a usable state; without this, all the system can determine is when
1461 * its window is first drawn and displayed. To participate in app launch time
1462 * measurement, you should always call this method after first launch (when
1463 * {@link #onCreate(android.os.Bundle)} is called) at the point where you have
1464 * entirely drawn your UI and populated with all of the significant data. You
1465 * can safely call this method any time after first launch as well, in which case
1466 * it will simply be ignored.
1467 */
1468 public void reportFullyDrawn() {
1469 if (mDoReportFullyDrawn) {
1470 mDoReportFullyDrawn = false;
1471 try {
1472 ActivityManagerNative.getDefault().reportActivityFullyDrawn(mToken);
1473 } catch (RemoteException e) {
1474 }
1475 }
1476 }
1477
1478 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 * Called by the system when the device configuration changes while your
1480 * activity is running. Note that this will <em>only</em> be called if
1481 * you have selected configurations you would like to handle with the
1482 * {@link android.R.attr#configChanges} attribute in your manifest. If
1483 * any configuration change occurs that is not selected to be reported
1484 * by that attribute, then instead of reporting it the system will stop
1485 * and restart the activity (to have it launched with the new
1486 * configuration).
1487 *
1488 * <p>At the time that this function has been called, your Resources
1489 * object will have been updated to return resource values matching the
1490 * new configuration.
1491 *
1492 * @param newConfig The new device configuration.
1493 */
1494 public void onConfigurationChanged(Configuration newConfig) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001495 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onConfigurationChanged " + this + ": " + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001497
Dianne Hackborn9d071802010-12-08 14:49:15 -08001498 mFragments.dispatchConfigurationChanged(newConfig);
1499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 if (mWindow != null) {
1501 // Pass the configuration changed event to the window
1502 mWindow.onConfigurationChanged(newConfig);
1503 }
Adam Powell45c0b192011-07-28 15:11:57 -07001504
1505 if (mActionBar != null) {
1506 // Do this last; the action bar will need to access
1507 // view changes from above.
1508 mActionBar.onConfigurationChanged(newConfig);
1509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 }
1511
1512 /**
1513 * If this activity is being destroyed because it can not handle a
1514 * configuration parameter being changed (and thus its
1515 * {@link #onConfigurationChanged(Configuration)} method is
1516 * <em>not</em> being called), then you can use this method to discover
1517 * the set of changes that have occurred while in the process of being
1518 * destroyed. Note that there is no guarantee that these will be
1519 * accurate (other changes could have happened at any time), so you should
1520 * only use this as an optimization hint.
1521 *
1522 * @return Returns a bit field of the configuration parameters that are
1523 * changing, as defined by the {@link android.content.res.Configuration}
1524 * class.
1525 */
1526 public int getChangingConfigurations() {
1527 return mConfigChangeFlags;
1528 }
1529
1530 /**
1531 * Retrieve the non-configuration instance data that was previously
1532 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1533 * be available from the initial {@link #onCreate} and
1534 * {@link #onStart} calls to the new instance, allowing you to extract
1535 * any useful dynamic state from the previous instance.
1536 *
1537 * <p>Note that the data you retrieve here should <em>only</em> be used
1538 * as an optimization for handling configuration changes. You should always
1539 * be able to handle getting a null pointer back, and an activity must
1540 * still be able to restore itself to its previous state (through the
1541 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1542 * function returns null.
1543 *
1544 * @return Returns the object previously returned by
1545 * {@link #onRetainNonConfigurationInstance()}.
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07001546 *
1547 * @deprecated Use the new {@link Fragment} API
1548 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
1549 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07001551 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001553 return mLastNonConfigurationInstances != null
1554 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 }
1556
1557 /**
1558 * Called by the system, as part of destroying an
1559 * activity due to a configuration change, when it is known that a new
1560 * instance will immediately be created for the new configuration. You
1561 * can return any object you like here, including the activity instance
1562 * itself, which can later be retrieved by calling
1563 * {@link #getLastNonConfigurationInstance()} in the new activity
1564 * instance.
1565 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001566 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1567 * or later, consider instead using a {@link Fragment} with
1568 * {@link Fragment#setRetainInstance(boolean)
1569 * Fragment.setRetainInstance(boolean}.</em>
1570 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 * <p>This function is called purely as an optimization, and you must
1572 * not rely on it being called. When it is called, a number of guarantees
1573 * will be made to help optimize configuration switching:
1574 * <ul>
1575 * <li> The function will be called between {@link #onStop} and
1576 * {@link #onDestroy}.
1577 * <li> A new instance of the activity will <em>always</em> be immediately
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001578 * created after this one's {@link #onDestroy()} is called. In particular,
1579 * <em>no</em> messages will be dispatched during this time (when the returned
1580 * object does not have an activity to be associated with).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 * <li> The object you return here will <em>always</em> be available from
1582 * the {@link #getLastNonConfigurationInstance()} method of the following
1583 * activity instance as described there.
1584 * </ul>
1585 *
1586 * <p>These guarantees are designed so that an activity can use this API
1587 * to propagate extensive state from the old to new activity instance, from
1588 * loaded bitmaps, to network connections, to evenly actively running
1589 * threads. Note that you should <em>not</em> propagate any data that
1590 * may change based on the configuration, including any data loaded from
1591 * resources such as strings, layouts, or drawables.
1592 *
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001593 * <p>The guarantee of no message handling during the switch to the next
1594 * activity simplifies use with active objects. For example if your retained
1595 * state is an {@link android.os.AsyncTask} you are guaranteed that its
1596 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
1597 * not be called from the call here until you execute the next instance's
1598 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
1599 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
1600 * running in a separate thread.)
1601 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 * @return Return any Object holding the desired state to propagate to the
1603 * next activity instance.
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07001604 *
1605 * @deprecated Use the new {@link Fragment} API
1606 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
1607 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 */
1609 public Object onRetainNonConfigurationInstance() {
1610 return null;
1611 }
1612
1613 /**
1614 * Retrieve the non-configuration instance data that was previously
1615 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1616 * be available from the initial {@link #onCreate} and
1617 * {@link #onStart} calls to the new instance, allowing you to extract
1618 * any useful dynamic state from the previous instance.
1619 *
1620 * <p>Note that the data you retrieve here should <em>only</em> be used
1621 * as an optimization for handling configuration changes. You should always
1622 * be able to handle getting a null pointer back, and an activity must
1623 * still be able to restore itself to its previous state (through the
1624 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1625 * function returns null.
1626 *
1627 * @return Returns the object previously returned by
1628 * {@link #onRetainNonConfigurationChildInstances()}
1629 */
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001630 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1631 return mLastNonConfigurationInstances != null
1632 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634
1635 /**
1636 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1637 * it should return either a mapping from child activity id strings to arbitrary objects,
1638 * or null. This method is intended to be used by Activity framework subclasses that control a
1639 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1640 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1641 */
1642 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1643 return null;
1644 }
1645
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001646 NonConfigurationInstances retainNonConfigurationInstances() {
1647 Object activity = onRetainNonConfigurationInstance();
1648 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1649 ArrayList<Fragment> fragments = mFragments.retainNonConfig();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001650 boolean retainLoaders = false;
1651 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001652 // prune out any loader managers that were already stopped and so
Dianne Hackborn2707d602010-07-09 18:01:20 -07001653 // have nothing useful to retain.
Dianne Hackborn3e82ba12013-07-16 13:23:55 -07001654 final int N = mAllLoaderManagers.size();
1655 LoaderManagerImpl loaders[] = new LoaderManagerImpl[N];
1656 for (int i=N-1; i>=0; i--) {
1657 loaders[i] = mAllLoaderManagers.valueAt(i);
1658 }
1659 for (int i=0; i<N; i++) {
1660 LoaderManagerImpl lm = loaders[i];
1661 if (lm.mRetaining) {
1662 retainLoaders = true;
1663 } else {
1664 lm.doDestroy();
1665 mAllLoaderManagers.remove(lm.mWho);
Dianne Hackborn2707d602010-07-09 18:01:20 -07001666 }
1667 }
1668 }
1669 if (activity == null && children == null && fragments == null && !retainLoaders) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001670 return null;
1671 }
1672
1673 NonConfigurationInstances nci = new NonConfigurationInstances();
1674 nci.activity = activity;
1675 nci.children = children;
1676 nci.fragments = fragments;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001677 nci.loaders = mAllLoaderManagers;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001678 return nci;
1679 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 public void onLowMemory() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001682 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onLowMemory " + this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 mCalled = true;
Dianne Hackborn9d071802010-12-08 14:49:15 -08001684 mFragments.dispatchLowMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001686
1687 public void onTrimMemory(int level) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001688 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onTrimMemory " + this + ": " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001689 mCalled = true;
1690 mFragments.dispatchTrimMemory(level);
1691 }
1692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 /**
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07001694 * Return the FragmentManager for interacting with fragments associated
1695 * with this activity.
1696 */
1697 public FragmentManager getFragmentManager() {
1698 return mFragments;
1699 }
1700
Dianne Hackborn62bea2f2012-09-04 18:48:15 -07001701 void invalidateFragment(String who) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001702 //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001703 if (mAllLoaderManagers != null) {
Dianne Hackborn62bea2f2012-09-04 18:48:15 -07001704 LoaderManagerImpl lm = mAllLoaderManagers.get(who);
Dianne Hackbornd04ad542011-07-25 16:16:15 -07001705 if (lm != null && !lm.mRetaining) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001706 lm.doDestroy();
Dianne Hackborn62bea2f2012-09-04 18:48:15 -07001707 mAllLoaderManagers.remove(who);
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001708 }
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001709 }
1710 }
1711
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001712 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07001713 * Called when a Fragment is being attached to this activity, immediately
1714 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1715 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1716 */
1717 public void onAttachFragment(Fragment fragment) {
1718 }
1719
1720 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 * Wrapper around
1722 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1723 * that gives the resulting {@link Cursor} to call
1724 * {@link #startManagingCursor} so that the activity will manage its
1725 * lifecycle for you.
1726 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001727 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1728 * or later, consider instead using {@link LoaderManager} instead, available
1729 * via {@link #getLoaderManager()}.</em>
1730 *
Joe Fernandez8ef69702011-09-02 14:32:22 -07001731 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
1732 * this method, because the activity will do that for you at the appropriate time. However, if
1733 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
1734 * not</em> automatically close the cursor and, in that case, you must call
1735 * {@link Cursor#close()}.</p>
1736 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 * @param uri The URI of the content provider to query.
1738 * @param projection List of columns to return.
1739 * @param selection SQL WHERE clause.
1740 * @param sortOrder SQL ORDER BY clause.
1741 *
1742 * @return The Cursor that was returned by query().
1743 *
1744 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1745 * @see #startManagingCursor
1746 * @hide
Jason parks6ed50de2010-08-25 10:18:50 -05001747 *
1748 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 */
Jason parks6ed50de2010-08-25 10:18:50 -05001750 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001751 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1752 String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1754 if (c != null) {
1755 startManagingCursor(c);
1756 }
1757 return c;
1758 }
1759
1760 /**
1761 * Wrapper around
1762 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1763 * that gives the resulting {@link Cursor} to call
1764 * {@link #startManagingCursor} so that the activity will manage its
1765 * lifecycle for you.
1766 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001767 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1768 * or later, consider instead using {@link LoaderManager} instead, available
1769 * via {@link #getLoaderManager()}.</em>
1770 *
Joe Fernandez8ef69702011-09-02 14:32:22 -07001771 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
1772 * this method, because the activity will do that for you at the appropriate time. However, if
1773 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
1774 * not</em> automatically close the cursor and, in that case, you must call
1775 * {@link Cursor#close()}.</p>
1776 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 * @param uri The URI of the content provider to query.
1778 * @param projection List of columns to return.
1779 * @param selection SQL WHERE clause.
1780 * @param selectionArgs The arguments to selection, if any ?s are pesent
1781 * @param sortOrder SQL ORDER BY clause.
1782 *
1783 * @return The Cursor that was returned by query().
1784 *
1785 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1786 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001787 *
1788 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 */
Jason parks6ed50de2010-08-25 10:18:50 -05001790 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001791 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1792 String[] selectionArgs, String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1794 if (c != null) {
1795 startManagingCursor(c);
1796 }
1797 return c;
1798 }
1799
1800 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 * This method allows the activity to take care of managing the given
1802 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1803 * That is, when the activity is stopped it will automatically call
1804 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1805 * it will call {@link Cursor#requery} for you. When the activity is
1806 * destroyed, all managed Cursors will be closed automatically.
1807 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001808 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1809 * or later, consider instead using {@link LoaderManager} instead, available
1810 * via {@link #getLoaderManager()}.</em>
1811 *
Joe Fernandez8ef69702011-09-02 14:32:22 -07001812 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on cursor obtained from
1813 * {@link #managedQuery}, because the activity will do that for you at the appropriate time.
1814 * However, if you call {@link #stopManagingCursor} on a cursor from a managed query, the system
1815 * <em>will not</em> automatically close the cursor and, in that case, you must call
1816 * {@link Cursor#close()}.</p>
1817 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 * @param c The Cursor to be managed.
1819 *
1820 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1821 * @see #stopManagingCursor
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07001822 *
1823 * @deprecated Use the new {@link android.content.CursorLoader} class with
1824 * {@link LoaderManager} instead; this is also
1825 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 */
Jason parks6ed50de2010-08-25 10:18:50 -05001827 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 public void startManagingCursor(Cursor c) {
1829 synchronized (mManagedCursors) {
1830 mManagedCursors.add(new ManagedCursor(c));
1831 }
1832 }
1833
1834 /**
1835 * Given a Cursor that was previously given to
1836 * {@link #startManagingCursor}, stop the activity's management of that
1837 * cursor.
1838 *
Joe Fernandez8ef69702011-09-02 14:32:22 -07001839 * <p><strong>Warning:</strong> After calling this method on a cursor from a managed query,
1840 * the system <em>will not</em> automatically close the cursor and you must call
1841 * {@link Cursor#close()}.</p>
1842 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 * @param c The Cursor that was being managed.
1844 *
1845 * @see #startManagingCursor
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07001846 *
1847 * @deprecated Use the new {@link android.content.CursorLoader} class with
1848 * {@link LoaderManager} instead; this is also
1849 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 */
Jason parks6ed50de2010-08-25 10:18:50 -05001851 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 public void stopManagingCursor(Cursor c) {
1853 synchronized (mManagedCursors) {
1854 final int N = mManagedCursors.size();
1855 for (int i=0; i<N; i++) {
1856 ManagedCursor mc = mManagedCursors.get(i);
1857 if (mc.mCursor == c) {
1858 mManagedCursors.remove(i);
1859 break;
1860 }
1861 }
1862 }
1863 }
1864
1865 /**
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07001866 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
1867 * this is a no-op.
Dianne Hackborn4f3867e2010-12-14 22:09:51 -08001868 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 */
Dianne Hackbornd3efa392010-09-01 17:34:12 -07001870 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 public void setPersistent(boolean isPersistent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 }
1873
1874 /**
1875 * Finds a view that was identified by the id attribute from the XML that
1876 * was processed in {@link #onCreate}.
1877 *
1878 * @return The view if found or null otherwise.
1879 */
1880 public View findViewById(int id) {
1881 return getWindow().findViewById(id);
1882 }
Adam Powell33b97432010-04-20 10:01:14 -07001883
1884 /**
1885 * Retrieve a reference to this activity's ActionBar.
Adam Powell42c0fe82010-08-10 16:36:56 -07001886 *
Adam Powell33b97432010-04-20 10:01:14 -07001887 * @return The Activity's ActionBar, or null if it does not have one.
1888 */
1889 public ActionBar getActionBar() {
Adam Powell42c0fe82010-08-10 16:36:56 -07001890 initActionBar();
Adam Powell33b97432010-04-20 10:01:14 -07001891 return mActionBar;
1892 }
1893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 /**
Adam Powell33b97432010-04-20 10:01:14 -07001895 * Creates a new ActionBar, locates the inflated ActionBarView,
1896 * initializes the ActionBar with the view, and sets mActionBar.
1897 */
1898 private void initActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07001899 Window window = getWindow();
Adam Powella593d982011-05-13 14:09:54 -07001900
1901 // Initializing the window decor can change window feature flags.
1902 // Make sure that we have the correct set before performing the test below.
1903 window.getDecorView();
1904
Adam Powell9b4c8042010-08-10 15:36:44 -07001905 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07001906 return;
1907 }
Adam Powell04fe6eb2013-05-31 14:39:48 -07001908
Adam Powell661c9082010-07-02 10:09:44 -07001909 mActionBar = new ActionBarImpl(this);
Adam Powelldd8fab22012-03-22 17:47:27 -07001910 mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
Adam Powell04fe6eb2013-05-31 14:39:48 -07001911
1912 mWindow.setDefaultIcon(mActivityInfo.getIconResource());
1913 mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
Adam Powell33b97432010-04-20 10:01:14 -07001914 }
1915
1916 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 * Set the activity content from a layout resource. The resource will be
1918 * inflated, adding all top-level views to the activity.
Romain Guy482b34a62011-01-20 10:59:28 -08001919 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 * @param layoutResID Resource ID to be inflated.
Romain Guy482b34a62011-01-20 10:59:28 -08001921 *
1922 * @see #setContentView(android.view.View)
1923 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 */
1925 public void setContentView(int layoutResID) {
1926 getWindow().setContentView(layoutResID);
Adam Powell33b97432010-04-20 10:01:14 -07001927 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
1929
1930 /**
1931 * Set the activity content to an explicit view. This view is placed
1932 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a62011-01-20 10:59:28 -08001933 * view hierarchy. When calling this method, the layout parameters of the
1934 * specified view are ignored. Both the width and the height of the view are
1935 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
1936 * your own layout parameters, invoke
1937 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
1938 * instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 *
1940 * @param view The desired content to display.
Romain Guy482b34a62011-01-20 10:59:28 -08001941 *
1942 * @see #setContentView(int)
1943 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 */
1945 public void setContentView(View view) {
1946 getWindow().setContentView(view);
Adam Powell33b97432010-04-20 10:01:14 -07001947 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 }
1949
1950 /**
1951 * Set the activity content to an explicit view. This view is placed
1952 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a62011-01-20 10:59:28 -08001953 * view hierarchy.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 *
1955 * @param view The desired content to display.
1956 * @param params Layout parameters for the view.
Romain Guy482b34a62011-01-20 10:59:28 -08001957 *
1958 * @see #setContentView(android.view.View)
1959 * @see #setContentView(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 */
1961 public void setContentView(View view, ViewGroup.LayoutParams params) {
1962 getWindow().setContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001963 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 }
1965
1966 /**
1967 * Add an additional content view to the activity. Added after any existing
1968 * ones in the activity -- existing views are NOT removed.
1969 *
1970 * @param view The desired content to display.
1971 * @param params Layout parameters for the view.
1972 */
1973 public void addContentView(View view, ViewGroup.LayoutParams params) {
1974 getWindow().addContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001975 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
1977
1978 /**
Dianne Hackborncfaf8872011-01-18 13:57:54 -08001979 * Sets whether this activity is finished when touched outside its window's
1980 * bounds.
1981 */
1982 public void setFinishOnTouchOutside(boolean finish) {
1983 mWindow.setCloseOnTouchOutside(finish);
1984 }
1985
1986 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1988 * keys.
1989 *
1990 * @see #setDefaultKeyMode
1991 */
1992 static public final int DEFAULT_KEYS_DISABLE = 0;
1993 /**
1994 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1995 * key handling.
1996 *
1997 * @see #setDefaultKeyMode
1998 */
1999 static public final int DEFAULT_KEYS_DIALER = 1;
2000 /**
2001 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
2002 * default key handling.
2003 *
2004 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
2005 *
2006 * @see #setDefaultKeyMode
2007 */
2008 static public final int DEFAULT_KEYS_SHORTCUT = 2;
2009 /**
2010 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2011 * will start an application-defined search. (If the application or activity does not
2012 * actually define a search, the the keys will be ignored.)
2013 *
2014 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2015 *
2016 * @see #setDefaultKeyMode
2017 */
2018 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
2019
2020 /**
2021 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2022 * will start a global search (typically web search, but some platforms may define alternate
2023 * methods for global search)
2024 *
2025 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2026 *
2027 * @see #setDefaultKeyMode
2028 */
2029 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
2030
2031 /**
2032 * Select the default key handling for this activity. This controls what
2033 * will happen to key events that are not otherwise handled. The default
2034 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
2035 * floor. Other modes allow you to launch the dialer
2036 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
2037 * menu without requiring the menu key be held down
2038 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
2039 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
2040 *
2041 * <p>Note that the mode selected here does not impact the default
2042 * handling of system keys, such as the "back" and "menu" keys, and your
2043 * activity and its views always get a first chance to receive and handle
2044 * all application keys.
2045 *
2046 * @param mode The desired default key mode constant.
2047 *
2048 * @see #DEFAULT_KEYS_DISABLE
2049 * @see #DEFAULT_KEYS_DIALER
2050 * @see #DEFAULT_KEYS_SHORTCUT
2051 * @see #DEFAULT_KEYS_SEARCH_LOCAL
2052 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
2053 * @see #onKeyDown
2054 */
2055 public final void setDefaultKeyMode(int mode) {
2056 mDefaultKeyMode = mode;
2057
2058 // Some modes use a SpannableStringBuilder to track & dispatch input events
2059 // This list must remain in sync with the switch in onKeyDown()
2060 switch (mode) {
2061 case DEFAULT_KEYS_DISABLE:
2062 case DEFAULT_KEYS_SHORTCUT:
2063 mDefaultKeySsb = null; // not used in these modes
2064 break;
2065 case DEFAULT_KEYS_DIALER:
2066 case DEFAULT_KEYS_SEARCH_LOCAL:
2067 case DEFAULT_KEYS_SEARCH_GLOBAL:
2068 mDefaultKeySsb = new SpannableStringBuilder();
2069 Selection.setSelection(mDefaultKeySsb,0);
2070 break;
2071 default:
2072 throw new IllegalArgumentException();
2073 }
2074 }
2075
2076 /**
2077 * Called when a key was pressed down and not handled by any of the views
2078 * inside of the activity. So, for example, key presses while the cursor
2079 * is inside a TextView will not trigger the event (unless it is a navigation
2080 * to another object) because TextView handles its own key presses.
2081 *
2082 * <p>If the focused view didn't want this event, this method is called.
2083 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07002084 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
2085 * by calling {@link #onBackPressed()}, though the behavior varies based
2086 * on the application compatibility mode: for
2087 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
2088 * it will set up the dispatch to call {@link #onKeyUp} where the action
2089 * will be performed; for earlier applications, it will perform the
2090 * action immediately in on-down, as those versions of the platform
2091 * behaved.
2092 *
2093 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002094 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 *
2096 * @return Return <code>true</code> to prevent this event from being propagated
2097 * further, or <code>false</code> to indicate that you have not handled
2098 * this event and it should continue to be propagated.
2099 * @see #onKeyUp
2100 * @see android.view.KeyEvent
2101 */
2102 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002103 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002104 if (getApplicationInfo().targetSdkVersion
2105 >= Build.VERSION_CODES.ECLAIR) {
2106 event.startTracking();
2107 } else {
2108 onBackPressed();
2109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 return true;
2111 }
2112
2113 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
2114 return false;
2115 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002116 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
2117 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
2118 return true;
2119 }
2120 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 } else {
2122 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
2123 boolean clearSpannable = false;
2124 boolean handled;
2125 if ((event.getRepeatCount() != 0) || event.isSystem()) {
2126 clearSpannable = true;
2127 handled = false;
2128 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002129 handled = TextKeyListener.getInstance().onKeyDown(
2130 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 if (handled && mDefaultKeySsb.length() > 0) {
2132 // something useable has been typed - dispatch it now.
2133
2134 final String str = mDefaultKeySsb.toString();
2135 clearSpannable = true;
2136
2137 switch (mDefaultKeyMode) {
2138 case DEFAULT_KEYS_DIALER:
2139 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
2140 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2141 startActivity(intent);
2142 break;
2143 case DEFAULT_KEYS_SEARCH_LOCAL:
2144 startSearch(str, false, null, false);
2145 break;
2146 case DEFAULT_KEYS_SEARCH_GLOBAL:
2147 startSearch(str, false, null, true);
2148 break;
2149 }
2150 }
2151 }
2152 if (clearSpannable) {
2153 mDefaultKeySsb.clear();
2154 mDefaultKeySsb.clearSpans();
2155 Selection.setSelection(mDefaultKeySsb,0);
2156 }
2157 return handled;
2158 }
2159 }
2160
2161 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002162 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2163 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2164 * the event).
2165 */
2166 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2167 return false;
2168 }
2169
2170 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 * Called when a key was released and not handled by any of the views
2172 * inside of the activity. So, for example, key presses while the cursor
2173 * is inside a TextView will not trigger the event (unless it is a navigation
2174 * to another object) because TextView handles its own key presses.
2175 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002176 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2177 * and go back.
2178 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 * @return Return <code>true</code> to prevent this event from being propagated
2180 * further, or <code>false</code> to indicate that you have not handled
2181 * this event and it should continue to be propagated.
2182 * @see #onKeyDown
2183 * @see KeyEvent
2184 */
2185 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002186 if (getApplicationInfo().targetSdkVersion
2187 >= Build.VERSION_CODES.ECLAIR) {
2188 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2189 && !event.isCanceled()) {
2190 onBackPressed();
2191 return true;
2192 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 return false;
2195 }
2196
2197 /**
2198 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2199 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2200 * the event).
2201 */
2202 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2203 return false;
2204 }
2205
2206 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002207 * Called when the activity has detected the user's press of the back
2208 * key. The default implementation simply finishes the current activity,
2209 * but you can override this to do whatever you want.
2210 */
2211 public void onBackPressed() {
Dianne Hackborn3a57fb92010-11-15 17:58:52 -08002212 if (!mFragments.popBackStackImmediate()) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002213 finish();
2214 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002215 }
Jeff Brown64da12a2011-01-04 19:57:47 -08002216
2217 /**
2218 * Called when a key shortcut event is not handled by any of the views in the Activity.
2219 * Override this method to implement global key shortcuts for the Activity.
2220 * Key shortcuts can also be implemented by setting the
2221 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
2222 *
2223 * @param keyCode The value in event.getKeyCode().
2224 * @param event Description of the key event.
2225 * @return True if the key shortcut was handled.
2226 */
2227 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2228 return false;
2229 }
2230
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002231 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 * Called when a touch screen event was not handled by any of the views
2233 * under it. This is most useful to process touch events that happen
2234 * outside of your window bounds, where there is no view to receive it.
2235 *
2236 * @param event The touch screen event being processed.
2237 *
2238 * @return Return true if you have consumed the event, false if you haven't.
2239 * The default implementation always returns false.
2240 */
2241 public boolean onTouchEvent(MotionEvent event) {
Dianne Hackborncfaf8872011-01-18 13:57:54 -08002242 if (mWindow.shouldCloseOnTouch(this, event)) {
2243 finish();
2244 return true;
2245 }
2246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 return false;
2248 }
2249
2250 /**
2251 * Called when the trackball was moved and not handled by any of the
2252 * views inside of the activity. So, for example, if the trackball moves
2253 * while focus is on a button, you will receive a call here because
2254 * buttons do not normally do anything with trackball events. The call
2255 * here happens <em>before</em> trackball movements are converted to
2256 * DPAD key events, which then get sent back to the view hierarchy, and
2257 * will be processed at the point for things like focus navigation.
2258 *
2259 * @param event The trackball event being processed.
2260 *
2261 * @return Return true if you have consumed the event, false if you haven't.
2262 * The default implementation always returns false.
2263 */
2264 public boolean onTrackballEvent(MotionEvent event) {
2265 return false;
2266 }
Jeff Browncb1404e2011-01-15 18:14:15 -08002267
2268 /**
2269 * Called when a generic motion event was not handled by any of the
2270 * views inside of the activity.
2271 * <p>
Jeff Brown33bbfd22011-02-24 20:55:35 -08002272 * Generic motion events describe joystick movements, mouse hovers, track pad
2273 * touches, scroll wheel movements and other input events. The
Jeff Browncb1404e2011-01-15 18:14:15 -08002274 * {@link MotionEvent#getSource() source} of the motion event specifies
2275 * the class of input that was received. Implementations of this method
2276 * must examine the bits in the source before processing the event.
2277 * The following code example shows how this is done.
Jeff Brown33bbfd22011-02-24 20:55:35 -08002278 * </p><p>
2279 * Generic motion events with source class
2280 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
2281 * are delivered to the view under the pointer. All other generic motion events are
2282 * delivered to the focused view.
2283 * </p><p>
2284 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
2285 * handle this event.
Jeff Browncb1404e2011-01-15 18:14:15 -08002286 * </p>
Jeff Browncb1404e2011-01-15 18:14:15 -08002287 *
2288 * @param event The generic motion event being processed.
2289 *
2290 * @return Return true if you have consumed the event, false if you haven't.
2291 * The default implementation always returns false.
2292 */
2293 public boolean onGenericMotionEvent(MotionEvent event) {
2294 return false;
2295 }
2296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 /**
2298 * Called whenever a key, touch, or trackball event is dispatched to the
2299 * activity. Implement this method if you wish to know that the user has
2300 * interacted with the device in some way while your activity is running.
2301 * This callback and {@link #onUserLeaveHint} are intended to help
2302 * activities manage status bar notifications intelligently; specifically,
2303 * for helping activities determine the proper time to cancel a notfication.
2304 *
2305 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2306 * be accompanied by calls to {@link #onUserInteraction}. This
2307 * ensures that your activity will be told of relevant user activity such
2308 * as pulling down the notification pane and touching an item there.
2309 *
2310 * <p>Note that this callback will be invoked for the touch down action
2311 * that begins a touch gesture, but may not be invoked for the touch-moved
2312 * and touch-up actions that follow.
2313 *
2314 * @see #onUserLeaveHint()
2315 */
2316 public void onUserInteraction() {
2317 }
2318
2319 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2320 // Update window manager if: we have a view, that view is
2321 // attached to its parent (which will be a RootView), and
2322 // this activity is not embedded.
2323 if (mParent == null) {
2324 View decor = mDecor;
2325 if (decor != null && decor.getParent() != null) {
2326 getWindowManager().updateViewLayout(decor, params);
2327 }
2328 }
2329 }
2330
2331 public void onContentChanged() {
2332 }
2333
2334 /**
2335 * Called when the current {@link Window} of the activity gains or loses
2336 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002337 * to the user. The default implementation clears the key tracking
2338 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002340 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 * is managed independently of activity lifecycles. As such, while focus
2342 * changes will generally have some relation to lifecycle changes (an
2343 * activity that is stopped will not generally get window focus), you
2344 * should not rely on any particular order between the callbacks here and
2345 * those in the other lifecycle methods such as {@link #onResume}.
2346 *
2347 * <p>As a general rule, however, a resumed activity will have window
2348 * focus... unless it has displayed other dialogs or popups that take
2349 * input focus, in which case the activity itself will not have focus
2350 * when the other windows have it. Likewise, the system may display
2351 * system-level windows (such as the status bar notification panel or
2352 * a system alert) which will temporarily take window input focus without
2353 * pausing the foreground activity.
2354 *
2355 * @param hasFocus Whether the window of this activity has focus.
2356 *
2357 * @see #hasWindowFocus()
2358 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002359 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 */
2361 public void onWindowFocusChanged(boolean hasFocus) {
2362 }
2363
2364 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002365 * Called when the main window associated with the activity has been
2366 * attached to the window manager.
2367 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2368 * for more information.
2369 * @see View#onAttachedToWindow
2370 */
2371 public void onAttachedToWindow() {
2372 }
2373
2374 /**
2375 * Called when the main window associated with the activity has been
2376 * detached from the window manager.
2377 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2378 * for more information.
2379 * @see View#onDetachedFromWindow
2380 */
2381 public void onDetachedFromWindow() {
2382 }
2383
2384 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 * Returns true if this activity's <em>main</em> window currently has window focus.
2386 * Note that this is not the same as the view itself having focus.
2387 *
2388 * @return True if this activity's main window currently has window focus.
2389 *
2390 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2391 */
2392 public boolean hasWindowFocus() {
2393 Window w = getWindow();
2394 if (w != null) {
2395 View d = w.getDecorView();
2396 if (d != null) {
2397 return d.hasWindowFocus();
2398 }
2399 }
2400 return false;
2401 }
2402
2403 /**
2404 * Called to process key events. You can override this to intercept all
2405 * key events before they are dispatched to the window. Be sure to call
2406 * this implementation for key events that should be handled normally.
2407 *
2408 * @param event The key event.
2409 *
2410 * @return boolean Return true if this event was consumed.
2411 */
2412 public boolean dispatchKeyEvent(KeyEvent event) {
2413 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002414 Window win = getWindow();
2415 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 return true;
2417 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002418 View decor = mDecor;
2419 if (decor == null) decor = win.getDecorView();
2420 return event.dispatch(this, decor != null
2421 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 }
2423
2424 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08002425 * Called to process a key shortcut event.
2426 * You can override this to intercept all key shortcut events before they are
2427 * dispatched to the window. Be sure to call this implementation for key shortcut
2428 * events that should be handled normally.
2429 *
2430 * @param event The key shortcut event.
2431 * @return True if this event was consumed.
2432 */
2433 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
2434 onUserInteraction();
2435 if (getWindow().superDispatchKeyShortcutEvent(event)) {
2436 return true;
2437 }
2438 return onKeyShortcut(event.getKeyCode(), event);
2439 }
2440
2441 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 * Called to process touch screen events. You can override this to
2443 * intercept all touch screen events before they are dispatched to the
2444 * window. Be sure to call this implementation for touch screen events
2445 * that should be handled normally.
2446 *
2447 * @param ev The touch screen event.
2448 *
2449 * @return boolean Return true if this event was consumed.
2450 */
2451 public boolean dispatchTouchEvent(MotionEvent ev) {
2452 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2453 onUserInteraction();
2454 }
2455 if (getWindow().superDispatchTouchEvent(ev)) {
2456 return true;
2457 }
2458 return onTouchEvent(ev);
2459 }
2460
2461 /**
2462 * Called to process trackball events. You can override this to
2463 * intercept all trackball events before they are dispatched to the
2464 * window. Be sure to call this implementation for trackball events
2465 * that should be handled normally.
2466 *
2467 * @param ev The trackball event.
2468 *
2469 * @return boolean Return true if this event was consumed.
2470 */
2471 public boolean dispatchTrackballEvent(MotionEvent ev) {
2472 onUserInteraction();
2473 if (getWindow().superDispatchTrackballEvent(ev)) {
2474 return true;
2475 }
2476 return onTrackballEvent(ev);
2477 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002478
Jeff Browncb1404e2011-01-15 18:14:15 -08002479 /**
2480 * Called to process generic motion events. You can override this to
2481 * intercept all generic motion events before they are dispatched to the
2482 * window. Be sure to call this implementation for generic motion events
2483 * that should be handled normally.
2484 *
2485 * @param ev The generic motion event.
2486 *
2487 * @return boolean Return true if this event was consumed.
2488 */
2489 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
2490 onUserInteraction();
2491 if (getWindow().superDispatchGenericMotionEvent(ev)) {
2492 return true;
2493 }
2494 return onGenericMotionEvent(ev);
2495 }
2496
svetoslavganov75986cf2009-05-14 22:28:01 -07002497 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2498 event.setClassName(getClass().getName());
2499 event.setPackageName(getPackageName());
2500
2501 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002502 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2503 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002504 event.setFullScreen(isFullScreen);
2505
2506 CharSequence title = getTitle();
2507 if (!TextUtils.isEmpty(title)) {
2508 event.getText().add(title);
2509 }
2510
2511 return true;
2512 }
2513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 /**
2515 * Default implementation of
2516 * {@link android.view.Window.Callback#onCreatePanelView}
2517 * for activities. This
2518 * simply returns null so that all panel sub-windows will have the default
2519 * menu behavior.
2520 */
2521 public View onCreatePanelView(int featureId) {
2522 return null;
2523 }
2524
2525 /**
2526 * Default implementation of
2527 * {@link android.view.Window.Callback#onCreatePanelMenu}
2528 * for activities. This calls through to the new
2529 * {@link #onCreateOptionsMenu} method for the
2530 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2531 * so that subclasses of Activity don't need to deal with feature codes.
2532 */
2533 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2534 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002535 boolean show = onCreateOptionsMenu(menu);
2536 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2537 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 }
2539 return false;
2540 }
2541
2542 /**
2543 * Default implementation of
2544 * {@link android.view.Window.Callback#onPreparePanel}
2545 * for activities. This
2546 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2547 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2548 * panel, so that subclasses of
2549 * Activity don't need to deal with feature codes.
2550 */
2551 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2552 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2553 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002554 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
Adam Powellef31e7c2012-05-08 09:59:40 -07002555 return goforit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 }
2557 return true;
2558 }
2559
2560 /**
2561 * {@inheritDoc}
2562 *
2563 * @return The default implementation returns true.
2564 */
2565 public boolean onMenuOpened(int featureId, Menu menu) {
Adam Powell8515ee82010-11-30 14:09:55 -08002566 if (featureId == Window.FEATURE_ACTION_BAR) {
Adam Powell763cbb12011-03-01 10:45:34 -08002567 initActionBar();
Adam Powell049dd3d2010-12-02 13:43:59 -08002568 if (mActionBar != null) {
2569 mActionBar.dispatchMenuVisibilityChanged(true);
2570 } else {
2571 Log.e(TAG, "Tried to open action bar menu with no action bar");
2572 }
Adam Powell8515ee82010-11-30 14:09:55 -08002573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 return true;
2575 }
2576
2577 /**
2578 * Default implementation of
2579 * {@link android.view.Window.Callback#onMenuItemSelected}
2580 * for activities. This calls through to the new
2581 * {@link #onOptionsItemSelected} method for the
2582 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2583 * panel, so that subclasses of
2584 * Activity don't need to deal with feature codes.
2585 */
2586 public boolean onMenuItemSelected(int featureId, MenuItem item) {
zobject686a8052012-12-14 21:11:08 +09002587 CharSequence titleCondensed = item.getTitleCondensed();
2588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 switch (featureId) {
2590 case Window.FEATURE_OPTIONS_PANEL:
2591 // Put event logging here so it gets called even if subclass
2592 // doesn't call through to superclass's implmeentation of each
2593 // of these methods below
zobject686a8052012-12-14 21:11:08 +09002594 if(titleCondensed != null) {
2595 EventLog.writeEvent(50000, 0, titleCondensed.toString());
2596 }
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002597 if (onOptionsItemSelected(item)) {
2598 return true;
2599 }
Adam Powell04d58112012-04-09 10:22:12 -07002600 if (mFragments.dispatchOptionsItemSelected(item)) {
2601 return true;
2602 }
2603 if (item.getItemId() == android.R.id.home && mActionBar != null &&
2604 (mActionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
2605 if (mParent == null) {
Adam Powell07304f5292012-05-07 17:32:44 -07002606 return onNavigateUp();
Adam Powell04d58112012-04-09 10:22:12 -07002607 } else {
Adam Powell07304f5292012-05-07 17:32:44 -07002608 return mParent.onNavigateUpFromChild(this);
Adam Powell04d58112012-04-09 10:22:12 -07002609 }
Adam Powell04d58112012-04-09 10:22:12 -07002610 }
2611 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612
2613 case Window.FEATURE_CONTEXT_MENU:
zobject686a8052012-12-14 21:11:08 +09002614 if(titleCondensed != null) {
2615 EventLog.writeEvent(50000, 1, titleCondensed.toString());
2616 }
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07002617 if (onContextItemSelected(item)) {
2618 return true;
2619 }
2620 return mFragments.dispatchContextItemSelected(item);
Adam Powell8515ee82010-11-30 14:09:55 -08002621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 default:
2623 return false;
2624 }
2625 }
2626
2627 /**
2628 * Default implementation of
2629 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2630 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2631 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2632 * so that subclasses of Activity don't need to deal with feature codes.
2633 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2634 * {@link #onContextMenuClosed(Menu)} will be called.
2635 */
2636 public void onPanelClosed(int featureId, Menu menu) {
2637 switch (featureId) {
2638 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002639 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 onOptionsMenuClosed(menu);
2641 break;
2642
2643 case Window.FEATURE_CONTEXT_MENU:
2644 onContextMenuClosed(menu);
2645 break;
Adam Powell8515ee82010-11-30 14:09:55 -08002646
2647 case Window.FEATURE_ACTION_BAR:
Adam Powell9b4bee02011-04-27 19:24:47 -07002648 initActionBar();
Adam Powell8515ee82010-11-30 14:09:55 -08002649 mActionBar.dispatchMenuVisibilityChanged(false);
2650 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 }
2652 }
2653
2654 /**
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002655 * Declare that the options menu has changed, so should be recreated.
2656 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2657 * time it needs to be displayed.
2658 */
2659 public void invalidateOptionsMenu() {
2660 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2661 }
2662
2663 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 * Initialize the contents of the Activity's standard options menu. You
2665 * should place your menu items in to <var>menu</var>.
2666 *
2667 * <p>This is only called once, the first time the options menu is
2668 * displayed. To update the menu every time it is displayed, see
2669 * {@link #onPrepareOptionsMenu}.
2670 *
2671 * <p>The default implementation populates the menu with standard system
2672 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2673 * they will be correctly ordered with application-defined menu items.
2674 * Deriving classes should always call through to the base implementation.
2675 *
2676 * <p>You can safely hold on to <var>menu</var> (and any items created
2677 * from it), making modifications to it as desired, until the next
2678 * time onCreateOptionsMenu() is called.
2679 *
2680 * <p>When you add items to the menu, you can implement the Activity's
2681 * {@link #onOptionsItemSelected} method to handle them there.
2682 *
2683 * @param menu The options menu in which you place your items.
2684 *
2685 * @return You must return true for the menu to be displayed;
2686 * if you return false it will not be shown.
2687 *
2688 * @see #onPrepareOptionsMenu
2689 * @see #onOptionsItemSelected
2690 */
2691 public boolean onCreateOptionsMenu(Menu menu) {
2692 if (mParent != null) {
2693 return mParent.onCreateOptionsMenu(menu);
2694 }
2695 return true;
2696 }
2697
2698 /**
2699 * Prepare the Screen's standard options menu to be displayed. This is
2700 * called right before the menu is shown, every time it is shown. You can
2701 * use this method to efficiently enable/disable items or otherwise
2702 * dynamically modify the contents.
2703 *
2704 * <p>The default implementation updates the system menu items based on the
2705 * activity's state. Deriving classes should always call through to the
2706 * base class implementation.
2707 *
2708 * @param menu The options menu as last shown or first initialized by
2709 * onCreateOptionsMenu().
2710 *
2711 * @return You must return true for the menu to be displayed;
2712 * if you return false it will not be shown.
2713 *
2714 * @see #onCreateOptionsMenu
2715 */
2716 public boolean onPrepareOptionsMenu(Menu menu) {
2717 if (mParent != null) {
2718 return mParent.onPrepareOptionsMenu(menu);
2719 }
2720 return true;
2721 }
2722
2723 /**
2724 * This hook is called whenever an item in your options menu is selected.
2725 * The default implementation simply returns false to have the normal
2726 * processing happen (calling the item's Runnable or sending a message to
2727 * its Handler as appropriate). You can use this method for any items
2728 * for which you would like to do processing without those other
2729 * facilities.
2730 *
2731 * <p>Derived classes should call through to the base class for it to
Adam Powelldd8fab22012-03-22 17:47:27 -07002732 * perform the default menu handling.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 *
2734 * @param item The menu item that was selected.
2735 *
2736 * @return boolean Return false to allow normal menu processing to
2737 * proceed, true to consume it here.
2738 *
2739 * @see #onCreateOptionsMenu
2740 */
2741 public boolean onOptionsItemSelected(MenuItem item) {
2742 if (mParent != null) {
2743 return mParent.onOptionsItemSelected(item);
2744 }
2745 return false;
2746 }
2747
2748 /**
Adam Powelldd8fab22012-03-22 17:47:27 -07002749 * This method is called whenever the user chooses to navigate Up within your application's
2750 * activity hierarchy from the action bar.
2751 *
2752 * <p>If the attribute {@link android.R.attr#parentActivityName parentActivityName}
2753 * was specified in the manifest for this activity or an activity-alias to it,
2754 * default Up navigation will be handled automatically. If any activity
2755 * along the parent chain requires extra Intent arguments, the Activity subclass
2756 * should override the method {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}
2757 * to supply those arguments.</p>
2758 *
2759 * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
2760 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
2761 * from the design guide for more information about navigating within your app.</p>
2762 *
2763 * <p>See the {@link TaskStackBuilder} class and the Activity methods
2764 * {@link #getParentActivityIntent()}, {@link #shouldUpRecreateTask(Intent)}, and
2765 * {@link #navigateUpTo(Intent)} for help implementing custom Up navigation.
2766 * The AppNavigation sample application in the Android SDK is also available for reference.</p>
2767 *
2768 * @return true if Up navigation completed successfully and this Activity was finished,
2769 * false otherwise.
2770 */
2771 public boolean onNavigateUp() {
2772 // Automatically handle hierarchical Up navigation if the proper
2773 // metadata is available.
2774 Intent upIntent = getParentActivityIntent();
2775 if (upIntent != null) {
Adam Powell0fc5b2b2012-07-18 18:20:29 -07002776 if (mActivityInfo.taskAffinity == null) {
2777 // Activities with a null affinity are special; they really shouldn't
2778 // specify a parent activity intent in the first place. Just finish
2779 // the current activity and call it a day.
2780 finish();
2781 } else if (shouldUpRecreateTask(upIntent)) {
Adam Powellf78a8442012-05-01 18:09:32 -07002782 TaskStackBuilder b = TaskStackBuilder.create(this);
Adam Powelldd8fab22012-03-22 17:47:27 -07002783 onCreateNavigateUpTaskStack(b);
2784 onPrepareNavigateUpTaskStack(b);
2785 b.startActivities();
Adam Powell3d193d92012-05-15 16:51:55 -07002786
2787 // We can't finishAffinity if we have a result.
2788 // Fall back and simply finish the current activity instead.
2789 if (mResultCode != RESULT_CANCELED || mResultData != null) {
2790 // Tell the developer what's going on to avoid hair-pulling.
2791 Log.i(TAG, "onNavigateUp only finishing topmost activity to return a result");
2792 finish();
2793 } else {
2794 finishAffinity();
2795 }
Adam Powelldd8fab22012-03-22 17:47:27 -07002796 } else {
2797 navigateUpTo(upIntent);
2798 }
2799 return true;
2800 }
2801 return false;
2802 }
2803
2804 /**
2805 * This is called when a child activity of this one attempts to navigate up.
2806 * The default implementation simply calls onNavigateUp() on this activity (the parent).
2807 *
2808 * @param child The activity making the call.
2809 */
2810 public boolean onNavigateUpFromChild(Activity child) {
2811 return onNavigateUp();
2812 }
2813
2814 /**
2815 * Define the synthetic task stack that will be generated during Up navigation from
2816 * a different task.
2817 *
2818 * <p>The default implementation of this method adds the parent chain of this activity
2819 * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications
2820 * may choose to override this method to construct the desired task stack in a different
2821 * way.</p>
2822 *
Adam Powellf0195952012-05-02 21:38:54 -07002823 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
2824 * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent
2825 * returned by {@link #getParentActivityIntent()}.</p>
2826 *
Adam Powelldd8fab22012-03-22 17:47:27 -07002827 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
2828 * by the manifest should override {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}.</p>
2829 *
2830 * @param builder An empty TaskStackBuilder - the application should add intents representing
2831 * the desired task stack
2832 */
2833 public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) {
2834 builder.addParentStack(this);
2835 }
2836
2837 /**
2838 * Prepare the synthetic task stack that will be generated during Up navigation
2839 * from a different task.
2840 *
2841 * <p>This method receives the {@link TaskStackBuilder} with the constructed series of
2842 * Intents as generated by {@link #onCreateNavigateUpTaskStack(TaskStackBuilder)}.
2843 * If any extra data should be added to these intents before launching the new task,
2844 * the application should override this method and add that data here.</p>
2845 *
2846 * @param builder A TaskStackBuilder that has been populated with Intents by
2847 * onCreateNavigateUpTaskStack.
2848 */
2849 public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) {
2850 }
2851
2852 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 * This hook is called whenever the options menu is being closed (either by the user canceling
2854 * the menu with the back/menu button, or when an item is selected).
2855 *
2856 * @param menu The options menu as last shown or first initialized by
2857 * onCreateOptionsMenu().
2858 */
2859 public void onOptionsMenuClosed(Menu menu) {
2860 if (mParent != null) {
2861 mParent.onOptionsMenuClosed(menu);
2862 }
2863 }
2864
2865 /**
2866 * Programmatically opens the options menu. If the options menu is already
2867 * open, this method does nothing.
2868 */
2869 public void openOptionsMenu() {
2870 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2871 }
2872
2873 /**
2874 * Progammatically closes the options menu. If the options menu is already
2875 * closed, this method does nothing.
2876 */
2877 public void closeOptionsMenu() {
2878 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2879 }
2880
2881 /**
2882 * Called when a context menu for the {@code view} is about to be shown.
2883 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2884 * time the context menu is about to be shown and should be populated for
2885 * the view (or item inside the view for {@link AdapterView} subclasses,
2886 * this can be found in the {@code menuInfo})).
2887 * <p>
2888 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2889 * item has been selected.
2890 * <p>
2891 * It is not safe to hold onto the context menu after this method returns.
Scott Maincdf51062013-01-08 20:03:05 -08002892 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 */
2894 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2895 }
2896
2897 /**
2898 * Registers a context menu to be shown for the given view (multiple views
2899 * can show the context menu). This method will set the
2900 * {@link OnCreateContextMenuListener} on the view to this activity, so
2901 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2902 * called when it is time to show the context menu.
2903 *
2904 * @see #unregisterForContextMenu(View)
2905 * @param view The view that should show a context menu.
2906 */
2907 public void registerForContextMenu(View view) {
2908 view.setOnCreateContextMenuListener(this);
2909 }
2910
2911 /**
2912 * Prevents a context menu to be shown for the given view. This method will remove the
2913 * {@link OnCreateContextMenuListener} on the view.
2914 *
2915 * @see #registerForContextMenu(View)
2916 * @param view The view that should stop showing a context menu.
2917 */
2918 public void unregisterForContextMenu(View view) {
2919 view.setOnCreateContextMenuListener(null);
2920 }
2921
2922 /**
2923 * Programmatically opens the context menu for a particular {@code view}.
2924 * The {@code view} should have been added via
2925 * {@link #registerForContextMenu(View)}.
2926 *
2927 * @param view The view to show the context menu for.
2928 */
2929 public void openContextMenu(View view) {
2930 view.showContextMenu();
2931 }
2932
2933 /**
2934 * Programmatically closes the most recently opened context menu, if showing.
2935 */
2936 public void closeContextMenu() {
2937 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2938 }
2939
2940 /**
2941 * This hook is called whenever an item in a context menu is selected. The
2942 * default implementation simply returns false to have the normal processing
2943 * happen (calling the item's Runnable or sending a message to its Handler
2944 * as appropriate). You can use this method for any items for which you
2945 * would like to do processing without those other facilities.
2946 * <p>
2947 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2948 * View that added this menu item.
2949 * <p>
2950 * Derived classes should call through to the base class for it to perform
2951 * the default menu handling.
2952 *
2953 * @param item The context menu item that was selected.
2954 * @return boolean Return false to allow normal context menu processing to
2955 * proceed, true to consume it here.
2956 */
2957 public boolean onContextItemSelected(MenuItem item) {
2958 if (mParent != null) {
2959 return mParent.onContextItemSelected(item);
2960 }
2961 return false;
2962 }
2963
2964 /**
2965 * This hook is called whenever the context menu is being closed (either by
2966 * the user canceling the menu with the back/menu button, or when an item is
2967 * selected).
2968 *
2969 * @param menu The context menu that is being closed.
2970 */
2971 public void onContextMenuClosed(Menu menu) {
2972 if (mParent != null) {
2973 mParent.onContextMenuClosed(menu);
2974 }
2975 }
2976
2977 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002978 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002980 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 protected Dialog onCreateDialog(int id) {
2982 return null;
2983 }
2984
2985 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002986 * Callback for creating dialogs that are managed (saved and restored) for you
2987 * by the activity. The default implementation calls through to
2988 * {@link #onCreateDialog(int)} for compatibility.
2989 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002990 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2991 * or later, consider instead using a {@link DialogFragment} instead.</em>
2992 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002993 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2994 * this method the first time, and hang onto it thereafter. Any dialog
2995 * that is created by this method will automatically be saved and restored
2996 * for you, including whether it is showing.
2997 *
2998 * <p>If you would like the activity to manage saving and restoring dialogs
2999 * for you, you should override this method and handle any ids that are
3000 * passed to {@link #showDialog}.
3001 *
3002 * <p>If you would like an opportunity to prepare your dialog before it is shown,
3003 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
3004 *
3005 * @param id The id of the dialog.
3006 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3007 * @return The dialog. If you return null, the dialog will not be created.
3008 *
3009 * @see #onPrepareDialog(int, Dialog, Bundle)
3010 * @see #showDialog(int, Bundle)
3011 * @see #dismissDialog(int)
3012 * @see #removeDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003013 *
3014 * @deprecated Use the new {@link DialogFragment} class with
3015 * {@link FragmentManager} instead; this is also
3016 * available on older platforms through the Android compatibility package.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003017 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07003018 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003019 protected Dialog onCreateDialog(int id, Bundle args) {
3020 return onCreateDialog(id);
3021 }
3022
3023 /**
3024 * @deprecated Old no-arguments version of
3025 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
3026 */
3027 @Deprecated
3028 protected void onPrepareDialog(int id, Dialog dialog) {
3029 dialog.setOwnerActivity(this);
3030 }
3031
3032 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003034 * shown. The default implementation calls through to
3035 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
3036 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 * <p>
3038 * Override this if you need to update a managed dialog based on the state
3039 * of the application each time it is shown. For example, a time picker
3040 * dialog might want to be updated with the current time. You should call
3041 * through to the superclass's implementation. The default implementation
3042 * will set this Activity as the owner activity on the Dialog.
3043 *
3044 * @param id The id of the managed dialog.
3045 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003046 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3047 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 * @see #showDialog(int)
3049 * @see #dismissDialog(int)
3050 * @see #removeDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003051 *
3052 * @deprecated Use the new {@link DialogFragment} class with
3053 * {@link FragmentManager} instead; this is also
3054 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07003056 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003057 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
3058 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 }
3060
3061 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003062 * Simple version of {@link #showDialog(int, Bundle)} that does not
3063 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
3064 * with null arguments.
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003065 *
3066 * @deprecated Use the new {@link DialogFragment} class with
3067 * {@link FragmentManager} instead; this is also
3068 * available on older platforms through the Android compatibility package.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003069 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07003070 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003071 public final void showDialog(int id) {
3072 showDialog(id, null);
3073 }
3074
3075 /**
3076 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 * will be made with the same id the first time this is called for a given
3078 * id. From thereafter, the dialog will be automatically saved and restored.
3079 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07003080 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3081 * or later, consider instead using a {@link DialogFragment} instead.</em>
3082 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003083 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 * be made to provide an opportunity to do any timely preparation.
3085 *
3086 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003087 * @param args Arguments to pass through to the dialog. These will be saved
3088 * and restored for you. Note that if the dialog is already created,
3089 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
3090 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08003091 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003092 * @return Returns true if the Dialog was created; false is returned if
3093 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
3094 *
Joe Onorato37296dc2009-07-31 17:58:55 -07003095 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003096 * @see #onCreateDialog(int, Bundle)
3097 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 * @see #dismissDialog(int)
3099 * @see #removeDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003100 *
3101 * @deprecated Use the new {@link DialogFragment} class with
3102 * {@link FragmentManager} instead; this is also
3103 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07003105 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003106 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003108 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003110 ManagedDialog md = mManagedDialogs.get(id);
3111 if (md == null) {
3112 md = new ManagedDialog();
3113 md.mDialog = createDialog(id, null, args);
3114 if (md.mDialog == null) {
3115 return false;
3116 }
3117 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 }
3119
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003120 md.mArgs = args;
3121 onPrepareDialog(id, md.mDialog, args);
3122 md.mDialog.show();
3123 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124 }
3125
3126 /**
3127 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
3128 *
3129 * @param id The id of the managed dialog.
3130 *
3131 * @throws IllegalArgumentException if the id was not previously shown via
3132 * {@link #showDialog(int)}.
3133 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003134 * @see #onCreateDialog(int, Bundle)
3135 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 * @see #showDialog(int)
3137 * @see #removeDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003138 *
3139 * @deprecated Use the new {@link DialogFragment} class with
3140 * {@link FragmentManager} instead; this is also
3141 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07003143 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 public final void dismissDialog(int id) {
3145 if (mManagedDialogs == null) {
3146 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003148
3149 final ManagedDialog md = mManagedDialogs.get(id);
3150 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 throw missingDialog(id);
3152 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003153 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 }
3155
3156 /**
3157 * Creates an exception to throw if a user passed in a dialog id that is
3158 * unexpected.
3159 */
3160 private IllegalArgumentException missingDialog(int id) {
3161 return new IllegalArgumentException("no dialog with id " + id + " was ever "
3162 + "shown via Activity#showDialog");
3163 }
3164
3165 /**
3166 * Removes any internal references to a dialog managed by this Activity.
3167 * If the dialog is showing, it will dismiss it as part of the clean up.
3168 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003169 * <p>This can be useful if you know that you will never show a dialog again and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 * want to avoid the overhead of saving and restoring it in the future.
3171 *
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07003172 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
3173 * will not throw an exception if you try to remove an ID that does not
3174 * currently have an associated dialog.</p>
3175 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 * @param id The id of the managed dialog.
3177 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003178 * @see #onCreateDialog(int, Bundle)
3179 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 * @see #showDialog(int)
3181 * @see #dismissDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003182 *
3183 * @deprecated Use the new {@link DialogFragment} class with
3184 * {@link FragmentManager} instead; this is also
3185 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07003187 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 public final void removeDialog(int id) {
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07003189 if (mManagedDialogs != null) {
3190 final ManagedDialog md = mManagedDialogs.get(id);
3191 if (md != null) {
3192 md.mDialog.dismiss();
3193 mManagedDialogs.remove(id);
3194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 }
3197
3198 /**
3199 * This hook is called when the user signals the desire to start a search.
3200 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01003201 * <p>You can use this function as a simple way to launch the search UI, in response to a
3202 * menu item, search button, or other widgets within your activity. Unless overidden,
3203 * calling this function is the same as calling
3204 * {@link #startSearch startSearch(null, false, null, false)}, which launches
3205 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 *
3207 * <p>You can override this function to force global search, e.g. in response to a dedicated
3208 * search key, or to block search entirely (by simply returning false).
3209 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01003210 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
3211 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 *
3213 * @see android.app.SearchManager
3214 */
3215 public boolean onSearchRequested() {
3216 startSearch(null, false, null, false);
3217 return true;
3218 }
3219
3220 /**
3221 * This hook is called to launch the search UI.
3222 *
3223 * <p>It is typically called from onSearchRequested(), either directly from
3224 * Activity.onSearchRequested() or from an overridden version in any given
3225 * Activity. If your goal is simply to activate search, it is preferred to call
3226 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
3227 * is to inject specific data such as context data, it is preferred to <i>override</i>
3228 * onSearchRequested(), so that any callers to it will benefit from the override.
3229 *
3230 * @param initialQuery Any non-null non-empty string will be inserted as
3231 * pre-entered text in the search query box.
3232 * @param selectInitialQuery If true, the intial query will be preselected, which means that
3233 * any further typing will replace it. This is useful for cases where an entire pre-formed
3234 * query is being inserted. If false, the selection point will be placed at the end of the
3235 * inserted query. This is useful when the inserted query is text that the user entered,
3236 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
3237 * if initialQuery is a non-empty string.</i>
3238 * @param appSearchData An application can insert application-specific
3239 * context here, in order to improve quality or specificity of its own
3240 * searches. This data will be returned with SEARCH intent(s). Null if
3241 * no extra data is required.
3242 * @param globalSearch If false, this will only launch the search that has been specifically
3243 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07003244 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 * If true, this will always launch a platform-global (e.g. web-based) search instead.
3246 *
3247 * @see android.app.SearchManager
3248 * @see #onSearchRequested
3249 */
3250 public void startSearch(String initialQuery, boolean selectInitialQuery,
3251 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003252 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003253 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 appSearchData, globalSearch);
3255 }
3256
3257 /**
krosaend2d60142009-08-17 08:56:48 -07003258 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
3259 * the search dialog. Made available for testing purposes.
3260 *
3261 * @param query The query to trigger. If empty, the request will be ignored.
3262 * @param appSearchData An application can insert application-specific
3263 * context here, in order to improve quality or specificity of its own
3264 * searches. This data will be returned with SEARCH intent(s). Null if
3265 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07003266 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01003267 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07003268 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01003269 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07003270 }
3271
3272 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 * Request that key events come to this activity. Use this if your
3274 * activity has no views with focus, but the activity still wants
3275 * a chance to process key events.
3276 *
3277 * @see android.view.Window#takeKeyEvents
3278 */
3279 public void takeKeyEvents(boolean get) {
3280 getWindow().takeKeyEvents(get);
3281 }
3282
3283 /**
3284 * Enable extended window features. This is a convenience for calling
3285 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
3286 *
3287 * @param featureId The desired feature as defined in
3288 * {@link android.view.Window}.
3289 * @return Returns true if the requested feature is supported and now
3290 * enabled.
3291 *
3292 * @see android.view.Window#requestFeature
3293 */
3294 public final boolean requestWindowFeature(int featureId) {
3295 return getWindow().requestFeature(featureId);
3296 }
3297
3298 /**
3299 * Convenience for calling
3300 * {@link android.view.Window#setFeatureDrawableResource}.
3301 */
3302 public final void setFeatureDrawableResource(int featureId, int resId) {
3303 getWindow().setFeatureDrawableResource(featureId, resId);
3304 }
3305
3306 /**
3307 * Convenience for calling
3308 * {@link android.view.Window#setFeatureDrawableUri}.
3309 */
3310 public final void setFeatureDrawableUri(int featureId, Uri uri) {
3311 getWindow().setFeatureDrawableUri(featureId, uri);
3312 }
3313
3314 /**
3315 * Convenience for calling
3316 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
3317 */
3318 public final void setFeatureDrawable(int featureId, Drawable drawable) {
3319 getWindow().setFeatureDrawable(featureId, drawable);
3320 }
3321
3322 /**
3323 * Convenience for calling
3324 * {@link android.view.Window#setFeatureDrawableAlpha}.
3325 */
3326 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
3327 getWindow().setFeatureDrawableAlpha(featureId, alpha);
3328 }
3329
3330 /**
3331 * Convenience for calling
3332 * {@link android.view.Window#getLayoutInflater}.
3333 */
3334 public LayoutInflater getLayoutInflater() {
3335 return getWindow().getLayoutInflater();
3336 }
3337
3338 /**
3339 * Returns a {@link MenuInflater} with this context.
3340 */
3341 public MenuInflater getMenuInflater() {
Adam Powell88ab6972011-07-28 11:25:01 -07003342 // Make sure that action views can get an appropriate theme.
3343 if (mMenuInflater == null) {
3344 initActionBar();
3345 if (mActionBar != null) {
Dianne Hackborn92751972012-05-18 19:22:14 -07003346 mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this);
Adam Powell88ab6972011-07-28 11:25:01 -07003347 } else {
3348 mMenuInflater = new MenuInflater(this);
3349 }
3350 }
3351 return mMenuInflater;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 }
3353
3354 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003355 protected void onApplyThemeResource(Resources.Theme theme, int resid,
3356 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 if (mParent == null) {
3358 super.onApplyThemeResource(theme, resid, first);
3359 } else {
3360 try {
3361 theme.setTo(mParent.getTheme());
3362 } catch (Exception e) {
3363 // Empty
3364 }
3365 theme.applyStyle(resid, false);
3366 }
3367 }
3368
3369 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003370 * Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
3371 * with no options.
3372 *
3373 * @param intent The intent to start.
3374 * @param requestCode If >= 0, this code will be returned in
3375 * onActivityResult() when the activity exits.
3376 *
3377 * @throws android.content.ActivityNotFoundException
3378 *
3379 * @see #startActivity
3380 */
3381 public void startActivityForResult(Intent intent, int requestCode) {
3382 startActivityForResult(intent, requestCode, null);
3383 }
3384
3385 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 * Launch an activity for which you would like a result when it finished.
3387 * When this activity exits, your
3388 * onActivityResult() method will be called with the given requestCode.
3389 * Using a negative requestCode is the same as calling
3390 * {@link #startActivity} (the activity is not launched as a sub-activity).
Dianne Hackborna4972e92012-03-14 10:38:05 -07003391 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 * <p>Note that this method should only be used with Intent protocols
3393 * that are defined to return a result. In other protocols (such as
3394 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3395 * not get the result when you expect. For example, if the activity you
3396 * are launching uses the singleTask launch mode, it will not run in your
3397 * task and thus you will immediately receive a cancel result.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003398 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 * <p>As a special case, if you call startActivityForResult() with a requestCode
3400 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3401 * activity, then your window will not be displayed until a result is
3402 * returned back from the started activity. This is to avoid visible
3403 * flickering when redirecting to another activity.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003404 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 * <p>This method throws {@link android.content.ActivityNotFoundException}
3406 * if there was no Activity found to run the given Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003407 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 * @param intent The intent to start.
3409 * @param requestCode If >= 0, this code will be returned in
3410 * onActivityResult() when the activity exits.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003411 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003412 * See {@link android.content.Context#startActivity(Intent, Bundle)
3413 * Context.startActivity(Intent, Bundle)} for more details.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003414 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 * @throws android.content.ActivityNotFoundException
Dianne Hackborna4972e92012-03-14 10:38:05 -07003416 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 * @see #startActivity
3418 */
Dianne Hackborna4972e92012-03-14 10:38:05 -07003419 public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 if (mParent == null) {
3421 Instrumentation.ActivityResult ar =
3422 mInstrumentation.execStartActivity(
3423 this, mMainThread.getApplicationThread(), mToken, this,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003424 intent, requestCode, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 if (ar != null) {
3426 mMainThread.sendActivityResult(
3427 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3428 ar.getResultData());
3429 }
3430 if (requestCode >= 0) {
3431 // If this start is requesting a result, we can avoid making
3432 // the activity visible until the result is received. Setting
3433 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3434 // activity hidden during this time, to avoid flickering.
3435 // This can only be done when a result is requested because
3436 // that guarantees we will get information back when the
3437 // activity is finished, no matter what happens to it.
3438 mStartedActivity = true;
3439 }
Adam Powell14874662013-07-18 19:42:41 -07003440
3441 final View decor = mWindow != null ? mWindow.peekDecorView() : null;
3442 if (decor != null) {
3443 decor.cancelPendingInputEvents();
3444 }
3445 // TODO Consider clearing/flushing other event sources and events for child windows.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 } else {
Dianne Hackborna4972e92012-03-14 10:38:05 -07003447 if (options != null) {
3448 mParent.startActivityFromChild(this, intent, requestCode, options);
3449 } else {
3450 // Note we want to go through this method for compatibility with
3451 // existing applications that may have overridden it.
3452 mParent.startActivityFromChild(this, intent, requestCode);
3453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 }
3455 }
3456
3457 /**
Dianne Hackbornf1c26e22012-08-23 13:54:58 -07003458 * @hide Implement to provide correct calling token.
3459 */
3460 public void startActivityAsUser(Intent intent, UserHandle user) {
3461 startActivityAsUser(intent, null, user);
3462 }
3463
3464 /**
3465 * @hide Implement to provide correct calling token.
3466 */
3467 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
3468 if (mParent != null) {
3469 throw new RuntimeException("Called be called from a child");
3470 }
3471 Instrumentation.ActivityResult ar =
3472 mInstrumentation.execStartActivity(
3473 this, mMainThread.getApplicationThread(), mToken, this,
3474 intent, -1, options, user);
3475 if (ar != null) {
3476 mMainThread.sendActivityResult(
3477 mToken, mEmbeddedID, -1, ar.getResultCode(),
3478 ar.getResultData());
3479 }
3480 }
3481
3482 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003483 * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
3484 * Intent, int, int, int, Bundle)} with no options.
3485 *
3486 * @param intent The IntentSender to launch.
3487 * @param requestCode If >= 0, this code will be returned in
3488 * onActivityResult() when the activity exits.
3489 * @param fillInIntent If non-null, this will be provided as the
3490 * intent parameter to {@link IntentSender#sendIntent}.
3491 * @param flagsMask Intent flags in the original IntentSender that you
3492 * would like to change.
3493 * @param flagsValues Desired values for any bits set in
3494 * <var>flagsMask</var>
3495 * @param extraFlags Always set to 0.
3496 */
3497 public void startIntentSenderForResult(IntentSender intent, int requestCode,
3498 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3499 throws IntentSender.SendIntentException {
3500 startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
3501 flagsValues, extraFlags, null);
3502 }
3503
3504 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003505 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003506 * to use a IntentSender to describe the activity to be started. If
3507 * the IntentSender is for an activity, that activity will be started
3508 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
3509 * here; otherwise, its associated action will be executed (such as
3510 * sending a broadcast) as if you had called
3511 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003512 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003513 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003514 * @param requestCode If >= 0, this code will be returned in
3515 * onActivityResult() when the activity exits.
3516 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003517 * intent parameter to {@link IntentSender#sendIntent}.
3518 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003519 * would like to change.
3520 * @param flagsValues Desired values for any bits set in
3521 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003522 * @param extraFlags Always set to 0.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003523 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003524 * See {@link android.content.Context#startActivity(Intent, Bundle)
3525 * Context.startActivity(Intent, Bundle)} for more details. If options
3526 * have also been supplied by the IntentSender, options given here will
3527 * override any that conflict with those given by the IntentSender.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003528 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003529 public void startIntentSenderForResult(IntentSender intent, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003530 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
3531 Bundle options) throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003532 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003533 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003534 flagsMask, flagsValues, this, options);
3535 } else if (options != null) {
3536 mParent.startIntentSenderFromChild(this, intent, requestCode,
3537 fillInIntent, flagsMask, flagsValues, extraFlags, options);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003538 } else {
Dianne Hackborna4972e92012-03-14 10:38:05 -07003539 // Note we want to go through this call for compatibility with
3540 // existing applications that may have overridden the method.
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003541 mParent.startIntentSenderFromChild(this, intent, requestCode,
3542 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003543 }
3544 }
3545
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003546 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003547 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity,
3548 Bundle options)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003549 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003550 try {
3551 String resolvedType = null;
3552 if (fillInIntent != null) {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07003553 fillInIntent.migrateExtraStreamToClipData();
3554 fillInIntent.prepareToLeaveProcess();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003555 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
3556 }
3557 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003558 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003559 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003560 requestCode, flagsMask, flagsValues, options);
3561 if (result == ActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003562 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003563 }
3564 Instrumentation.checkStartActivityResult(result, null);
3565 } catch (RemoteException e) {
3566 }
3567 if (requestCode >= 0) {
3568 // If this start is requesting a result, we can avoid making
3569 // the activity visible until the result is received. Setting
3570 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3571 // activity hidden during this time, to avoid flickering.
3572 // This can only be done when a result is requested because
3573 // that guarantees we will get information back when the
3574 // activity is finished, no matter what happens to it.
3575 mStartedActivity = true;
3576 }
3577 }
3578
3579 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003580 * Same as {@link #startActivity(Intent, Bundle)} with no options
3581 * specified.
3582 *
3583 * @param intent The intent to start.
3584 *
3585 * @throws android.content.ActivityNotFoundException
3586 *
3587 * @see {@link #startActivity(Intent, Bundle)}
3588 * @see #startActivityForResult
3589 */
3590 @Override
3591 public void startActivity(Intent intent) {
3592 startActivity(intent, null);
3593 }
3594
3595 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 * Launch a new activity. You will not receive any information about when
3597 * the activity exits. This implementation overrides the base version,
3598 * providing information about
3599 * the activity performing the launch. Because of this additional
3600 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3601 * required; if not specified, the new activity will be added to the
3602 * task of the caller.
3603 *
3604 * <p>This method throws {@link android.content.ActivityNotFoundException}
3605 * if there was no Activity found to run the given Intent.
3606 *
3607 * @param intent The intent to start.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003608 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003609 * See {@link android.content.Context#startActivity(Intent, Bundle)
3610 * Context.startActivity(Intent, Bundle)} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 *
3612 * @throws android.content.ActivityNotFoundException
Dianne Hackborna4972e92012-03-14 10:38:05 -07003613 *
3614 * @see {@link #startActivity(Intent)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 * @see #startActivityForResult
3616 */
3617 @Override
Dianne Hackborna4972e92012-03-14 10:38:05 -07003618 public void startActivity(Intent intent, Bundle options) {
3619 if (options != null) {
3620 startActivityForResult(intent, -1, options);
3621 } else {
3622 // Note we want to go through this call for compatibility with
3623 // applications that may have overridden the method.
3624 startActivityForResult(intent, -1);
3625 }
3626 }
3627
3628 /**
3629 * Same as {@link #startActivities(Intent[], Bundle)} with no options
3630 * specified.
3631 *
3632 * @param intents The intents to start.
3633 *
3634 * @throws android.content.ActivityNotFoundException
3635 *
3636 * @see {@link #startActivities(Intent[], Bundle)}
3637 * @see #startActivityForResult
3638 */
3639 @Override
3640 public void startActivities(Intent[] intents) {
3641 startActivities(intents, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 }
3643
3644 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003645 * Launch a new activity. You will not receive any information about when
3646 * the activity exits. This implementation overrides the base version,
3647 * providing information about
3648 * the activity performing the launch. Because of this additional
3649 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3650 * required; if not specified, the new activity will be added to the
3651 * task of the caller.
3652 *
3653 * <p>This method throws {@link android.content.ActivityNotFoundException}
3654 * if there was no Activity found to run the given Intent.
3655 *
3656 * @param intents The intents to start.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003657 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003658 * See {@link android.content.Context#startActivity(Intent, Bundle)
3659 * Context.startActivity(Intent, Bundle)} for more details.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003660 *
3661 * @throws android.content.ActivityNotFoundException
3662 *
Dianne Hackborna4972e92012-03-14 10:38:05 -07003663 * @see {@link #startActivities(Intent[])}
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003664 * @see #startActivityForResult
3665 */
3666 @Override
Dianne Hackborna4972e92012-03-14 10:38:05 -07003667 public void startActivities(Intent[] intents, Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003668 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
Dianne Hackborna4972e92012-03-14 10:38:05 -07003669 mToken, this, intents, options);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003670 }
3671
3672 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003673 * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
3674 * with no options.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003675 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003676 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003677 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003678 * intent parameter to {@link IntentSender#sendIntent}.
3679 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003680 * would like to change.
3681 * @param flagsValues Desired values for any bits set in
3682 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003683 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003684 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003685 public void startIntentSender(IntentSender intent,
3686 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3687 throws IntentSender.SendIntentException {
Dianne Hackborna4972e92012-03-14 10:38:05 -07003688 startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
3689 extraFlags, null);
3690 }
3691
3692 /**
3693 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
3694 * to start; see
3695 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
3696 * for more information.
3697 *
3698 * @param intent The IntentSender to launch.
3699 * @param fillInIntent If non-null, this will be provided as the
3700 * intent parameter to {@link IntentSender#sendIntent}.
3701 * @param flagsMask Intent flags in the original IntentSender that you
3702 * would like to change.
3703 * @param flagsValues Desired values for any bits set in
3704 * <var>flagsMask</var>
3705 * @param extraFlags Always set to 0.
3706 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003707 * See {@link android.content.Context#startActivity(Intent, Bundle)
3708 * Context.startActivity(Intent, Bundle)} for more details. If options
3709 * have also been supplied by the IntentSender, options given here will
3710 * override any that conflict with those given by the IntentSender.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003711 */
3712 public void startIntentSender(IntentSender intent,
3713 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
3714 Bundle options) throws IntentSender.SendIntentException {
3715 if (options != null) {
3716 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3717 flagsValues, extraFlags, options);
3718 } else {
3719 // Note we want to go through this call for compatibility with
3720 // applications that may have overridden the method.
3721 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3722 flagsValues, extraFlags);
3723 }
3724 }
3725
3726 /**
3727 * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
3728 * with no options.
3729 *
3730 * @param intent The intent to start.
3731 * @param requestCode If >= 0, this code will be returned in
3732 * onActivityResult() when the activity exits, as described in
3733 * {@link #startActivityForResult}.
3734 *
3735 * @return If a new activity was launched then true is returned; otherwise
3736 * false is returned and you must handle the Intent yourself.
3737 *
3738 * @see #startActivity
3739 * @see #startActivityForResult
3740 */
3741 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
3742 return startActivityIfNeeded(intent, requestCode, null);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003743 }
3744
3745 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 * A special variation to launch an activity only if a new activity
3747 * instance is needed to handle the given Intent. In other words, this is
3748 * just like {@link #startActivityForResult(Intent, int)} except: if you are
3749 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
3750 * singleTask or singleTop
3751 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
3752 * and the activity
3753 * that handles <var>intent</var> is the same as your currently running
3754 * activity, then a new instance is not needed. In this case, instead of
3755 * the normal behavior of calling {@link #onNewIntent} this function will
3756 * return and you can handle the Intent yourself.
3757 *
3758 * <p>This function can only be called from a top-level activity; if it is
3759 * called from a child activity, a runtime exception will be thrown.
3760 *
3761 * @param intent The intent to start.
3762 * @param requestCode If >= 0, this code will be returned in
3763 * onActivityResult() when the activity exits, as described in
3764 * {@link #startActivityForResult}.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003765 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003766 * See {@link android.content.Context#startActivity(Intent, Bundle)
3767 * Context.startActivity(Intent, Bundle)} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003768 *
3769 * @return If a new activity was launched then true is returned; otherwise
3770 * false is returned and you must handle the Intent yourself.
3771 *
3772 * @see #startActivity
3773 * @see #startActivityForResult
3774 */
Dianne Hackborna4972e92012-03-14 10:38:05 -07003775 public boolean startActivityIfNeeded(Intent intent, int requestCode, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 if (mParent == null) {
Dianne Hackborna4972e92012-03-14 10:38:05 -07003777 int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 try {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07003779 intent.migrateExtraStreamToClipData();
3780 intent.prepareToLeaveProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 result = ActivityManagerNative.getDefault()
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003782 .startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
Siva Velusamy92a8b222012-03-09 16:24:04 -08003783 intent, intent.resolveTypeIfNeeded(getContentResolver()),
Dianne Hackborna4972e92012-03-14 10:38:05 -07003784 mToken, mEmbeddedID, requestCode,
3785 ActivityManager.START_FLAG_ONLY_IF_NEEDED, null, null,
3786 options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 } catch (RemoteException e) {
3788 // Empty
3789 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 Instrumentation.checkStartActivityResult(result, intent);
Siva Velusamy92a8b222012-03-09 16:24:04 -08003792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 if (requestCode >= 0) {
3794 // If this start is requesting a result, we can avoid making
3795 // the activity visible until the result is received. Setting
3796 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3797 // activity hidden during this time, to avoid flickering.
3798 // This can only be done when a result is requested because
3799 // that guarantees we will get information back when the
3800 // activity is finished, no matter what happens to it.
3801 mStartedActivity = true;
3802 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07003803 return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 }
3805
3806 throw new UnsupportedOperationException(
3807 "startActivityIfNeeded can only be called from a top-level activity");
3808 }
3809
3810 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003811 * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
3812 * no options.
3813 *
3814 * @param intent The intent to dispatch to the next activity. For
3815 * correct behavior, this must be the same as the Intent that started
3816 * your own activity; the only changes you can make are to the extras
3817 * inside of it.
3818 *
3819 * @return Returns a boolean indicating whether there was another Activity
3820 * to start: true if there was a next activity to start, false if there
3821 * wasn't. In general, if true is returned you will then want to call
3822 * finish() on yourself.
3823 */
3824 public boolean startNextMatchingActivity(Intent intent) {
3825 return startNextMatchingActivity(intent, null);
3826 }
3827
3828 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 * Special version of starting an activity, for use when you are replacing
3830 * other activity components. You can use this to hand the Intent off
3831 * to the next Activity that can handle it. You typically call this in
3832 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3833 *
3834 * @param intent The intent to dispatch to the next activity. For
3835 * correct behavior, this must be the same as the Intent that started
3836 * your own activity; the only changes you can make are to the extras
3837 * inside of it.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003838 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003839 * See {@link android.content.Context#startActivity(Intent, Bundle)
3840 * Context.startActivity(Intent, Bundle)} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003841 *
3842 * @return Returns a boolean indicating whether there was another Activity
3843 * to start: true if there was a next activity to start, false if there
3844 * wasn't. In general, if true is returned you will then want to call
3845 * finish() on yourself.
3846 */
Dianne Hackborna4972e92012-03-14 10:38:05 -07003847 public boolean startNextMatchingActivity(Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003848 if (mParent == null) {
3849 try {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07003850 intent.migrateExtraStreamToClipData();
3851 intent.prepareToLeaveProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 return ActivityManagerNative.getDefault()
Dianne Hackborna4972e92012-03-14 10:38:05 -07003853 .startNextMatchingActivity(mToken, intent, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 } catch (RemoteException e) {
3855 // Empty
3856 }
3857 return false;
3858 }
3859
3860 throw new UnsupportedOperationException(
3861 "startNextMatchingActivity can only be called from a top-level activity");
3862 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07003863
3864 /**
3865 * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
3866 * with no options.
3867 *
3868 * @param child The activity making the call.
3869 * @param intent The intent to start.
3870 * @param requestCode Reply request code. < 0 if reply is not requested.
3871 *
3872 * @throws android.content.ActivityNotFoundException
3873 *
3874 * @see #startActivity
3875 * @see #startActivityForResult
3876 */
3877 public void startActivityFromChild(Activity child, Intent intent,
3878 int requestCode) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003879 startActivityFromChild(child, intent, requestCode, null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003880 }
3881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 /**
3883 * This is called when a child activity of this one calls its
3884 * {@link #startActivity} or {@link #startActivityForResult} method.
3885 *
3886 * <p>This method throws {@link android.content.ActivityNotFoundException}
3887 * if there was no Activity found to run the given Intent.
3888 *
3889 * @param child The activity making the call.
3890 * @param intent The intent to start.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003891 * @param requestCode Reply request code. < 0 if reply is not requested.
3892 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003893 * See {@link android.content.Context#startActivity(Intent, Bundle)
3894 * Context.startActivity(Intent, Bundle)} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 *
3896 * @throws android.content.ActivityNotFoundException
3897 *
3898 * @see #startActivity
3899 * @see #startActivityForResult
3900 */
3901 public void startActivityFromChild(Activity child, Intent intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003902 int requestCode, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 Instrumentation.ActivityResult ar =
3904 mInstrumentation.execStartActivity(
3905 this, mMainThread.getApplicationThread(), mToken, child,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003906 intent, requestCode, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 if (ar != null) {
3908 mMainThread.sendActivityResult(
3909 mToken, child.mEmbeddedID, requestCode,
3910 ar.getResultCode(), ar.getResultData());
3911 }
3912 }
3913
3914 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003915 * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
3916 * with no options.
3917 *
3918 * @param fragment The fragment making the call.
3919 * @param intent The intent to start.
3920 * @param requestCode Reply request code. < 0 if reply is not requested.
3921 *
3922 * @throws android.content.ActivityNotFoundException
3923 *
3924 * @see Fragment#startActivity
3925 * @see Fragment#startActivityForResult
3926 */
3927 public void startActivityFromFragment(Fragment fragment, Intent intent,
3928 int requestCode) {
3929 startActivityFromFragment(fragment, intent, requestCode, null);
3930 }
3931
3932 /**
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003933 * This is called when a Fragment in this activity calls its
3934 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
3935 * method.
3936 *
3937 * <p>This method throws {@link android.content.ActivityNotFoundException}
3938 * if there was no Activity found to run the given Intent.
3939 *
3940 * @param fragment The fragment making the call.
3941 * @param intent The intent to start.
3942 * @param requestCode Reply request code. < 0 if reply is not requested.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003943 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003944 * See {@link android.content.Context#startActivity(Intent, Bundle)
3945 * Context.startActivity(Intent, Bundle)} for more details.
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003946 *
3947 * @throws android.content.ActivityNotFoundException
3948 *
3949 * @see Fragment#startActivity
3950 * @see Fragment#startActivityForResult
3951 */
3952 public void startActivityFromFragment(Fragment fragment, Intent intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003953 int requestCode, Bundle options) {
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003954 Instrumentation.ActivityResult ar =
3955 mInstrumentation.execStartActivity(
3956 this, mMainThread.getApplicationThread(), mToken, fragment,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003957 intent, requestCode, options);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003958 if (ar != null) {
3959 mMainThread.sendActivityResult(
3960 mToken, fragment.mWho, requestCode,
3961 ar.getResultCode(), ar.getResultData());
3962 }
3963 }
3964
3965 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003966 * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
3967 * int, Intent, int, int, int, Bundle)} with no options.
3968 */
3969 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3970 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3971 int extraFlags)
3972 throws IntentSender.SendIntentException {
3973 startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
3974 flagsMask, flagsValues, extraFlags, null);
3975 }
3976
3977 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003978 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003979 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003980 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003981 * for more information.
3982 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003983 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3984 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003985 int extraFlags, Bundle options)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003986 throws IntentSender.SendIntentException {
3987 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003988 flagsMask, flagsValues, child, options);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003989 }
3990
3991 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003992 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3993 * or {@link #finish} to specify an explicit transition animation to
3994 * perform next.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003995 *
3996 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
3997 * to using this with starting activities is to supply the desired animation
3998 * information through a {@link ActivityOptions} bundle to
3999 * {@link #startActivity(Intent, Bundle) or a related function. This allows
4000 * you to specify a custom animation even when starting an activity from
4001 * outside the context of the current top activity.
4002 *
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07004003 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07004004 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07004005 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07004006 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07004007 */
4008 public void overridePendingTransition(int enterAnim, int exitAnim) {
4009 try {
4010 ActivityManagerNative.getDefault().overridePendingTransition(
4011 mToken, getPackageName(), enterAnim, exitAnim);
4012 } catch (RemoteException e) {
4013 }
4014 }
4015
4016 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 * Call this to set the result that your activity will return to its
4018 * caller.
4019 *
4020 * @param resultCode The result code to propagate back to the originating
4021 * activity, often RESULT_CANCELED or RESULT_OK
4022 *
4023 * @see #RESULT_CANCELED
4024 * @see #RESULT_OK
4025 * @see #RESULT_FIRST_USER
4026 * @see #setResult(int, Intent)
4027 */
4028 public final void setResult(int resultCode) {
4029 synchronized (this) {
4030 mResultCode = resultCode;
4031 mResultData = null;
4032 }
4033 }
4034
4035 /**
4036 * Call this to set the result that your activity will return to its
4037 * caller.
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004038 *
4039 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
4040 * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
4041 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4042 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the
4043 * Activity receiving the result access to the specific URIs in the Intent.
4044 * Access will remain until the Activity has finished (it will remain across the hosting
4045 * process being killed and other temporary destruction) and will be added
4046 * to any existing set of URI permissions it already holds.
4047 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 * @param resultCode The result code to propagate back to the originating
4049 * activity, often RESULT_CANCELED or RESULT_OK
4050 * @param data The data to propagate back to the originating activity.
4051 *
4052 * @see #RESULT_CANCELED
4053 * @see #RESULT_OK
4054 * @see #RESULT_FIRST_USER
4055 * @see #setResult(int)
4056 */
4057 public final void setResult(int resultCode, Intent data) {
4058 synchronized (this) {
4059 mResultCode = resultCode;
4060 mResultData = data;
4061 }
4062 }
4063
4064 /**
4065 * Return the name of the package that invoked this activity. This is who
4066 * the data in {@link #setResult setResult()} will be sent to. You can
4067 * use this information to validate that the recipient is allowed to
4068 * receive the data.
4069 *
Dianne Hackborn7b924672013-04-11 18:08:42 -07004070 * <p class="note">Note: if the calling activity is not expecting a result (that is it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 * did not use the {@link #startActivityForResult}
4072 * form that includes a request code), then the calling package will be
Dianne Hackborn7b924672013-04-11 18:08:42 -07004073 * null.</p>
4074 *
4075 * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
4076 * the result from this method was unstable. If the process hosting the calling
4077 * package was no longer running, it would return null instead of the proper package
4078 * name. You can use {@link #getCallingActivity()} and retrieve the package name
4079 * from that instead.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 *
4081 * @return The package of the activity that will receive your
4082 * reply, or null if none.
4083 */
4084 public String getCallingPackage() {
4085 try {
4086 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
4087 } catch (RemoteException e) {
4088 return null;
4089 }
4090 }
4091
4092 /**
4093 * Return the name of the activity that invoked this activity. This is
4094 * who the data in {@link #setResult setResult()} will be sent to. You
4095 * can use this information to validate that the recipient is allowed to
4096 * receive the data.
4097 *
Dianne Hackborn7b924672013-04-11 18:08:42 -07004098 * <p class="note">Note: if the calling activity is not expecting a result (that is it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 * did not use the {@link #startActivityForResult}
4100 * form that includes a request code), then the calling package will be
4101 * null.
4102 *
Dianne Hackborn7b924672013-04-11 18:08:42 -07004103 * @return The ComponentName of the activity that will receive your
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 * reply, or null if none.
4105 */
4106 public ComponentName getCallingActivity() {
4107 try {
4108 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
4109 } catch (RemoteException e) {
4110 return null;
4111 }
4112 }
4113
4114 /**
4115 * Control whether this activity's main window is visible. This is intended
4116 * only for the special case of an activity that is not going to show a
4117 * UI itself, but can't just finish prior to onResume() because it needs
4118 * to wait for a service binding or such. Setting this to false allows
4119 * you to prevent your UI from being shown during that time.
4120 *
4121 * <p>The default value for this is taken from the
4122 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
4123 */
4124 public void setVisible(boolean visible) {
4125 if (mVisibleFromClient != visible) {
4126 mVisibleFromClient = visible;
4127 if (mVisibleFromServer) {
4128 if (visible) makeVisible();
4129 else mDecor.setVisibility(View.INVISIBLE);
4130 }
4131 }
4132 }
4133
4134 void makeVisible() {
4135 if (!mWindowAdded) {
4136 ViewManager wm = getWindowManager();
4137 wm.addView(mDecor, getWindow().getAttributes());
4138 mWindowAdded = true;
4139 }
4140 mDecor.setVisibility(View.VISIBLE);
4141 }
4142
4143 /**
4144 * Check to see whether this activity is in the process of finishing,
4145 * either because you called {@link #finish} on it or someone else
4146 * has requested that it finished. This is often used in
4147 * {@link #onPause} to determine whether the activity is simply pausing or
4148 * completely finishing.
4149 *
4150 * @return If the activity is finishing, returns true; else returns false.
4151 *
4152 * @see #finish
4153 */
4154 public boolean isFinishing() {
4155 return mFinished;
4156 }
4157
4158 /**
Dianne Hackborn6d9dcbc2012-10-02 17:51:13 -07004159 * Returns true if the final {@link #onDestroy()} call has been made
4160 * on the Activity, so this instance is now dead.
4161 */
4162 public boolean isDestroyed() {
4163 return mDestroyed;
4164 }
4165
4166 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05004167 * Check to see whether this activity is in the process of being destroyed in order to be
4168 * recreated with a new configuration. This is often used in
4169 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
4170 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
4171 *
4172 * @return If the activity is being torn down in order to be recreated with a new configuration,
4173 * returns true; else returns false.
4174 */
4175 public boolean isChangingConfigurations() {
4176 return mChangingConfigurations;
4177 }
4178
4179 /**
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004180 * Cause this Activity to be recreated with a new instance. This results
4181 * in essentially the same flow as when the Activity is created due to
4182 * a configuration change -- the current instance will go through its
4183 * lifecycle to {@link #onDestroy} and a new instance then created after it.
4184 */
4185 public void recreate() {
4186 if (mParent != null) {
4187 throw new IllegalStateException("Can only be called on top-level activity");
4188 }
4189 if (Looper.myLooper() != mMainThread.getLooper()) {
4190 throw new IllegalStateException("Must be called from main thread");
4191 }
4192 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, false);
4193 }
4194
4195 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 * Call this when your activity is done and should be closed. The
4197 * ActivityResult is propagated back to whoever launched you via
4198 * onActivityResult().
4199 */
4200 public void finish() {
4201 if (mParent == null) {
4202 int resultCode;
4203 Intent resultData;
4204 synchronized (this) {
4205 resultCode = mResultCode;
4206 resultData = mResultData;
4207 }
Joe Onorato43a17652011-04-06 19:22:23 -07004208 if (false) Log.v(TAG, "Finishing self: token=" + mToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 try {
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04004210 if (resultData != null) {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07004211 resultData.prepareToLeaveProcess();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04004212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 if (ActivityManagerNative.getDefault()
4214 .finishActivity(mToken, resultCode, resultData)) {
4215 mFinished = true;
4216 }
4217 } catch (RemoteException e) {
4218 // Empty
4219 }
4220 } else {
4221 mParent.finishFromChild(this);
4222 }
4223 }
4224
4225 /**
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07004226 * Finish this activity as well as all activities immediately below it
4227 * in the current task that have the same affinity. This is typically
4228 * used when an application can be launched on to another task (such as
4229 * from an ACTION_VIEW of a content type it understands) and the user
4230 * has used the up navigation to switch out of the current task and in
4231 * to its own task. In this case, if the user has navigated down into
4232 * any other activities of the second application, all of those should
4233 * be removed from the original task as part of the task switch.
4234 *
4235 * <p>Note that this finish does <em>not</em> allow you to deliver results
4236 * to the previous activity, and an exception will be thrown if you are trying
4237 * to do so.</p>
4238 */
4239 public void finishAffinity() {
4240 if (mParent != null) {
4241 throw new IllegalStateException("Can not be called from an embedded activity");
4242 }
4243 if (mResultCode != RESULT_CANCELED || mResultData != null) {
4244 throw new IllegalStateException("Can not be called to deliver a result");
4245 }
4246 try {
4247 if (ActivityManagerNative.getDefault().finishActivityAffinity(mToken)) {
4248 mFinished = true;
4249 }
4250 } catch (RemoteException e) {
4251 // Empty
4252 }
4253 }
4254
4255 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004256 * This is called when a child activity of this one calls its
4257 * {@link #finish} method. The default implementation simply calls
4258 * finish() on this activity (the parent), finishing the entire group.
4259 *
4260 * @param child The activity making the call.
4261 *
4262 * @see #finish
4263 */
4264 public void finishFromChild(Activity child) {
4265 finish();
4266 }
4267
4268 /**
4269 * Force finish another activity that you had previously started with
4270 * {@link #startActivityForResult}.
4271 *
4272 * @param requestCode The request code of the activity that you had
4273 * given to startActivityForResult(). If there are multiple
4274 * activities started with this request code, they
4275 * will all be finished.
4276 */
4277 public void finishActivity(int requestCode) {
4278 if (mParent == null) {
4279 try {
4280 ActivityManagerNative.getDefault()
4281 .finishSubActivity(mToken, mEmbeddedID, requestCode);
4282 } catch (RemoteException e) {
4283 // Empty
4284 }
4285 } else {
4286 mParent.finishActivityFromChild(this, requestCode);
4287 }
4288 }
4289
4290 /**
4291 * This is called when a child activity of this one calls its
4292 * finishActivity().
4293 *
4294 * @param child The activity making the call.
4295 * @param requestCode Request code that had been used to start the
4296 * activity.
4297 */
4298 public void finishActivityFromChild(Activity child, int requestCode) {
4299 try {
4300 ActivityManagerNative.getDefault()
4301 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
4302 } catch (RemoteException e) {
4303 // Empty
4304 }
4305 }
4306
4307 /**
4308 * Called when an activity you launched exits, giving you the requestCode
4309 * you started it with, the resultCode it returned, and any additional
4310 * data from it. The <var>resultCode</var> will be
4311 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
4312 * didn't return any result, or crashed during its operation.
4313 *
4314 * <p>You will receive this call immediately before onResume() when your
4315 * activity is re-starting.
4316 *
4317 * @param requestCode The integer request code originally supplied to
4318 * startActivityForResult(), allowing you to identify who this
4319 * result came from.
4320 * @param resultCode The integer result code returned by the child activity
4321 * through its setResult().
4322 * @param data An Intent, which can return result data to the caller
4323 * (various data can be attached to Intent "extras").
4324 *
4325 * @see #startActivityForResult
4326 * @see #createPendingResult
4327 * @see #setResult(int)
4328 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004329 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 }
4331
4332 /**
4333 * Create a new PendingIntent object which you can hand to others
4334 * for them to use to send result data back to your
4335 * {@link #onActivityResult} callback. The created object will be either
4336 * one-shot (becoming invalid after a result is sent back) or multiple
4337 * (allowing any number of results to be sent through it).
4338 *
4339 * @param requestCode Private request code for the sender that will be
4340 * associated with the result data when it is returned. The sender can not
4341 * modify this value, allowing you to identify incoming results.
4342 * @param data Default data to supply in the result, which may be modified
4343 * by the sender.
4344 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
4345 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
4346 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
4347 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
4348 * or any of the flags as supported by
4349 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
4350 * of the intent that can be supplied when the actual send happens.
4351 *
4352 * @return Returns an existing or new PendingIntent matching the given
4353 * parameters. May return null only if
4354 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
4355 * supplied.
4356 *
4357 * @see PendingIntent
4358 */
4359 public PendingIntent createPendingResult(int requestCode, Intent data,
4360 int flags) {
4361 String packageName = getPackageName();
4362 try {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07004363 data.prepareToLeaveProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 IIntentSender target =
4365 ActivityManagerNative.getDefault().getIntentSender(
Dianne Hackborna4972e92012-03-14 10:38:05 -07004366 ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 mParent == null ? mToken : mParent.mToken,
Dianne Hackborn41203752012-08-31 14:05:51 -07004368 mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null,
4369 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004370 return target != null ? new PendingIntent(target) : null;
4371 } catch (RemoteException e) {
4372 // Empty
4373 }
4374 return null;
4375 }
4376
4377 /**
4378 * Change the desired orientation of this activity. If the activity
4379 * is currently in the foreground or otherwise impacting the screen
4380 * orientation, the screen will immediately be changed (possibly causing
4381 * the activity to be restarted). Otherwise, this will be used the next
4382 * time the activity is visible.
4383 *
4384 * @param requestedOrientation An orientation constant as used in
4385 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
4386 */
4387 public void setRequestedOrientation(int requestedOrientation) {
4388 if (mParent == null) {
4389 try {
4390 ActivityManagerNative.getDefault().setRequestedOrientation(
4391 mToken, requestedOrientation);
4392 } catch (RemoteException e) {
4393 // Empty
4394 }
4395 } else {
4396 mParent.setRequestedOrientation(requestedOrientation);
4397 }
4398 }
4399
4400 /**
4401 * Return the current requested orientation of the activity. This will
4402 * either be the orientation requested in its component's manifest, or
4403 * the last requested orientation given to
4404 * {@link #setRequestedOrientation(int)}.
4405 *
4406 * @return Returns an orientation constant as used in
4407 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
4408 */
4409 public int getRequestedOrientation() {
4410 if (mParent == null) {
4411 try {
4412 return ActivityManagerNative.getDefault()
4413 .getRequestedOrientation(mToken);
4414 } catch (RemoteException e) {
4415 // Empty
4416 }
4417 } else {
4418 return mParent.getRequestedOrientation();
4419 }
4420 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
4421 }
4422
4423 /**
4424 * Return the identifier of the task this activity is in. This identifier
4425 * will remain the same for the lifetime of the activity.
4426 *
4427 * @return Task identifier, an opaque integer.
4428 */
4429 public int getTaskId() {
4430 try {
4431 return ActivityManagerNative.getDefault()
4432 .getTaskForActivity(mToken, false);
4433 } catch (RemoteException e) {
4434 return -1;
4435 }
4436 }
4437
4438 /**
4439 * Return whether this activity is the root of a task. The root is the
4440 * first activity in a task.
4441 *
4442 * @return True if this is the root activity, else false.
4443 */
4444 public boolean isTaskRoot() {
4445 try {
4446 return ActivityManagerNative.getDefault()
4447 .getTaskForActivity(mToken, true) >= 0;
4448 } catch (RemoteException e) {
4449 return false;
4450 }
4451 }
4452
4453 /**
4454 * Move the task containing this activity to the back of the activity
4455 * stack. The activity's order within the task is unchanged.
4456 *
4457 * @param nonRoot If false then this only works if the activity is the root
4458 * of a task; if true it will work for any activity in
4459 * a task.
4460 *
4461 * @return If the task was moved (or it was already at the
4462 * back) true is returned, else false.
4463 */
4464 public boolean moveTaskToBack(boolean nonRoot) {
4465 try {
4466 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
4467 mToken, nonRoot);
4468 } catch (RemoteException e) {
4469 // Empty
4470 }
4471 return false;
4472 }
4473
4474 /**
4475 * Returns class name for this activity with the package prefix removed.
4476 * This is the default name used to read and write settings.
4477 *
4478 * @return The local class name.
4479 */
4480 public String getLocalClassName() {
4481 final String pkg = getPackageName();
4482 final String cls = mComponent.getClassName();
4483 int packageLen = pkg.length();
4484 if (!cls.startsWith(pkg) || cls.length() <= packageLen
4485 || cls.charAt(packageLen) != '.') {
4486 return cls;
4487 }
4488 return cls.substring(packageLen+1);
4489 }
4490
4491 /**
4492 * Returns complete component name of this activity.
4493 *
4494 * @return Returns the complete component name for this activity
4495 */
4496 public ComponentName getComponentName()
4497 {
4498 return mComponent;
4499 }
4500
4501 /**
4502 * Retrieve a {@link SharedPreferences} object for accessing preferences
4503 * that are private to this activity. This simply calls the underlying
4504 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
4505 * class name as the preferences name.
4506 *
4507 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
4508 * operation, {@link #MODE_WORLD_READABLE} and
4509 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
4510 *
4511 * @return Returns the single SharedPreferences instance that can be used
4512 * to retrieve and modify the preference values.
4513 */
4514 public SharedPreferences getPreferences(int mode) {
4515 return getSharedPreferences(getLocalClassName(), mode);
4516 }
4517
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004518 private void ensureSearchManager() {
4519 if (mSearchManager != null) {
4520 return;
4521 }
4522
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08004523 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004524 }
4525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526 @Override
4527 public Object getSystemService(String name) {
4528 if (getBaseContext() == null) {
4529 throw new IllegalStateException(
4530 "System services not available to Activities before onCreate()");
4531 }
4532
4533 if (WINDOW_SERVICE.equals(name)) {
4534 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01004535 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004536 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01004537 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004538 }
4539 return super.getSystemService(name);
4540 }
4541
4542 /**
4543 * Change the title associated with this activity. If this is a
4544 * top-level activity, the title for its window will change. If it
4545 * is an embedded activity, the parent can do whatever it wants
4546 * with it.
4547 */
4548 public void setTitle(CharSequence title) {
4549 mTitle = title;
4550 onTitleChanged(title, mTitleColor);
4551
4552 if (mParent != null) {
4553 mParent.onChildTitleChanged(this, title);
4554 }
4555 }
4556
4557 /**
4558 * Change the title associated with this activity. If this is a
4559 * top-level activity, the title for its window will change. If it
4560 * is an embedded activity, the parent can do whatever it wants
4561 * with it.
4562 */
4563 public void setTitle(int titleId) {
4564 setTitle(getText(titleId));
4565 }
4566
4567 public void setTitleColor(int textColor) {
4568 mTitleColor = textColor;
4569 onTitleChanged(mTitle, textColor);
4570 }
4571
4572 public final CharSequence getTitle() {
4573 return mTitle;
4574 }
4575
4576 public final int getTitleColor() {
4577 return mTitleColor;
4578 }
4579
4580 protected void onTitleChanged(CharSequence title, int color) {
4581 if (mTitleReady) {
4582 final Window win = getWindow();
4583 if (win != null) {
4584 win.setTitle(title);
4585 if (color != 0) {
4586 win.setTitleColor(color);
4587 }
4588 }
4589 }
4590 }
4591
4592 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
4593 }
4594
4595 /**
4596 * Sets the visibility of the progress bar in the title.
4597 * <p>
4598 * In order for the progress bar to be shown, the feature must be requested
4599 * via {@link #requestWindowFeature(int)}.
4600 *
4601 * @param visible Whether to show the progress bars in the title.
4602 */
4603 public final void setProgressBarVisibility(boolean visible) {
4604 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
4605 Window.PROGRESS_VISIBILITY_OFF);
4606 }
4607
4608 /**
4609 * Sets the visibility of the indeterminate progress bar in the title.
4610 * <p>
4611 * In order for the progress bar to be shown, the feature must be requested
4612 * via {@link #requestWindowFeature(int)}.
4613 *
4614 * @param visible Whether to show the progress bars in the title.
4615 */
4616 public final void setProgressBarIndeterminateVisibility(boolean visible) {
4617 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
4618 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
4619 }
4620
4621 /**
4622 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
4623 * is always indeterminate).
4624 * <p>
4625 * In order for the progress bar to be shown, the feature must be requested
4626 * via {@link #requestWindowFeature(int)}.
4627 *
4628 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
4629 */
4630 public final void setProgressBarIndeterminate(boolean indeterminate) {
4631 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4632 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
4633 }
4634
4635 /**
4636 * Sets the progress for the progress bars in the title.
4637 * <p>
4638 * In order for the progress bar to be shown, the feature must be requested
4639 * via {@link #requestWindowFeature(int)}.
4640 *
4641 * @param progress The progress for the progress bar. Valid ranges are from
4642 * 0 to 10000 (both inclusive). If 10000 is given, the progress
4643 * bar will be completely filled and will fade out.
4644 */
4645 public final void setProgress(int progress) {
4646 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
4647 }
4648
4649 /**
4650 * Sets the secondary progress for the progress bar in the title. This
4651 * progress is drawn between the primary progress (set via
4652 * {@link #setProgress(int)} and the background. It can be ideal for media
4653 * scenarios such as showing the buffering progress while the default
4654 * progress shows the play progress.
4655 * <p>
4656 * In order for the progress bar to be shown, the feature must be requested
4657 * via {@link #requestWindowFeature(int)}.
4658 *
4659 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
4660 * 0 to 10000 (both inclusive).
4661 */
4662 public final void setSecondaryProgress(int secondaryProgress) {
4663 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4664 secondaryProgress + Window.PROGRESS_SECONDARY_START);
4665 }
4666
4667 /**
4668 * Suggests an audio stream whose volume should be changed by the hardware
4669 * volume controls.
4670 * <p>
4671 * The suggested audio stream will be tied to the window of this Activity.
4672 * If the Activity is switched, the stream set here is no longer the
4673 * suggested stream. The client does not need to save and restore the old
4674 * suggested stream value in onPause and onResume.
4675 *
4676 * @param streamType The type of the audio stream whose volume should be
4677 * changed by the hardware volume controls. It is not guaranteed that
4678 * the hardware volume controls will always change this stream's
4679 * volume (for example, if a call is in progress, its stream's volume
4680 * may be changed instead). To reset back to the default, use
4681 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
4682 */
4683 public final void setVolumeControlStream(int streamType) {
4684 getWindow().setVolumeControlStream(streamType);
4685 }
4686
4687 /**
4688 * Gets the suggested audio stream whose volume should be changed by the
4689 * harwdare volume controls.
4690 *
4691 * @return The suggested audio stream type whose volume should be changed by
4692 * the hardware volume controls.
4693 * @see #setVolumeControlStream(int)
4694 */
4695 public final int getVolumeControlStream() {
4696 return getWindow().getVolumeControlStream();
4697 }
4698
4699 /**
4700 * Runs the specified action on the UI thread. If the current thread is the UI
4701 * thread, then the action is executed immediately. If the current thread is
4702 * not the UI thread, the action is posted to the event queue of the UI thread.
4703 *
4704 * @param action the action to run on the UI thread
4705 */
4706 public final void runOnUiThread(Runnable action) {
4707 if (Thread.currentThread() != mUiThread) {
4708 mHandler.post(action);
4709 } else {
4710 action.run();
4711 }
4712 }
4713
4714 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004715 * Standard implementation of
4716 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
4717 * inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004718 * This implementation does nothing and is for
4719 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
4720 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
4721 *
4722 * @see android.view.LayoutInflater#createView
4723 * @see android.view.Window#getLayoutInflater
4724 */
4725 public View onCreateView(String name, Context context, AttributeSet attrs) {
4726 return null;
4727 }
4728
4729 /**
4730 * Standard implementation of
4731 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
4732 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004733 * This implementation handles <fragment> tags to embed fragments inside
4734 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 *
4736 * @see android.view.LayoutInflater#createView
4737 * @see android.view.Window#getLayoutInflater
4738 */
Dianne Hackborn625ac272010-09-17 18:29:22 -07004739 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004740 if (!"fragment".equals(name)) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07004741 return onCreateView(name, context, attrs);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004742 }
4743
Dianne Hackborndef15372010-08-15 12:43:52 -07004744 String fname = attrs.getAttributeValue(null, "class");
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004745 TypedArray a =
4746 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment);
Dianne Hackborndef15372010-08-15 12:43:52 -07004747 if (fname == null) {
4748 fname = a.getString(com.android.internal.R.styleable.Fragment_name);
4749 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004750 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, View.NO_ID);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004751 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag);
4752 a.recycle();
4753
Dianne Hackborn625ac272010-09-17 18:29:22 -07004754 int containerId = parent != null ? parent.getId() : 0;
4755 if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004756 throw new IllegalArgumentException(attrs.getPositionDescription()
Dianne Hackborn625ac272010-09-17 18:29:22 -07004757 + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004758 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004759
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004760 // If we restored from a previous state, we may already have
4761 // instantiated this fragment from the state and should use
4762 // that instance instead of making a new one.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004763 Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
4764 if (fragment == null && tag != null) {
4765 fragment = mFragments.findFragmentByTag(tag);
4766 }
4767 if (fragment == null && containerId != View.NO_ID) {
4768 fragment = mFragments.findFragmentById(containerId);
4769 }
4770
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004771 if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
4772 + Integer.toHexString(id) + " fname=" + fname
4773 + " existing=" + fragment);
4774 if (fragment == null) {
4775 fragment = Fragment.instantiate(this, fname);
4776 fragment.mFromLayout = true;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004777 fragment.mFragmentId = id != 0 ? id : containerId;
4778 fragment.mContainerId = containerId;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004779 fragment.mTag = tag;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004780 fragment.mInLayout = true;
Dianne Hackborn3e449ce2010-09-11 20:52:31 -07004781 fragment.mFragmentManager = mFragments;
Dianne Hackborne3a7f622011-03-03 21:48:24 -08004782 fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004783 mFragments.addFragment(fragment, true);
4784
4785 } else if (fragment.mInLayout) {
4786 // A fragment already exists and it is not one we restored from
4787 // previous state.
4788 throw new IllegalArgumentException(attrs.getPositionDescription()
4789 + ": Duplicate id 0x" + Integer.toHexString(id)
4790 + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
4791 + " with another fragment for " + fname);
4792 } else {
4793 // This fragment was retained from a previous instance; get it
4794 // going now.
4795 fragment.mInLayout = true;
Dianne Hackborndef15372010-08-15 12:43:52 -07004796 // If this fragment is newly instantiated (either right now, or
4797 // from last saved state), then give it the attributes to
4798 // initialize itself.
4799 if (!fragment.mRetaining) {
Dianne Hackborne3a7f622011-03-03 21:48:24 -08004800 fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
Dianne Hackborndef15372010-08-15 12:43:52 -07004801 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004802 mFragments.moveToState(fragment);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004803 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004804
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004805 if (fragment.mView == null) {
4806 throw new IllegalStateException("Fragment " + fname
4807 + " did not create a view.");
4808 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004809 if (id != 0) {
4810 fragment.mView.setId(id);
4811 }
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004812 if (fragment.mView.getTag() == null) {
4813 fragment.mView.setTag(tag);
4814 }
4815 return fragment.mView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004816 }
4817
Daniel Sandler69a48172010-06-23 16:29:36 -04004818 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -07004819 * Print the Activity's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07004820 * you run "adb shell dumpsys activity &lt;activity_component_name&gt;".
Dianne Hackborn625ac272010-09-17 18:29:22 -07004821 *
Dianne Hackborn30d71892010-12-11 10:37:55 -08004822 * @param prefix Desired prefix to prepend at each line of output.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004823 * @param fd The raw file descriptor that the dump is being sent to.
4824 * @param writer The PrintWriter to which you should dump your state. This will be
4825 * closed for you after you return.
4826 * @param args additional arguments to the dump request.
4827 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08004828 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
Dianne Hackborn62bea2f2012-09-04 18:48:15 -07004829 dumpInner(prefix, fd, writer, args);
4830 }
4831
4832 void dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
Dianne Hackborn30d71892010-12-11 10:37:55 -08004833 writer.print(prefix); writer.print("Local Activity ");
4834 writer.print(Integer.toHexString(System.identityHashCode(this)));
4835 writer.println(" State:");
4836 String innerPrefix = prefix + " ";
4837 writer.print(innerPrefix); writer.print("mResumed=");
4838 writer.print(mResumed); writer.print(" mStopped=");
4839 writer.print(mStopped); writer.print(" mFinished=");
4840 writer.println(mFinished);
4841 writer.print(innerPrefix); writer.print("mLoadersStarted=");
4842 writer.println(mLoadersStarted);
4843 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
4844 writer.println(mChangingConfigurations);
4845 writer.print(innerPrefix); writer.print("mCurrentConfig=");
4846 writer.println(mCurrentConfig);
4847 if (mLoaderManager != null) {
4848 writer.print(prefix); writer.print("Loader Manager ");
4849 writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
4850 writer.println(":");
4851 mLoaderManager.dump(prefix + " ", fd, writer, args);
4852 }
4853 mFragments.dump(prefix, fd, writer, args);
Dianne Hackborn4702a852012-08-17 15:18:29 -07004854 writer.print(prefix); writer.println("View Hierarchy:");
4855 dumpViewHierarchy(prefix + " ", writer, getWindow().getDecorView());
4856 }
4857
4858 private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
4859 writer.print(prefix);
4860 if (view == null) {
4861 writer.println("null");
4862 return;
4863 }
4864 writer.println(view.toString());
4865 if (!(view instanceof ViewGroup)) {
4866 return;
4867 }
4868 ViewGroup grp = (ViewGroup)view;
4869 final int N = grp.getChildCount();
4870 if (N <= 0) {
4871 return;
4872 }
4873 prefix = prefix + " ";
4874 for (int i=0; i<N; i++) {
4875 dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
4876 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004877 }
4878
4879 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04004880 * Bit indicating that this activity is "immersive" and should not be
4881 * interrupted by notifications if possible.
4882 *
4883 * This value is initially set by the manifest property
4884 * <code>android:immersive</code> but may be changed at runtime by
4885 * {@link #setImmersive}.
4886 *
Christopher Tate73c2aee2012-03-15 16:27:14 -07004887 * @see #setImmersive(boolean)
Daniel Sandler69a48172010-06-23 16:29:36 -04004888 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4889 */
4890 public boolean isImmersive() {
4891 try {
4892 return ActivityManagerNative.getDefault().isImmersive(mToken);
4893 } catch (RemoteException e) {
4894 return false;
4895 }
4896 }
4897
4898 /**
Craig Mautner4addfc52013-06-25 08:05:45 -07004899 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} to a
4900 * fullscreen opaque Activity.
Craig Mautner5eda9b32013-07-02 11:58:16 -07004901 * <p>
Craig Mautner4addfc52013-06-25 08:05:45 -07004902 * Call this whenever the background of a translucent Activity has changed to become opaque.
Craig Mautner5eda9b32013-07-02 11:58:16 -07004903 * Doing so will allow the {@link android.view.Surface} of the Activity behind to be released.
4904 * <p>
Craig Mautner4addfc52013-06-25 08:05:45 -07004905 * This call has no effect on non-translucent activities or on activities with the
4906 * {@link android.R.attr#windowIsFloating} attribute.
Craig Mautner5eda9b32013-07-02 11:58:16 -07004907 *
4908 * @see #convertToTranslucent(TranslucentConversionListener)
4909 * @see TranslucentConversionListener
Chet Haaseabd3d772013-09-11 14:33:05 -07004910 *
4911 * @hide
Craig Mautner4addfc52013-06-25 08:05:45 -07004912 */
Craig Mautner5eda9b32013-07-02 11:58:16 -07004913 public void convertFromTranslucent() {
Craig Mautner4addfc52013-06-25 08:05:45 -07004914 try {
Craig Mautner5eda9b32013-07-02 11:58:16 -07004915 mTranslucentCallback = null;
Craig Mautnerbc57cd12013-08-19 15:47:42 -07004916 if (ActivityManagerNative.getDefault().convertFromTranslucent(mToken)) {
4917 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true);
4918 }
Craig Mautner4addfc52013-06-25 08:05:45 -07004919 } catch (RemoteException e) {
4920 // pass
4921 }
4922 }
4923
4924 /**
Craig Mautner5eda9b32013-07-02 11:58:16 -07004925 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} back from
4926 * opaque to translucent following a call to {@link #convertFromTranslucent()}.
4927 * <p>
4928 * Calling this allows the Activity behind this one to be seen again. Once all such Activities
4929 * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
4930 * be called indicating that it is safe to make this activity translucent again. Until
4931 * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
4932 * behind the frontmost Activity will be indeterminate.
4933 * <p>
4934 * This call has no effect on non-translucent activities or on activities with the
4935 * {@link android.R.attr#windowIsFloating} attribute.
4936 *
4937 * @param callback the method to call when all visible Activities behind this one have been
4938 * drawn and it is safe to make this Activity translucent again.
4939 *
4940 * @see #convertFromTranslucent()
4941 * @see TranslucentConversionListener
Chet Haaseabd3d772013-09-11 14:33:05 -07004942 *
4943 * @hide
Craig Mautner5eda9b32013-07-02 11:58:16 -07004944 */
4945 public void convertToTranslucent(TranslucentConversionListener callback) {
4946 try {
4947 mTranslucentCallback = callback;
Craig Mautnerbc57cd12013-08-19 15:47:42 -07004948 mChangeCanvasToTranslucent =
4949 ActivityManagerNative.getDefault().convertToTranslucent(mToken);
Craig Mautner5eda9b32013-07-02 11:58:16 -07004950 } catch (RemoteException e) {
4951 // pass
4952 }
4953 }
4954
4955 /** @hide */
4956 void onTranslucentConversionComplete(boolean drawComplete) {
4957 if (mTranslucentCallback != null) {
4958 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
4959 mTranslucentCallback = null;
4960 }
Craig Mautnerbc57cd12013-08-19 15:47:42 -07004961 if (mChangeCanvasToTranslucent) {
4962 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
4963 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07004964 }
4965
4966 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04004967 * Adjust the current immersive mode setting.
Christopher Tate73c2aee2012-03-15 16:27:14 -07004968 *
Daniel Sandler69a48172010-06-23 16:29:36 -04004969 * Note that changing this value will have no effect on the activity's
4970 * {@link android.content.pm.ActivityInfo} structure; that is, if
4971 * <code>android:immersive</code> is set to <code>true</code>
4972 * in the application's manifest entry for this activity, the {@link
4973 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
4974 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4975 * FLAG_IMMERSIVE} bit set.
4976 *
Christopher Tate73c2aee2012-03-15 16:27:14 -07004977 * @see #isImmersive()
Daniel Sandler69a48172010-06-23 16:29:36 -04004978 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4979 */
4980 public void setImmersive(boolean i) {
4981 try {
4982 ActivityManagerNative.getDefault().setImmersive(mToken, i);
4983 } catch (RemoteException e) {
4984 // pass
4985 }
4986 }
4987
Adam Powell6e346362010-07-23 10:18:23 -07004988 /**
Adam Powelldebf3be2010-11-15 18:58:48 -08004989 * Start an action mode.
Adam Powell6e346362010-07-23 10:18:23 -07004990 *
4991 * @param callback Callback that will manage lifecycle events for this context mode
4992 * @return The ContextMode that was started, or null if it was canceled
4993 *
4994 * @see ActionMode
4995 */
Adam Powell5d279772010-07-27 16:34:07 -07004996 public ActionMode startActionMode(ActionMode.Callback callback) {
Adam Powell6e346362010-07-23 10:18:23 -07004997 return mWindow.getDecorView().startActionMode(callback);
4998 }
4999
Adam Powelldebf3be2010-11-15 18:58:48 -08005000 /**
5001 * Give the Activity a chance to control the UI for an action mode requested
5002 * by the system.
5003 *
5004 * <p>Note: If you are looking for a notification callback that an action mode
5005 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
5006 *
5007 * @param callback The callback that should control the new action mode
5008 * @return The new action mode, or <code>null</code> if the activity does not want to
5009 * provide special handling for this action mode. (It will be handled by the system.)
5010 */
Craig Mautner5eda9b32013-07-02 11:58:16 -07005011 @Override
Adam Powelldebf3be2010-11-15 18:58:48 -08005012 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
Adam Powell42c0fe82010-08-10 16:36:56 -07005013 initActionBar();
Adam Powell6e346362010-07-23 10:18:23 -07005014 if (mActionBar != null) {
Adam Powell5d279772010-07-27 16:34:07 -07005015 return mActionBar.startActionMode(callback);
Adam Powell6e346362010-07-23 10:18:23 -07005016 }
5017 return null;
5018 }
5019
Adam Powelldebf3be2010-11-15 18:58:48 -08005020 /**
5021 * Notifies the Activity that an action mode has been started.
5022 * Activity subclasses overriding this method should call the superclass implementation.
5023 *
5024 * @param mode The new action mode.
5025 */
Craig Mautner5eda9b32013-07-02 11:58:16 -07005026 @Override
Adam Powelldebf3be2010-11-15 18:58:48 -08005027 public void onActionModeStarted(ActionMode mode) {
5028 }
5029
5030 /**
5031 * Notifies the activity that an action mode has finished.
5032 * Activity subclasses overriding this method should call the superclass implementation.
5033 *
5034 * @param mode The action mode that just finished.
5035 */
Craig Mautner5eda9b32013-07-02 11:58:16 -07005036 @Override
Adam Powelldebf3be2010-11-15 18:58:48 -08005037 public void onActionModeFinished(ActionMode mode) {
5038 }
5039
Adam Powelldd8fab22012-03-22 17:47:27 -07005040 /**
5041 * Returns true if the app should recreate the task when navigating 'up' from this activity
5042 * by using targetIntent.
5043 *
5044 * <p>If this method returns false the app can trivially call
5045 * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
5046 * up navigation. If this method returns false, the app should synthesize a new task stack
5047 * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
5048 *
5049 * @param targetIntent An intent representing the target destination for up navigation
5050 * @return true if navigating up should recreate a new task stack, false if the same task
5051 * should be used for the destination
5052 */
5053 public boolean shouldUpRecreateTask(Intent targetIntent) {
5054 try {
5055 PackageManager pm = getPackageManager();
5056 ComponentName cn = targetIntent.getComponent();
5057 if (cn == null) {
5058 cn = targetIntent.resolveActivity(pm);
5059 }
5060 ActivityInfo info = pm.getActivityInfo(cn, 0);
5061 if (info.taskAffinity == null) {
5062 return false;
5063 }
5064 return !ActivityManagerNative.getDefault()
5065 .targetTaskAffinityMatchesActivity(mToken, info.taskAffinity);
5066 } catch (RemoteException e) {
5067 return false;
5068 } catch (NameNotFoundException e) {
5069 return false;
5070 }
5071 }
5072
5073 /**
5074 * Navigate from this activity to the activity specified by upIntent, finishing this activity
5075 * in the process. If the activity indicated by upIntent already exists in the task's history,
5076 * this activity and all others before the indicated activity in the history stack will be
Adam Powell35c064b2012-05-02 11:37:15 -07005077 * finished.
5078 *
5079 * <p>If the indicated activity does not appear in the history stack, this will finish
5080 * each activity in this task until the root activity of the task is reached, resulting in
5081 * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
5082 * when an activity may be reached by a path not passing through a canonical parent
5083 * activity.</p>
Adam Powelldd8fab22012-03-22 17:47:27 -07005084 *
5085 * <p>This method should be used when performing up navigation from within the same task
5086 * as the destination. If up navigation should cross tasks in some cases, see
5087 * {@link #shouldUpRecreateTask(Intent)}.</p>
5088 *
5089 * @param upIntent An intent representing the target destination for up navigation
5090 *
5091 * @return true if up navigation successfully reached the activity indicated by upIntent and
5092 * upIntent was delivered to it. false if an instance of the indicated activity could
5093 * not be found and this activity was simply finished normally.
5094 */
5095 public boolean navigateUpTo(Intent upIntent) {
5096 if (mParent == null) {
5097 ComponentName destInfo = upIntent.getComponent();
5098 if (destInfo == null) {
5099 destInfo = upIntent.resolveActivity(getPackageManager());
5100 if (destInfo == null) {
5101 return false;
5102 }
5103 upIntent = new Intent(upIntent);
5104 upIntent.setComponent(destInfo);
5105 }
5106 int resultCode;
5107 Intent resultData;
5108 synchronized (this) {
5109 resultCode = mResultCode;
5110 resultData = mResultData;
5111 }
5112 if (resultData != null) {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07005113 resultData.prepareToLeaveProcess();
Adam Powelldd8fab22012-03-22 17:47:27 -07005114 }
5115 try {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07005116 upIntent.prepareToLeaveProcess();
Adam Powelldd8fab22012-03-22 17:47:27 -07005117 return ActivityManagerNative.getDefault().navigateUpTo(mToken, upIntent,
5118 resultCode, resultData);
5119 } catch (RemoteException e) {
5120 return false;
5121 }
5122 } else {
5123 return mParent.navigateUpToFromChild(this, upIntent);
5124 }
5125 }
5126
5127 /**
5128 * This is called when a child activity of this one calls its
5129 * {@link #navigateUpTo} method. The default implementation simply calls
5130 * navigateUpTo(upIntent) on this activity (the parent).
5131 *
5132 * @param child The activity making the call.
5133 * @param upIntent An intent representing the target destination for up navigation
5134 *
5135 * @return true if up navigation successfully reached the activity indicated by upIntent and
5136 * upIntent was delivered to it. false if an instance of the indicated activity could
5137 * not be found and this activity was simply finished normally.
5138 */
5139 public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
5140 return navigateUpTo(upIntent);
5141 }
5142
5143 /**
5144 * Obtain an {@link Intent} that will launch an explicit target activity specified by
5145 * this activity's logical parent. The logical parent is named in the application's manifest
5146 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
Adam Powell04d58112012-04-09 10:22:12 -07005147 * Activity subclasses may override this method to modify the Intent returned by
5148 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
5149 * the parent intent entirely.
Adam Powelldd8fab22012-03-22 17:47:27 -07005150 *
Adam Powell04d58112012-04-09 10:22:12 -07005151 * @return a new Intent targeting the defined parent of this activity or null if
5152 * there is no valid parent.
Adam Powelldd8fab22012-03-22 17:47:27 -07005153 */
5154 public Intent getParentActivityIntent() {
Adam Powell04d58112012-04-09 10:22:12 -07005155 final String parentName = mActivityInfo.parentActivityName;
5156 if (TextUtils.isEmpty(parentName)) {
5157 return null;
5158 }
Adam Powell5a4010c2012-09-16 15:14:05 -07005159
5160 // If the parent itself has no parent, generate a main activity intent.
5161 final ComponentName target = new ComponentName(this, parentName);
5162 try {
5163 final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
5164 final String parentActivity = parentInfo.parentActivityName;
5165 final Intent parentIntent = parentActivity == null
5166 ? Intent.makeMainActivity(target)
5167 : new Intent().setComponent(target);
5168 return parentIntent;
5169 } catch (NameNotFoundException e) {
5170 Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
5171 "' in manifest");
5172 return null;
5173 }
Adam Powelldd8fab22012-03-22 17:47:27 -07005174 }
5175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005176 // ------------------ Internal API ------------------
5177
5178 final void setParent(Activity parent) {
5179 mParent = parent;
5180 }
5181
5182 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
5183 Application application, Intent intent, ActivityInfo info, CharSequence title,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07005184 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005185 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005186 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07005187 lastNonConfigurationInstances, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005188 }
5189
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005190 final void attach(Context context, ActivityThread aThread,
5191 Instrumentation instr, IBinder token, int ident,
5192 Application application, Intent intent, ActivityInfo info,
5193 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07005194 NonConfigurationInstances lastNonConfigurationInstances,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005195 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 attachBaseContext(context);
5197
Dianne Hackborn62bea2f2012-09-04 18:48:15 -07005198 mFragments.attachActivity(this, mContainer, null);
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 mWindow = PolicyManager.makeNewWindow(this);
5201 mWindow.setCallback(this);
Dianne Hackborn420829e2011-01-28 11:30:35 -08005202 mWindow.getLayoutInflater().setPrivateFactory(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
5204 mWindow.setSoftInputMode(info.softInputMode);
5205 }
Adam Powell269248d2011-08-02 10:26:54 -07005206 if (info.uiOptions != 0) {
5207 mWindow.setUiOptions(info.uiOptions);
5208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 mUiThread = Thread.currentThread();
Romain Guy529b60a2010-08-03 18:05:47 -07005210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005211 mMainThread = aThread;
5212 mInstrumentation = instr;
5213 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005214 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005215 mApplication = application;
5216 mIntent = intent;
5217 mComponent = intent.getComponent();
5218 mActivityInfo = info;
5219 mTitle = title;
5220 mParent = parent;
5221 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07005222 mLastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223
Jeff Brown98365d72012-08-19 20:30:52 -07005224 mWindow.setWindowManager(
5225 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
5226 mToken, mComponent.flattenToString(),
Romain Guy529b60a2010-08-03 18:05:47 -07005227 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005228 if (mParent != null) {
5229 mWindow.setContainer(mParent.getWindow());
5230 }
5231 mWindowManager = mWindow.getWindowManager();
5232 mCurrentConfig = config;
5233 }
5234
Dianne Hackborn5320eb82012-05-18 12:05:04 -07005235 /** @hide */
5236 public final IBinder getActivityToken() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005237 return mParent != null ? mParent.getActivityToken() : mToken;
5238 }
5239
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005240 final void performCreate(Bundle icicle) {
5241 onCreate(icicle);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005242 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
5243 com.android.internal.R.styleable.Window_windowNoDisplay, false);
Dianne Hackbornc8017682010-07-06 13:34:38 -07005244 mFragments.dispatchActivityCreated();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005245 }
5246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005247 final void performStart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07005248 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005249 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07005250 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005251 mInstrumentation.callActivityOnStart(this);
5252 if (!mCalled) {
5253 throw new SuperNotCalledException(
5254 "Activity " + mComponent.toShortString() +
5255 " did not call through to super.onStart()");
5256 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005257 mFragments.dispatchStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07005258 if (mAllLoaderManagers != null) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -07005259 final int N = mAllLoaderManagers.size();
5260 LoaderManagerImpl loaders[] = new LoaderManagerImpl[N];
5261 for (int i=N-1; i>=0; i--) {
5262 loaders[i] = mAllLoaderManagers.valueAt(i);
5263 }
5264 for (int i=0; i<N; i++) {
5265 LoaderManagerImpl lm = loaders[i];
5266 lm.finishRetain();
5267 lm.doReportStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07005268 }
5269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 }
5271
5272 final void performRestart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07005273 mFragments.noteStateNotSaved();
Dianne Hackborna21e3da2010-09-12 19:27:46 -07005274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005275 if (mStopped) {
5276 mStopped = false;
Dianne Hackbornce418e62011-03-01 14:31:38 -08005277 if (mToken != null && mParent == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07005278 WindowManagerGlobal.getInstance().setStoppedState(mToken, false);
Dianne Hackbornce418e62011-03-01 14:31:38 -08005279 }
Dianne Hackborn185e3e22011-06-03 15:26:01 -07005280
5281 synchronized (mManagedCursors) {
5282 final int N = mManagedCursors.size();
5283 for (int i=0; i<N; i++) {
5284 ManagedCursor mc = mManagedCursors.get(i);
5285 if (mc.mReleased || mc.mUpdated) {
5286 if (!mc.mCursor.requery()) {
Dianne Hackborna5445d32011-09-01 14:38:24 -07005287 if (getApplicationInfo().targetSdkVersion
5288 >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
5289 throw new IllegalStateException(
5290 "trying to requery an already closed cursor "
5291 + mc.mCursor);
5292 }
Dianne Hackborn185e3e22011-06-03 15:26:01 -07005293 }
5294 mc.mReleased = false;
5295 mc.mUpdated = false;
5296 }
5297 }
5298 }
5299
5300 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005301 mInstrumentation.callActivityOnRestart(this);
5302 if (!mCalled) {
5303 throw new SuperNotCalledException(
5304 "Activity " + mComponent.toShortString() +
5305 " did not call through to super.onRestart()");
5306 }
5307 performStart();
5308 }
5309 }
5310
5311 final void performResume() {
5312 performRestart();
5313
Dianne Hackborn445646c2010-06-25 15:52:59 -07005314 mFragments.execPendingActions();
5315
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07005316 mLastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005318 mCalled = false;
Jeff Hamilton52d32032011-01-08 15:31:26 -06005319 // mResumed is set by the instrumentation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320 mInstrumentation.callActivityOnResume(this);
5321 if (!mCalled) {
5322 throw new SuperNotCalledException(
5323 "Activity " + mComponent.toShortString() +
5324 " did not call through to super.onResume()");
5325 }
5326
5327 // Now really resume, and install the current status bar and menu.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005328 mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005329
5330 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07005331 mFragments.execPendingActions();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005333 onPostResume();
5334 if (!mCalled) {
5335 throw new SuperNotCalledException(
5336 "Activity " + mComponent.toShortString() +
5337 " did not call through to super.onPostResume()");
5338 }
5339 }
5340
5341 final void performPause() {
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07005342 mDoReportFullyDrawn = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005343 mFragments.dispatchPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07005344 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345 onPause();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08005346 mResumed = false;
Dianne Hackborne794e9f2010-08-24 12:32:10 -07005347 if (!mCalled && getApplicationInfo().targetSdkVersion
5348 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
5349 throw new SuperNotCalledException(
5350 "Activity " + mComponent.toShortString() +
5351 " did not call through to super.onPause()");
5352 }
Jeff Hamilton52d32032011-01-08 15:31:26 -06005353 mResumed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354 }
5355
5356 final void performUserLeaving() {
5357 onUserInteraction();
5358 onUserLeaveHint();
5359 }
5360
5361 final void performStop() {
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07005362 mDoReportFullyDrawn = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07005363 if (mLoadersStarted) {
5364 mLoadersStarted = false;
Dianne Hackborn2707d602010-07-09 18:01:20 -07005365 if (mLoaderManager != null) {
5366 if (!mChangingConfigurations) {
5367 mLoaderManager.doStop();
5368 } else {
5369 mLoaderManager.doRetain();
5370 }
5371 }
5372 }
5373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 if (!mStopped) {
5375 if (mWindow != null) {
5376 mWindow.closeAllPanels();
5377 }
5378
Dianne Hackbornce418e62011-03-01 14:31:38 -08005379 if (mToken != null && mParent == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07005380 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
Dianne Hackbornce418e62011-03-01 14:31:38 -08005381 }
5382
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005383 mFragments.dispatchStop();
5384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005385 mCalled = false;
5386 mInstrumentation.callActivityOnStop(this);
5387 if (!mCalled) {
5388 throw new SuperNotCalledException(
5389 "Activity " + mComponent.toShortString() +
5390 " did not call through to super.onStop()");
5391 }
5392
Makoto Onuki2f6a0182010-02-22 13:26:59 -08005393 synchronized (mManagedCursors) {
5394 final int N = mManagedCursors.size();
5395 for (int i=0; i<N; i++) {
5396 ManagedCursor mc = mManagedCursors.get(i);
5397 if (!mc.mReleased) {
5398 mc.mCursor.deactivate();
5399 mc.mReleased = true;
5400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005401 }
5402 }
5403
5404 mStopped = true;
5405 }
5406 mResumed = false;
5407 }
5408
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005409 final void performDestroy() {
Dianne Hackborn6d9dcbc2012-10-02 17:51:13 -07005410 mDestroyed = true;
Dianne Hackborn291905e2010-08-17 15:17:15 -07005411 mWindow.destroy();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005412 mFragments.dispatchDestroy();
5413 onDestroy();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07005414 if (mLoaderManager != null) {
5415 mLoaderManager.doDestroy();
5416 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005417 }
5418
Jeff Hamilton52d32032011-01-08 15:31:26 -06005419 /**
5420 * @hide
5421 */
5422 public final boolean isResumed() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005423 return mResumed;
5424 }
5425
5426 void dispatchActivityResult(String who, int requestCode,
5427 int resultCode, Intent data) {
Joe Onorato43a17652011-04-06 19:22:23 -07005428 if (false) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
5430 + ", resCode=" + resultCode + ", data=" + data);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07005431 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 if (who == null) {
5433 onActivityResult(requestCode, resultCode, data);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07005434 } else {
5435 Fragment frag = mFragments.findFragmentByWho(who);
5436 if (frag != null) {
5437 frag.onActivityResult(requestCode, resultCode, data);
5438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 }
5440 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07005441
5442 /**
5443 * Interface for informing a translucent {@link Activity} once all visible activities below it
5444 * have completed drawing. This is necessary only after an {@link Activity} has been made
5445 * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
5446 * translucent again following a call to {@link
5447 * Activity#convertToTranslucent(TranslucentConversionListener)}.
Chet Haaseabd3d772013-09-11 14:33:05 -07005448 *
5449 * @hide
Craig Mautner5eda9b32013-07-02 11:58:16 -07005450 */
5451 public interface TranslucentConversionListener {
5452 /**
5453 * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
5454 * below the top one have been redrawn. Following this callback it is safe to make the top
5455 * Activity translucent because the underlying Activity has been drawn.
5456 *
5457 * @param drawComplete True if the background Activity has drawn itself. False if a timeout
5458 * occurred waiting for the Activity to complete drawing.
5459 *
5460 * @see Activity#convertFromTranslucent()
5461 * @see Activity#convertToTranslucent(TranslucentConversionListener)
5462 */
5463 public void onTranslucentConversionComplete(boolean drawComplete);
5464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465}