blob: cdfd6f2e3432c079aa0c3ebf3476d21ffd48b4a7 [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;
Jeff Brown5182c782013-10-15 20:31:52 -070061import android.util.PrintWriterPrinter;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070062import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.util.SparseArray;
Adam Powell6e346362010-07-23 10:18:23 -070064import android.view.ActionMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.view.ContextMenu;
Adam Powell6e346362010-07-23 10:18:23 -070066import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.view.ContextThemeWrapper;
68import android.view.KeyEvent;
69import android.view.LayoutInflater;
70import android.view.Menu;
71import android.view.MenuInflater;
72import android.view.MenuItem;
73import android.view.MotionEvent;
74import android.view.View;
Adam Powell6e346362010-07-23 10:18:23 -070075import android.view.View.OnCreateContextMenuListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.view.ViewGroup;
Adam Powell6e346362010-07-23 10:18:23 -070077import android.view.ViewGroup.LayoutParams;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.view.ViewManager;
79import android.view.Window;
80import android.view.WindowManager;
Jeff Brown98365d72012-08-19 20:30:52 -070081import android.view.WindowManagerGlobal;
svetoslavganov75986cf2009-05-14 22:28:01 -070082import android.view.accessibility.AccessibilityEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.widget.AdapterView;
84
Dianne Hackborn625ac272010-09-17 18:29:22 -070085import java.io.FileDescriptor;
86import java.io.PrintWriter;
Adam Powell6e346362010-07-23 10:18:23 -070087import java.util.ArrayList;
88import java.util.HashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
90/**
91 * An activity is a single, focused thing that the user can do. Almost all
92 * activities interact with the user, so the Activity class takes care of
93 * creating a window for you in which you can place your UI with
94 * {@link #setContentView}. While activities are often presented to the user
95 * as full-screen windows, they can also be used in other ways: as floating
96 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
97 * or embedded inside of another activity (using {@link ActivityGroup}).
98 *
99 * There are two methods almost all subclasses of Activity will implement:
100 *
101 * <ul>
102 * <li> {@link #onCreate} is where you initialize your activity. Most
103 * importantly, here you will usually call {@link #setContentView(int)}
104 * with a layout resource defining your UI, and using {@link #findViewById}
105 * to retrieve the widgets in that UI that you need to interact with
106 * programmatically.
107 *
108 * <li> {@link #onPause} is where you deal with the user leaving your
109 * activity. Most importantly, any changes made by the user should at this
110 * point be committed (usually to the
111 * {@link android.content.ContentProvider} holding the data).
112 * </ul>
113 *
114 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
115 * activity classes must have a corresponding
116 * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
117 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
118 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 * <p>Topics covered here:
120 * <ol>
Dianne Hackborn291905e2010-08-17 15:17:15 -0700121 * <li><a href="#Fragments">Fragments</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
123 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
124 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
125 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
126 * <li><a href="#Permissions">Permissions</a>
127 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
128 * </ol>
Joe Fernandezb54e7a32011-10-03 15:09:50 -0700129 *
130 * <div class="special reference">
131 * <h3>Developer Guides</h3>
132 * <p>The Activity class is an important part of an application's overall lifecycle,
133 * and the way activities are launched and put together is a fundamental
134 * part of the platform's application model. For a detailed perspective on the structure of an
135 * Android application and how activities behave, please read the
136 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and
137 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
138 * developer guides.</p>
139 *
140 * <p>You can also find a detailed discussion about how to create activities in the
141 * <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a>
142 * developer guide.</p>
143 * </div>
144 *
Dianne Hackborn291905e2010-08-17 15:17:15 -0700145 * <a name="Fragments"></a>
146 * <h3>Fragments</h3>
147 *
148 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
149 * implementations can make use of the {@link Fragment} class to better
150 * modularize their code, build more sophisticated user interfaces for larger
151 * screens, and help scale their application between small and large screens.
152 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 * <a name="ActivityLifecycle"></a>
154 * <h3>Activity Lifecycle</h3>
155 *
156 * <p>Activities in the system are managed as an <em>activity stack</em>.
157 * When a new activity is started, it is placed on the top of the stack
158 * and becomes the running activity -- the previous activity always remains
159 * below it in the stack, and will not come to the foreground again until
160 * the new activity exits.</p>
161 *
162 * <p>An activity has essentially four states:</p>
163 * <ul>
164 * <li> If an activity in the foreground of the screen (at the top of
165 * the stack),
166 * it is <em>active</em> or <em>running</em>. </li>
167 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
168 * or transparent activity has focus on top of your activity), it
169 * is <em>paused</em>. A paused activity is completely alive (it
170 * maintains all state and member information and remains attached to
171 * the window manager), but can be killed by the system in extreme
172 * low memory situations.
173 * <li>If an activity is completely obscured by another activity,
174 * it is <em>stopped</em>. It still retains all state and member information,
175 * however, it is no longer visible to the user so its window is hidden
176 * and it will often be killed by the system when memory is needed
177 * elsewhere.</li>
178 * <li>If an activity is paused or stopped, the system can drop the activity
179 * from memory by either asking it to finish, or simply killing its
180 * process. When it is displayed again to the user, it must be
181 * completely restarted and restored to its previous state.</li>
182 * </ul>
183 *
184 * <p>The following diagram shows the important state paths of an Activity.
185 * The square rectangles represent callback methods you can implement to
186 * perform operations when the Activity moves between states. The colored
187 * ovals are major states the Activity can be in.</p>
188 *
189 * <p><img src="../../../images/activity_lifecycle.png"
190 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
191 *
192 * <p>There are three key loops you may be interested in monitoring within your
193 * activity:
194 *
195 * <ul>
196 * <li>The <b>entire lifetime</b> of an activity happens between the first call
197 * to {@link android.app.Activity#onCreate} through to a single final call
198 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
199 * of "global" state in onCreate(), and release all remaining resources in
200 * onDestroy(). For example, if it has a thread running in the background
201 * to download data from the network, it may create that thread in onCreate()
202 * and then stop the thread in onDestroy().
203 *
204 * <li>The <b>visible lifetime</b> of an activity happens between a call to
205 * {@link android.app.Activity#onStart} until a corresponding call to
206 * {@link android.app.Activity#onStop}. During this time the user can see the
207 * activity on-screen, though it may not be in the foreground and interacting
208 * with the user. Between these two methods you can maintain resources that
209 * are needed to show the activity to the user. For example, you can register
210 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
Ken Wakasaf76a50c2012-03-09 19:56:35 +0900211 * that impact your UI, and unregister it in onStop() when the user no
212 * longer sees what you are displaying. The onStart() and onStop() methods
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 * can be called multiple times, as the activity becomes visible and hidden
214 * to the user.
215 *
216 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
217 * {@link android.app.Activity#onResume} until a corresponding call to
218 * {@link android.app.Activity#onPause}. During this time the activity is
219 * in front of all other activities and interacting with the user. An activity
220 * can frequently go between the resumed and paused states -- for example when
221 * the device goes to sleep, when an activity result is delivered, when a new
222 * intent is delivered -- so the code in these methods should be fairly
223 * lightweight.
224 * </ul>
225 *
226 * <p>The entire lifecycle of an activity is defined by the following
227 * Activity methods. All of these are hooks that you can override
228 * to do appropriate work when the activity changes state. All
229 * activities will implement {@link android.app.Activity#onCreate}
230 * to do their initial setup; many will also implement
231 * {@link android.app.Activity#onPause} to commit changes to data and
232 * otherwise prepare to stop interacting with the user. You should always
233 * call up to your superclass when implementing these methods.</p>
234 *
235 * </p>
236 * <pre class="prettyprint">
237 * public class Activity extends ApplicationContext {
238 * protected void onCreate(Bundle savedInstanceState);
239 *
240 * protected void onStart();
241 *
242 * protected void onRestart();
243 *
244 * protected void onResume();
245 *
246 * protected void onPause();
247 *
248 * protected void onStop();
249 *
250 * protected void onDestroy();
251 * }
252 * </pre>
253 *
254 * <p>In general the movement through an activity's lifecycle looks like
255 * this:</p>
256 *
257 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
258 * <colgroup align="left" span="3" />
259 * <colgroup align="left" />
260 * <colgroup align="center" />
261 * <colgroup align="center" />
262 *
263 * <thead>
264 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
265 * </thead>
266 *
267 * <tbody>
268 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
269 * <td>Called when the activity is first created.
270 * This is where you should do all of your normal static set up:
271 * create views, bind data to lists, etc. This method also
272 * provides you with a Bundle containing the activity's previously
273 * frozen state, if there was one.
274 * <p>Always followed by <code>onStart()</code>.</td>
275 * <td align="center">No</td>
276 * <td align="center"><code>onStart()</code></td>
277 * </tr>
278 *
279 * <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
280 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
281 * <td>Called after your activity has been stopped, prior to it being
282 * started again.
283 * <p>Always followed by <code>onStart()</code></td>
284 * <td align="center">No</td>
285 * <td align="center"><code>onStart()</code></td>
286 * </tr>
287 *
288 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
289 * <td>Called when the activity is becoming visible to the user.
290 * <p>Followed by <code>onResume()</code> if the activity comes
291 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
292 * <td align="center">No</td>
293 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
294 * </tr>
295 *
296 * <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
297 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
298 * <td>Called when the activity will start
299 * interacting with the user. At this point your activity is at
300 * the top of the activity stack, with user input going to it.
301 * <p>Always followed by <code>onPause()</code>.</td>
302 * <td align="center">No</td>
303 * <td align="center"><code>onPause()</code></td>
304 * </tr>
305 *
306 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
307 * <td>Called when the system is about to start resuming a previous
308 * activity. This is typically used to commit unsaved changes to
309 * persistent data, stop animations and other things that may be consuming
310 * CPU, etc. Implementations of this method must be very quick because
311 * the next activity will not be resumed until this method returns.
312 * <p>Followed by either <code>onResume()</code> if the activity
313 * returns back to the front, or <code>onStop()</code> if it becomes
314 * invisible to the user.</td>
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800315 * <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 -0800316 * <td align="center"><code>onResume()</code> or<br>
317 * <code>onStop()</code></td>
318 * </tr>
319 *
320 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
321 * <td>Called when the activity is no longer visible to the user, because
322 * another activity has been resumed and is covering this one. This
323 * may happen either because a new activity is being started, an existing
324 * one is being brought in front of this one, or this one is being
325 * destroyed.
326 * <p>Followed by either <code>onRestart()</code> if
327 * this activity is coming back to interact with the user, or
328 * <code>onDestroy()</code> if this activity is going away.</td>
329 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
330 * <td align="center"><code>onRestart()</code> or<br>
331 * <code>onDestroy()</code></td>
332 * </tr>
333 *
334 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
335 * <td>The final call you receive before your
336 * activity is destroyed. This can happen either because the
337 * activity is finishing (someone called {@link Activity#finish} on
338 * it, or because the system is temporarily destroying this
339 * instance of the activity to save space. You can distinguish
340 * between these two scenarios with the {@link
341 * Activity#isFinishing} method.</td>
342 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
343 * <td align="center"><em>nothing</em></td>
344 * </tr>
345 * </tbody>
346 * </table>
347 *
348 * <p>Note the "Killable" column in the above table -- for those methods that
349 * are marked as being killable, after that method returns the process hosting the
350 * activity may killed by the system <em>at any time</em> without another line
351 * of its code being executed. Because of this, you should use the
352 * {@link #onPause} method to write any persistent data (such as user edits)
353 * to storage. In addition, the method
354 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
355 * in such a background state, allowing you to save away any dynamic instance
356 * state in your activity into the given Bundle, to be later received in
357 * {@link #onCreate} if the activity needs to be re-created.
358 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
359 * section for more information on how the lifecycle of a process is tied
360 * to the activities it is hosting. Note that it is important to save
361 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
Daisuke Miyakawa5c40f3f2011-02-15 13:24:36 -0800362 * because the latter is not part of the lifecycle callbacks, so will not
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 * be called in every situation as described in its documentation.</p>
364 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800365 * <p class="note">Be aware that these semantics will change slightly between
366 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
367 * vs. those targeting prior platforms. Starting with Honeycomb, an application
368 * is not in the killable state until its {@link #onStop} has returned. This
369 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
370 * safely called after {@link #onPause()} and allows and application to safely
371 * wait until {@link #onStop()} to save persistent state.</p>
372 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 * <p>For those methods that are not marked as being killable, the activity's
374 * process will not be killed by the system starting from the time the method
375 * is called and continuing after it returns. Thus an activity is in the killable
376 * state, for example, between after <code>onPause()</code> to the start of
377 * <code>onResume()</code>.</p>
378 *
379 * <a name="ConfigurationChanges"></a>
380 * <h3>Configuration Changes</h3>
381 *
382 * <p>If the configuration of the device (as defined by the
383 * {@link Configuration Resources.Configuration} class) changes,
384 * then anything displaying a user interface will need to update to match that
385 * configuration. Because Activity is the primary mechanism for interacting
386 * with the user, it includes special support for handling configuration
387 * changes.</p>
388 *
389 * <p>Unless you specify otherwise, a configuration change (such as a change
390 * in screen orientation, language, input devices, etc) will cause your
391 * current activity to be <em>destroyed</em>, going through the normal activity
392 * lifecycle process of {@link #onPause},
393 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
394 * had been in the foreground or visible to the user, once {@link #onDestroy} is
395 * called in that instance then a new instance of the activity will be
396 * created, with whatever savedInstanceState the previous instance had generated
397 * from {@link #onSaveInstanceState}.</p>
398 *
399 * <p>This is done because any application resource,
400 * including layout files, can change based on any configuration value. Thus
401 * the only safe way to handle a configuration change is to re-retrieve all
402 * resources, including layouts, drawables, and strings. Because activities
403 * must already know how to save their state and re-create themselves from
404 * that state, this is a convenient way to have an activity restart itself
405 * with a new configuration.</p>
406 *
407 * <p>In some special cases, you may want to bypass restarting of your
408 * activity based on one or more types of configuration changes. This is
409 * done with the {@link android.R.attr#configChanges android:configChanges}
410 * attribute in its manifest. For any types of configuration changes you say
411 * that you handle there, you will receive a call to your current activity's
412 * {@link #onConfigurationChanged} method instead of being restarted. If
413 * a configuration change involves any that you do not handle, however, the
414 * activity will still be restarted and {@link #onConfigurationChanged}
415 * will not be called.</p>
416 *
417 * <a name="StartingActivities"></a>
418 * <h3>Starting Activities and Getting Results</h3>
419 *
420 * <p>The {@link android.app.Activity#startActivity}
421 * method is used to start a
422 * new activity, which will be placed at the top of the activity stack. It
423 * takes a single argument, an {@link android.content.Intent Intent},
424 * which describes the activity
425 * to be executed.</p>
426 *
427 * <p>Sometimes you want to get a result back from an activity when it
428 * ends. For example, you may start an activity that lets the user pick
429 * a person in a list of contacts; when it ends, it returns the person
430 * that was selected. To do this, you call the
431 * {@link android.app.Activity#startActivityForResult(Intent, int)}
432 * version with a second integer parameter identifying the call. The result
433 * will come back through your {@link android.app.Activity#onActivityResult}
434 * method.</p>
435 *
436 * <p>When an activity exits, it can call
437 * {@link android.app.Activity#setResult(int)}
438 * to return data back to its parent. It must always supply a result code,
439 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
440 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
441 * return back an Intent containing any additional data it wants. All of this
442 * information appears back on the
443 * parent's <code>Activity.onActivityResult()</code>, along with the integer
444 * identifier it originally supplied.</p>
445 *
446 * <p>If a child activity fails for any reason (such as crashing), the parent
447 * activity will receive a result with the code RESULT_CANCELED.</p>
448 *
449 * <pre class="prettyprint">
450 * public class MyActivity extends Activity {
451 * ...
452 *
453 * static final int PICK_CONTACT_REQUEST = 0;
454 *
455 * protected boolean onKeyDown(int keyCode, KeyEvent event) {
456 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
457 * // When the user center presses, let them pick a contact.
458 * startActivityForResult(
459 * new Intent(Intent.ACTION_PICK,
460 * new Uri("content://contacts")),
461 * PICK_CONTACT_REQUEST);
462 * return true;
463 * }
464 * return false;
465 * }
466 *
467 * protected void onActivityResult(int requestCode, int resultCode,
468 * Intent data) {
469 * if (requestCode == PICK_CONTACT_REQUEST) {
470 * if (resultCode == RESULT_OK) {
471 * // A contact was picked. Here we will just display it
472 * // to the user.
473 * startActivity(new Intent(Intent.ACTION_VIEW, data));
474 * }
475 * }
476 * }
477 * }
478 * </pre>
479 *
480 * <a name="SavingPersistentState"></a>
481 * <h3>Saving Persistent State</h3>
482 *
483 * <p>There are generally two kinds of persistent state than an activity
484 * will deal with: shared document-like data (typically stored in a SQLite
485 * database using a {@linkplain android.content.ContentProvider content provider})
486 * and internal state such as user preferences.</p>
487 *
488 * <p>For content provider data, we suggest that activities use a
489 * "edit in place" user model. That is, any edits a user makes are effectively
490 * made immediately without requiring an additional confirmation step.
491 * Supporting this model is generally a simple matter of following two rules:</p>
492 *
493 * <ul>
494 * <li> <p>When creating a new document, the backing database entry or file for
495 * it is created immediately. For example, if the user chooses to write
496 * a new e-mail, a new entry for that e-mail is created as soon as they
497 * start entering data, so that if they go to any other activity after
498 * that point this e-mail will now appear in the list of drafts.</p>
499 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
500 * commit to the backing content provider or file any changes the user
501 * has made. This ensures that those changes will be seen by any other
502 * activity that is about to run. You will probably want to commit
503 * your data even more aggressively at key times during your
504 * activity's lifecycle: for example before starting a new
505 * activity, before finishing your own activity, when the user
506 * switches between input fields, etc.</p>
507 * </ul>
508 *
509 * <p>This model is designed to prevent data loss when a user is navigating
510 * between activities, and allows the system to safely kill an activity (because
511 * system resources are needed somewhere else) at any time after it has been
512 * paused. Note this implies
513 * that the user pressing BACK from your activity does <em>not</em>
514 * mean "cancel" -- it means to leave the activity with its current contents
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800515 * saved away. Canceling edits in an activity must be provided through
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
517 *
518 * <p>See the {@linkplain android.content.ContentProvider content package} for
519 * more information about content providers. These are a key aspect of how
520 * different activities invoke and propagate data between themselves.</p>
521 *
522 * <p>The Activity class also provides an API for managing internal persistent state
523 * associated with an activity. This can be used, for example, to remember
524 * the user's preferred initial display in a calendar (day view or week view)
525 * or the user's default home page in a web browser.</p>
526 *
527 * <p>Activity persistent state is managed
528 * with the method {@link #getPreferences},
529 * allowing you to retrieve and
530 * modify a set of name/value pairs associated with the activity. To use
531 * preferences that are shared across multiple application components
532 * (activities, receivers, services, providers), you can use the underlying
533 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
534 * to retrieve a preferences
535 * object stored under a specific name.
536 * (Note that it is not possible to share settings data across application
537 * packages -- for that you will need a content provider.)</p>
538 *
539 * <p>Here is an excerpt from a calendar activity that stores the user's
540 * preferred view mode in its persistent settings:</p>
541 *
542 * <pre class="prettyprint">
543 * public class CalendarActivity extends Activity {
544 * ...
545 *
546 * static final int DAY_VIEW_MODE = 0;
547 * static final int WEEK_VIEW_MODE = 1;
548 *
549 * private SharedPreferences mPrefs;
550 * private int mCurViewMode;
551 *
552 * protected void onCreate(Bundle savedInstanceState) {
553 * super.onCreate(savedInstanceState);
554 *
555 * SharedPreferences mPrefs = getSharedPreferences();
Quddus Chong3fa98cb2012-04-13 11:17:24 -0700556 * mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 * }
558 *
559 * protected void onPause() {
560 * super.onPause();
561 *
562 * SharedPreferences.Editor ed = mPrefs.edit();
563 * ed.putInt("view_mode", mCurViewMode);
564 * ed.commit();
565 * }
566 * }
567 * </pre>
568 *
569 * <a name="Permissions"></a>
570 * <h3>Permissions</h3>
571 *
572 * <p>The ability to start a particular Activity can be enforced when it is
573 * declared in its
574 * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
575 * tag. By doing so, other applications will need to declare a corresponding
576 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
577 * element in their own manifest to be able to start that activity.
Dianne Hackborn21c241e2012-03-08 13:57:23 -0800578 *
579 * <p>When starting an Activity you can set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
580 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
581 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the
582 * Activity access to the specific URIs in the Intent. Access will remain
583 * until the Activity has finished (it will remain across the hosting
584 * process being killed and other temporary destruction). As of
585 * {@link android.os.Build.VERSION_CODES#GINGERBREAD}, if the Activity
586 * was already created and a new Intent is being delivered to
587 * {@link #onNewIntent(Intent)}, any newly granted URI permissions will be added
588 * to the existing ones it holds.
589 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
591 * document for more information on permissions and security in general.
592 *
593 * <a name="ProcessLifecycle"></a>
594 * <h3>Process Lifecycle</h3>
595 *
596 * <p>The Android system attempts to keep application process around for as
597 * long as possible, but eventually will need to remove old processes when
598 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
599 * Lifecycle</a>, the decision about which process to remove is intimately
600 * tied to the state of the user's interaction with it. In general, there
601 * are four states a process can be in based on the activities running in it,
602 * listed here in order of importance. The system will kill less important
603 * processes (the last ones) before it resorts to killing more important
604 * processes (the first ones).
605 *
606 * <ol>
607 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
608 * that the user is currently interacting with) is considered the most important.
609 * Its process will only be killed as a last resort, if it uses more memory
610 * than is available on the device. Generally at this point the device has
611 * reached a memory paging state, so this is required in order to keep the user
612 * interface responsive.
613 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
614 * but not in the foreground, such as one sitting behind a foreground dialog)
615 * is considered extremely important and will not be killed unless that is
616 * required to keep the foreground activity running.
617 * <li> <p>A <b>background activity</b> (an activity that is not visible to
618 * the user and has been paused) is no longer critical, so the system may
619 * safely kill its process to reclaim memory for other foreground or
620 * visible processes. If its process needs to be killed, when the user navigates
621 * back to the activity (making it visible on the screen again), its
622 * {@link #onCreate} method will be called with the savedInstanceState it had previously
623 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
624 * state as the user last left it.
625 * <li> <p>An <b>empty process</b> is one hosting no activities or other
626 * application components (such as {@link Service} or
627 * {@link android.content.BroadcastReceiver} classes). These are killed very
628 * quickly by the system as memory becomes low. For this reason, any
629 * background operation you do outside of an activity must be executed in the
630 * context of an activity BroadcastReceiver or Service to ensure that the system
631 * knows it needs to keep your process around.
632 * </ol>
633 *
634 * <p>Sometimes an Activity may need to do a long-running operation that exists
635 * independently of the activity lifecycle itself. An example may be a camera
636 * application that allows you to upload a picture to a web site. The upload
637 * may take a long time, and the application should allow the user to leave
638 * the application will it is executing. To accomplish this, your Activity
639 * should start a {@link Service} in which the upload takes place. This allows
640 * the system to properly prioritize your process (considering it to be more
641 * important than other non-visible applications) for the duration of the
642 * upload, independent of whether the original activity is paused, stopped,
643 * or finished.
644 */
645public class Activity extends ContextThemeWrapper
Dianne Hackborn625ac272010-09-17 18:29:22 -0700646 implements LayoutInflater.Factory2,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 Window.Callback, KeyEvent.Callback,
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700648 OnCreateContextMenuListener, ComponentCallbacks2 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 private static final String TAG = "Activity";
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700650 private static final boolean DEBUG_LIFECYCLE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651
652 /** Standard activity result: operation canceled. */
653 public static final int RESULT_CANCELED = 0;
654 /** Standard activity result: operation succeeded. */
655 public static final int RESULT_OK = -1;
656 /** Start of user-defined activity results. */
657 public static final int RESULT_FIRST_USER = 1;
658
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700659 static final String FRAGMENTS_TAG = "android:fragments";
660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
662 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
663 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
664 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800665 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800667 private static class ManagedDialog {
668 Dialog mDialog;
669 Bundle mArgs;
670 }
671 private SparseArray<ManagedDialog> mManagedDialogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672
673 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
674 private Instrumentation mInstrumentation;
675 private IBinder mToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700676 private int mIdent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 /*package*/ String mEmbeddedID;
678 private Application mApplication;
Christopher Tateb70f3df2009-04-07 16:07:59 -0700679 /*package*/ Intent mIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 private ComponentName mComponent;
681 /*package*/ ActivityInfo mActivityInfo;
682 /*package*/ ActivityThread mMainThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 Activity mParent;
684 boolean mCalled;
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700685 boolean mCheckedForLoaderManager;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700686 boolean mLoadersStarted;
Jeff Hamilton52d32032011-01-08 15:31:26 -0600687 /*package*/ boolean mResumed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 private boolean mStopped;
689 boolean mFinished;
690 boolean mStartedActivity;
Dianne Hackborn6d9dcbc2012-10-02 17:51:13 -0700691 private boolean mDestroyed;
Dianne Hackborn2286cdc2013-07-01 19:10:06 -0700692 private boolean mDoReportFullyDrawn = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700693 /** true if the activity is going through a transient pause */
694 /*package*/ boolean mTemporaryPause = false;
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -0500695 /** true if the activity is being destroyed in order to recreate it with a new configuration */
696 /*package*/ boolean mChangingConfigurations = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 /*package*/ int mConfigChangeFlags;
698 /*package*/ Configuration mCurrentConfig;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +0100699 private SearchManager mSearchManager;
Adam Powell88ab6972011-07-28 11:25:01 -0700700 private MenuInflater mMenuInflater;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700702 static final class NonConfigurationInstances {
703 Object activity;
704 HashMap<String, Object> children;
705 ArrayList<Fragment> fragments;
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700706 ArrayMap<String, LoaderManagerImpl> loaders;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700707 }
708 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 private Window mWindow;
711
712 private WindowManager mWindowManager;
713 /*package*/ View mDecor = null;
714 /*package*/ boolean mWindowAdded = false;
715 /*package*/ boolean mVisibleFromServer = false;
716 /*package*/ boolean mVisibleFromClient = true;
Adam Powellac695c62010-07-20 18:19:27 -0700717 /*package*/ ActionBarImpl mActionBar = null;
Adam Powelldd8fab22012-03-22 17:47:27 -0700718 private boolean mEnableDefaultActionBarUp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719
720 private CharSequence mTitle;
721 private int mTitleColor = 0;
722
Dianne Hackbornb7a2e472010-08-12 16:20:42 -0700723 final FragmentManagerImpl mFragments = new FragmentManagerImpl();
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700724 final FragmentContainer mContainer = new FragmentContainer() {
725 @Override
726 public View findViewById(int id) {
727 return Activity.this.findViewById(id);
728 }
729 };
Dianne Hackborn2dedce62010-04-15 14:45:25 -0700730
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700731 ArrayMap<String, LoaderManagerImpl> mAllLoaderManagers;
Dianne Hackborn4911b782010-07-15 12:54:39 -0700732 LoaderManagerImpl mLoaderManager;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 private static final class ManagedCursor {
735 ManagedCursor(Cursor cursor) {
736 mCursor = cursor;
737 mReleased = false;
738 mUpdated = false;
739 }
740
741 private final Cursor mCursor;
742 private boolean mReleased;
743 private boolean mUpdated;
744 }
745 private final ArrayList<ManagedCursor> mManagedCursors =
746 new ArrayList<ManagedCursor>();
747
748 // protected by synchronized (this)
749 int mResultCode = RESULT_CANCELED;
750 Intent mResultData = null;
Craig Mautner5eda9b32013-07-02 11:58:16 -0700751 private TranslucentConversionListener mTranslucentCallback;
Craig Mautnerbc57cd12013-08-19 15:47:42 -0700752 private boolean mChangeCanvasToTranslucent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753
754 private boolean mTitleReady = false;
755
756 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
757 private SpannableStringBuilder mDefaultKeySsb = null;
758
759 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
760
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700761 @SuppressWarnings("unused")
Jeff Brown7e442832011-06-10 18:00:16 -0700762 private final Object mInstanceTracker = StrictMode.trackActivity(this);
763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 private Thread mUiThread;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700765 final Handler mHandler = new Handler();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 /** Return the intent that started this activity. */
768 public Intent getIntent() {
769 return mIntent;
770 }
771
772 /**
773 * Change the intent returned by {@link #getIntent}. This holds a
774 * reference to the given intent; it does not copy it. Often used in
775 * conjunction with {@link #onNewIntent}.
776 *
777 * @param newIntent The new Intent object to return from getIntent
778 *
779 * @see #getIntent
780 * @see #onNewIntent
781 */
782 public void setIntent(Intent newIntent) {
783 mIntent = newIntent;
784 }
785
786 /** Return the application that owns this activity. */
787 public final Application getApplication() {
788 return mApplication;
789 }
790
791 /** Is this activity embedded inside of another activity? */
792 public final boolean isChild() {
793 return mParent != null;
794 }
795
796 /** Return the parent activity if this view is an embedded child. */
797 public final Activity getParent() {
798 return mParent;
799 }
800
801 /** Retrieve the window manager for showing custom windows. */
802 public WindowManager getWindowManager() {
803 return mWindowManager;
804 }
805
806 /**
807 * Retrieve the current {@link android.view.Window} for the activity.
808 * This can be used to directly access parts of the Window API that
809 * are not available through Activity/Screen.
810 *
811 * @return Window The current window, or null if the activity is not
812 * visual.
813 */
814 public Window getWindow() {
815 return mWindow;
816 }
817
818 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -0700819 * Return the LoaderManager for this fragment, creating it if needed.
820 */
821 public LoaderManager getLoaderManager() {
822 if (mLoaderManager != null) {
823 return mLoaderManager;
824 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700825 mCheckedForLoaderManager = true;
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700826 mLoaderManager = getLoaderManager("(root)", mLoadersStarted, true);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700827 return mLoaderManager;
828 }
829
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700830 LoaderManagerImpl getLoaderManager(String who, boolean started, boolean create) {
Dianne Hackbornc8017682010-07-06 13:34:38 -0700831 if (mAllLoaderManagers == null) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700832 mAllLoaderManagers = new ArrayMap<String, LoaderManagerImpl>();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700833 }
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700834 LoaderManagerImpl lm = mAllLoaderManagers.get(who);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700835 if (lm == null) {
836 if (create) {
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700837 lm = new LoaderManagerImpl(who, this, started);
838 mAllLoaderManagers.put(who, lm);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700839 }
840 } else {
841 lm.updateActivity(this);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700842 }
843 return lm;
844 }
845
846 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 * Calls {@link android.view.Window#getCurrentFocus} on the
848 * Window of this Activity to return the currently focused view.
849 *
850 * @return View The current View with focus or null.
851 *
852 * @see #getWindow
853 * @see android.view.Window#getCurrentFocus
854 */
855 public View getCurrentFocus() {
856 return mWindow != null ? mWindow.getCurrentFocus() : null;
857 }
858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 /**
860 * Called when the activity is starting. This is where most initialization
861 * should go: calling {@link #setContentView(int)} to inflate the
862 * activity's UI, using {@link #findViewById} to programmatically interact
863 * with widgets in the UI, calling
864 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
865 * cursors for data being displayed, etc.
866 *
867 * <p>You can call {@link #finish} from within this function, in
868 * which case onDestroy() will be immediately called without any of the rest
869 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
870 * {@link #onPause}, etc) executing.
871 *
872 * <p><em>Derived classes must call through to the super class's
873 * implementation of this method. If they do not, an exception will be
874 * thrown.</em></p>
875 *
876 * @param savedInstanceState If the activity is being re-initialized after
877 * previously being shut down then this Bundle contains the data it most
878 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
879 *
880 * @see #onStart
881 * @see #onSaveInstanceState
882 * @see #onRestoreInstanceState
883 * @see #onPostCreate
884 */
885 protected void onCreate(Bundle savedInstanceState) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700886 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700887 if (mLastNonConfigurationInstances != null) {
888 mAllLoaderManagers = mLastNonConfigurationInstances.loaders;
889 }
Adam Powelldd8fab22012-03-22 17:47:27 -0700890 if (mActivityInfo.parentActivityName != null) {
891 if (mActionBar == null) {
892 mEnableDefaultActionBarUp = true;
893 } else {
894 mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
895 }
896 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700897 if (savedInstanceState != null) {
898 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
899 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
900 ? mLastNonConfigurationInstances.fragments : null);
901 }
902 mFragments.dispatchCreate();
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700903 getApplication().dispatchActivityCreated(this, savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 mCalled = true;
905 }
906
907 /**
908 * The hook for {@link ActivityThread} to restore the state of this activity.
909 *
910 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
911 * {@link #restoreManagedDialogs(android.os.Bundle)}.
912 *
913 * @param savedInstanceState contains the saved state
914 */
915 final void performRestoreInstanceState(Bundle savedInstanceState) {
916 onRestoreInstanceState(savedInstanceState);
917 restoreManagedDialogs(savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 }
919
920 /**
921 * This method is called after {@link #onStart} when the activity is
922 * being re-initialized from a previously saved state, given here in
Mike LeBeau305de9d2010-03-11 09:21:08 -0800923 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 * to restore their state, but it is sometimes convenient to do it here
925 * after all of the initialization has been done or to allow subclasses to
926 * decide whether to use your default implementation. The default
927 * implementation of this method performs a restore of any view state that
928 * had previously been frozen by {@link #onSaveInstanceState}.
929 *
930 * <p>This method is called between {@link #onStart} and
931 * {@link #onPostCreate}.
932 *
933 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
934 *
935 * @see #onCreate
936 * @see #onPostCreate
937 * @see #onResume
938 * @see #onSaveInstanceState
939 */
940 protected void onRestoreInstanceState(Bundle savedInstanceState) {
941 if (mWindow != null) {
942 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
943 if (windowState != null) {
944 mWindow.restoreHierarchyState(windowState);
945 }
946 }
947 }
948
949 /**
950 * Restore the state of any saved managed dialogs.
951 *
952 * @param savedInstanceState The bundle to restore from.
953 */
954 private void restoreManagedDialogs(Bundle savedInstanceState) {
955 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
956 if (b == null) {
957 return;
958 }
959
960 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
961 final int numDialogs = ids.length;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800962 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 for (int i = 0; i < numDialogs; i++) {
964 final Integer dialogId = ids[i];
965 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
966 if (dialogState != null) {
Romain Guye35c2352009-06-19 13:18:12 -0700967 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
968 // so tell createDialog() not to do it, otherwise we get an exception
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800969 final ManagedDialog md = new ManagedDialog();
970 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
971 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
972 if (md.mDialog != null) {
973 mManagedDialogs.put(dialogId, md);
974 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
975 md.mDialog.onRestoreInstanceState(dialogState);
976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 }
978 }
979 }
980
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800981 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
982 final Dialog dialog = onCreateDialog(dialogId, args);
Romain Guy764d5332009-06-17 16:52:22 -0700983 if (dialog == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800984 return null;
Romain Guy764d5332009-06-17 16:52:22 -0700985 }
Romain Guy6de4aed2009-07-08 10:54:45 -0700986 dialog.dispatchOnCreate(state);
Romain Guy764d5332009-06-17 16:52:22 -0700987 return dialog;
988 }
989
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800990 private static String savedDialogKeyFor(int key) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 return SAVED_DIALOG_KEY_PREFIX + key;
992 }
993
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800994 private static String savedDialogArgsKeyFor(int key) {
995 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997
998 /**
999 * Called when activity start-up is complete (after {@link #onStart}
1000 * and {@link #onRestoreInstanceState} have been called). Applications will
1001 * generally not implement this method; it is intended for system
1002 * classes to do final initialization after application code has run.
1003 *
1004 * <p><em>Derived classes must call through to the super class's
1005 * implementation of this method. If they do not, an exception will be
1006 * thrown.</em></p>
1007 *
1008 * @param savedInstanceState If the activity is being re-initialized after
1009 * previously being shut down then this Bundle contains the data it most
1010 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
1011 * @see #onCreate
1012 */
1013 protected void onPostCreate(Bundle savedInstanceState) {
1014 if (!isChild()) {
1015 mTitleReady = true;
1016 onTitleChanged(getTitle(), getTitleColor());
1017 }
1018 mCalled = true;
1019 }
1020
1021 /**
1022 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
1023 * the activity had been stopped, but is now again being displayed to the
1024 * user. It will be followed by {@link #onResume}.
1025 *
1026 * <p><em>Derived classes must call through to the super class's
1027 * implementation of this method. If they do not, an exception will be
1028 * thrown.</em></p>
1029 *
1030 * @see #onCreate
1031 * @see #onStop
1032 * @see #onResume
1033 */
1034 protected void onStart() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001035 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 mCalled = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001037
1038 if (!mLoadersStarted) {
1039 mLoadersStarted = true;
1040 if (mLoaderManager != null) {
1041 mLoaderManager.doStart();
1042 } else if (!mCheckedForLoaderManager) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -07001043 mLoaderManager = getLoaderManager("(root)", mLoadersStarted, false);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001044 }
1045 mCheckedForLoaderManager = true;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001046 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001047
1048 getApplication().dispatchActivityStarted(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050
1051 /**
1052 * Called after {@link #onStop} when the current activity is being
1053 * re-displayed to the user (the user has navigated back to it). It will
1054 * be followed by {@link #onStart} and then {@link #onResume}.
1055 *
1056 * <p>For activities that are using raw {@link Cursor} objects (instead of
1057 * creating them through
1058 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1059 * this is usually the place
1060 * where the cursor should be requeried (because you had deactivated it in
1061 * {@link #onStop}.
1062 *
1063 * <p><em>Derived classes must call through to the super class's
1064 * implementation of this method. If they do not, an exception will be
1065 * thrown.</em></p>
1066 *
1067 * @see #onStop
1068 * @see #onStart
1069 * @see #onResume
1070 */
1071 protected void onRestart() {
1072 mCalled = true;
1073 }
1074
1075 /**
1076 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1077 * {@link #onPause}, for your activity to start interacting with the user.
1078 * This is a good place to begin animations, open exclusive-access devices
1079 * (such as the camera), etc.
1080 *
1081 * <p>Keep in mind that onResume is not the best indicator that your activity
1082 * is visible to the user; a system window such as the keyguard may be in
1083 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1084 * activity is visible to the user (for example, to resume a game).
1085 *
1086 * <p><em>Derived classes must call through to the super class's
1087 * implementation of this method. If they do not, an exception will be
1088 * thrown.</em></p>
1089 *
1090 * @see #onRestoreInstanceState
1091 * @see #onRestart
1092 * @see #onPostResume
1093 * @see #onPause
1094 */
1095 protected void onResume() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001096 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001097 getApplication().dispatchActivityResumed(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 mCalled = true;
1099 }
1100
1101 /**
1102 * Called when activity resume is complete (after {@link #onResume} has
1103 * been called). Applications will generally not implement this method;
1104 * it is intended for system classes to do final setup after application
1105 * resume code has run.
1106 *
1107 * <p><em>Derived classes must call through to the super class's
1108 * implementation of this method. If they do not, an exception will be
1109 * thrown.</em></p>
1110 *
1111 * @see #onResume
1112 */
1113 protected void onPostResume() {
1114 final Window win = getWindow();
1115 if (win != null) win.makeActive();
Adam Powell50efbed2011-02-08 16:20:15 -08001116 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 mCalled = true;
1118 }
1119
1120 /**
1121 * This is called for activities that set launchMode to "singleTop" in
1122 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1123 * flag when calling {@link #startActivity}. In either case, when the
1124 * activity is re-launched while at the top of the activity stack instead
1125 * of a new instance of the activity being started, onNewIntent() will be
1126 * called on the existing instance with the Intent that was used to
1127 * re-launch it.
1128 *
1129 * <p>An activity will always be paused before receiving a new intent, so
1130 * you can count on {@link #onResume} being called after this method.
1131 *
1132 * <p>Note that {@link #getIntent} still returns the original Intent. You
1133 * can use {@link #setIntent} to update it to this new Intent.
1134 *
1135 * @param intent The new intent that was started for the activity.
1136 *
1137 * @see #getIntent
1138 * @see #setIntent
1139 * @see #onResume
1140 */
1141 protected void onNewIntent(Intent intent) {
1142 }
1143
1144 /**
1145 * The hook for {@link ActivityThread} to save the state of this activity.
1146 *
1147 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1148 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1149 *
1150 * @param outState The bundle to save the state to.
1151 */
1152 final void performSaveInstanceState(Bundle outState) {
1153 onSaveInstanceState(outState);
1154 saveManagedDialogs(outState);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001155 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 }
1157
1158 /**
1159 * Called to retrieve per-instance state from an activity before being killed
1160 * so that the state can be restored in {@link #onCreate} or
1161 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1162 * will be passed to both).
1163 *
1164 * <p>This method is called before an activity may be killed so that when it
1165 * comes back some time in the future it can restore its state. For example,
1166 * if activity B is launched in front of activity A, and at some point activity
1167 * A is killed to reclaim resources, activity A will have a chance to save the
1168 * current state of its user interface via this method so that when the user
1169 * returns to activity A, the state of the user interface can be restored
1170 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1171 *
1172 * <p>Do not confuse this method with activity lifecycle callbacks such as
1173 * {@link #onPause}, which is always called when an activity is being placed
1174 * in the background or on its way to destruction, or {@link #onStop} which
1175 * is called before destruction. One example of when {@link #onPause} and
1176 * {@link #onStop} is called and not this method is when a user navigates back
1177 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1178 * on B because that particular instance will never be restored, so the
1179 * system avoids calling it. An example when {@link #onPause} is called and
1180 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1181 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1182 * killed during the lifetime of B since the state of the user interface of
1183 * A will stay intact.
1184 *
1185 * <p>The default implementation takes care of most of the UI per-instance
1186 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1187 * view in the hierarchy that has an id, and by saving the id of the currently
1188 * focused view (all of which is restored by the default implementation of
1189 * {@link #onRestoreInstanceState}). If you override this method to save additional
1190 * information not captured by each individual view, you will likely want to
1191 * call through to the default implementation, otherwise be prepared to save
1192 * all of the state of each view yourself.
1193 *
1194 * <p>If called, this method will occur before {@link #onStop}. There are
1195 * no guarantees about whether it will occur before or after {@link #onPause}.
1196 *
1197 * @param outState Bundle in which to place your saved state.
1198 *
1199 * @see #onCreate
1200 * @see #onRestoreInstanceState
1201 * @see #onPause
1202 */
1203 protected void onSaveInstanceState(Bundle outState) {
1204 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001205 Parcelable p = mFragments.saveAllState();
1206 if (p != null) {
1207 outState.putParcelable(FRAGMENTS_TAG, p);
1208 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001209 getApplication().dispatchActivitySaveInstanceState(this, outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
1211
1212 /**
1213 * Save the state of any managed dialogs.
1214 *
1215 * @param outState place to store the saved state.
1216 */
1217 private void saveManagedDialogs(Bundle outState) {
1218 if (mManagedDialogs == null) {
1219 return;
1220 }
1221
1222 final int numDialogs = mManagedDialogs.size();
1223 if (numDialogs == 0) {
1224 return;
1225 }
1226
1227 Bundle dialogState = new Bundle();
1228
1229 int[] ids = new int[mManagedDialogs.size()];
1230
1231 // save each dialog's bundle, gather the ids
1232 for (int i = 0; i < numDialogs; i++) {
1233 final int key = mManagedDialogs.keyAt(i);
1234 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001235 final ManagedDialog md = mManagedDialogs.valueAt(i);
1236 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1237 if (md.mArgs != null) {
1238 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 }
1241
1242 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1243 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1244 }
1245
1246
1247 /**
1248 * Called as part of the activity lifecycle when an activity is going into
1249 * the background, but has not (yet) been killed. The counterpart to
1250 * {@link #onResume}.
1251 *
1252 * <p>When activity B is launched in front of activity A, this callback will
1253 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1254 * so be sure to not do anything lengthy here.
1255 *
1256 * <p>This callback is mostly used for saving any persistent state the
1257 * activity is editing, to present a "edit in place" model to the user and
1258 * making sure nothing is lost if there are not enough resources to start
1259 * the new activity without first killing this one. This is also a good
1260 * place to do things like stop animations and other things that consume a
Pin Ting14a93102012-04-25 11:27:03 +08001261 * noticeable amount of CPU in order to make the switch to the next activity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 * as fast as possible, or to close resources that are exclusive access
1263 * such as the camera.
1264 *
1265 * <p>In situations where the system needs more memory it may kill paused
1266 * processes to reclaim resources. Because of this, you should be sure
1267 * that all of your state is saved by the time you return from
1268 * this function. In general {@link #onSaveInstanceState} is used to save
1269 * per-instance state in the activity and this method is used to store
1270 * global persistent data (in content providers, files, etc.)
1271 *
1272 * <p>After receiving this call you will usually receive a following call
1273 * to {@link #onStop} (after the next activity has been resumed and
1274 * displayed), however in some cases there will be a direct call back to
1275 * {@link #onResume} without going through the stopped state.
1276 *
1277 * <p><em>Derived classes must call through to the super class's
1278 * implementation of this method. If they do not, an exception will be
1279 * thrown.</em></p>
1280 *
1281 * @see #onResume
1282 * @see #onSaveInstanceState
1283 * @see #onStop
1284 */
1285 protected void onPause() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001286 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001287 getApplication().dispatchActivityPaused(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 mCalled = true;
1289 }
1290
1291 /**
1292 * Called as part of the activity lifecycle when an activity is about to go
1293 * into the background as the result of user choice. For example, when the
1294 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1295 * when an incoming phone call causes the in-call Activity to be automatically
1296 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1297 * the activity being interrupted. In cases when it is invoked, this method
1298 * is called right before the activity's {@link #onPause} callback.
1299 *
1300 * <p>This callback and {@link #onUserInteraction} are intended to help
1301 * activities manage status bar notifications intelligently; specifically,
1302 * for helping activities determine the proper time to cancel a notfication.
1303 *
1304 * @see #onUserInteraction()
1305 */
1306 protected void onUserLeaveHint() {
1307 }
1308
1309 /**
1310 * Generate a new thumbnail for this activity. This method is called before
1311 * pausing the activity, and should draw into <var>outBitmap</var> the
1312 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1313 * can use the given <var>canvas</var>, which is configured to draw into the
1314 * bitmap, for rendering if desired.
1315 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001316 * <p>The default implementation returns fails and does not draw a thumbnail;
1317 * this will result in the platform creating its own thumbnail if needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 *
1319 * @param outBitmap The bitmap to contain the thumbnail.
1320 * @param canvas Can be used to render into the bitmap.
1321 *
1322 * @return Return true if you have drawn into the bitmap; otherwise after
1323 * you return it will be filled with a default thumbnail.
1324 *
1325 * @see #onCreateDescription
1326 * @see #onSaveInstanceState
1327 * @see #onPause
1328 */
1329 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001330 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
1332
1333 /**
1334 * Generate a new description for this activity. This method is called
1335 * before pausing the activity and can, if desired, return some textual
1336 * description of its current state to be displayed to the user.
1337 *
1338 * <p>The default implementation returns null, which will cause you to
1339 * inherit the description from the previous activity. If all activities
1340 * return null, generally the label of the top activity will be used as the
1341 * description.
1342 *
1343 * @return A description of what the user is doing. It should be short and
1344 * sweet (only a few words).
1345 *
1346 * @see #onCreateThumbnail
1347 * @see #onSaveInstanceState
1348 * @see #onPause
1349 */
1350 public CharSequence onCreateDescription() {
1351 return null;
1352 }
1353
1354 /**
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001355 * This is called when the user is requesting an assist, to build a full
1356 * {@link Intent#ACTION_ASSIST} Intent with all of the context of the current
1357 * application. You can override this method to place into the bundle anything
1358 * you would like to appear in the {@link Intent#EXTRA_ASSIST_CONTEXT} part
1359 * of the assist Intent. The default implementation does nothing.
1360 *
1361 * <p>This function will be called after any global assist callbacks that had
Ying Wang4e0eb222013-04-18 20:39:48 -07001362 * been registered with {@link Application#registerOnProvideAssistDataListener
1363 * Application.registerOnProvideAssistDataListener}.
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001364 */
1365 public void onProvideAssistData(Bundle data) {
1366 }
1367
1368 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 * Called when you are no longer visible to the user. You will next
1370 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1371 * depending on later user activity.
1372 *
1373 * <p>Note that this method may never be called, in low memory situations
1374 * where the system does not have enough memory to keep your activity's
1375 * process running after its {@link #onPause} method is called.
1376 *
1377 * <p><em>Derived classes must call through to the super class's
1378 * implementation of this method. If they do not, an exception will be
1379 * thrown.</em></p>
1380 *
1381 * @see #onRestart
1382 * @see #onResume
1383 * @see #onSaveInstanceState
1384 * @see #onDestroy
1385 */
1386 protected void onStop() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001387 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
Adam Powell50efbed2011-02-08 16:20:15 -08001388 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001389 getApplication().dispatchActivityStopped(this);
Craig Mautner5eda9b32013-07-02 11:58:16 -07001390 mTranslucentCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 mCalled = true;
1392 }
1393
1394 /**
1395 * Perform any final cleanup before an activity is destroyed. This can
1396 * happen either because the activity is finishing (someone called
1397 * {@link #finish} on it, or because the system is temporarily destroying
1398 * this instance of the activity to save space. You can distinguish
1399 * between these two scenarios with the {@link #isFinishing} method.
1400 *
1401 * <p><em>Note: do not count on this method being called as a place for
1402 * saving data! For example, if an activity is editing data in a content
1403 * provider, those edits should be committed in either {@link #onPause} or
1404 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1405 * free resources like threads that are associated with an activity, so
1406 * that a destroyed activity does not leave such things around while the
1407 * rest of its application is still running. There are situations where
1408 * the system will simply kill the activity's hosting process without
1409 * calling this method (or any others) in it, so it should not be used to
1410 * do things that are intended to remain around after the process goes
1411 * away.
1412 *
1413 * <p><em>Derived classes must call through to the super class's
1414 * implementation of this method. If they do not, an exception will be
1415 * thrown.</em></p>
1416 *
1417 * @see #onPause
1418 * @see #onStop
1419 * @see #finish
1420 * @see #isFinishing
1421 */
1422 protected void onDestroy() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001423 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 mCalled = true;
1425
1426 // dismiss any dialogs we are managing.
1427 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 final int numDialogs = mManagedDialogs.size();
1429 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001430 final ManagedDialog md = mManagedDialogs.valueAt(i);
1431 if (md.mDialog.isShowing()) {
1432 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 }
1434 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001435 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437
1438 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001439 synchronized (mManagedCursors) {
1440 int numCursors = mManagedCursors.size();
1441 for (int i = 0; i < numCursors; i++) {
1442 ManagedCursor c = mManagedCursors.get(i);
1443 if (c != null) {
1444 c.mCursor.close();
1445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001447 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 }
Amith Yamasani49860442010-03-17 20:54:10 -07001449
1450 // Close any open search dialog
1451 if (mSearchManager != null) {
1452 mSearchManager.stopSearch();
1453 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001454
1455 getApplication().dispatchActivityDestroyed(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 }
1457
1458 /**
Dianne Hackbornebc15ef2013-10-09 17:36:57 -07001459 * Report to the system that your app is now fully drawn, purely for diagnostic
1460 * purposes (calling it does not impact the visible behavior of the activity).
1461 * This is only used to help instrument application launch times, so that the
1462 * app can report when it is fully in a usable state; without this, the only thing
1463 * the system itself can determine is the point at which the activity's window
1464 * is <em>first</em> drawn and displayed. To participate in app launch time
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07001465 * measurement, you should always call this method after first launch (when
Dianne Hackbornebc15ef2013-10-09 17:36:57 -07001466 * {@link #onCreate(android.os.Bundle)} is called), at the point where you have
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07001467 * entirely drawn your UI and populated with all of the significant data. You
1468 * can safely call this method any time after first launch as well, in which case
1469 * it will simply be ignored.
1470 */
1471 public void reportFullyDrawn() {
1472 if (mDoReportFullyDrawn) {
1473 mDoReportFullyDrawn = false;
1474 try {
1475 ActivityManagerNative.getDefault().reportActivityFullyDrawn(mToken);
1476 } catch (RemoteException e) {
1477 }
1478 }
1479 }
1480
1481 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 * Called by the system when the device configuration changes while your
1483 * activity is running. Note that this will <em>only</em> be called if
1484 * you have selected configurations you would like to handle with the
1485 * {@link android.R.attr#configChanges} attribute in your manifest. If
1486 * any configuration change occurs that is not selected to be reported
1487 * by that attribute, then instead of reporting it the system will stop
1488 * and restart the activity (to have it launched with the new
1489 * configuration).
1490 *
1491 * <p>At the time that this function has been called, your Resources
1492 * object will have been updated to return resource values matching the
1493 * new configuration.
1494 *
1495 * @param newConfig The new device configuration.
1496 */
1497 public void onConfigurationChanged(Configuration newConfig) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001498 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onConfigurationChanged " + this + ": " + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001500
Dianne Hackborn9d071802010-12-08 14:49:15 -08001501 mFragments.dispatchConfigurationChanged(newConfig);
1502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 if (mWindow != null) {
1504 // Pass the configuration changed event to the window
1505 mWindow.onConfigurationChanged(newConfig);
1506 }
Adam Powell45c0b192011-07-28 15:11:57 -07001507
1508 if (mActionBar != null) {
1509 // Do this last; the action bar will need to access
1510 // view changes from above.
1511 mActionBar.onConfigurationChanged(newConfig);
1512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 }
1514
1515 /**
1516 * If this activity is being destroyed because it can not handle a
1517 * configuration parameter being changed (and thus its
1518 * {@link #onConfigurationChanged(Configuration)} method is
1519 * <em>not</em> being called), then you can use this method to discover
1520 * the set of changes that have occurred while in the process of being
1521 * destroyed. Note that there is no guarantee that these will be
1522 * accurate (other changes could have happened at any time), so you should
1523 * only use this as an optimization hint.
1524 *
1525 * @return Returns a bit field of the configuration parameters that are
1526 * changing, as defined by the {@link android.content.res.Configuration}
1527 * class.
1528 */
1529 public int getChangingConfigurations() {
1530 return mConfigChangeFlags;
1531 }
1532
1533 /**
1534 * Retrieve the non-configuration instance data that was previously
1535 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1536 * be available from the initial {@link #onCreate} and
1537 * {@link #onStart} calls to the new instance, allowing you to extract
1538 * any useful dynamic state from the previous instance.
1539 *
1540 * <p>Note that the data you retrieve here should <em>only</em> be used
1541 * as an optimization for handling configuration changes. You should always
1542 * be able to handle getting a null pointer back, and an activity must
1543 * still be able to restore itself to its previous state (through the
1544 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1545 * function returns null.
1546 *
1547 * @return Returns the object previously returned by
1548 * {@link #onRetainNonConfigurationInstance()}.
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07001549 *
1550 * @deprecated Use the new {@link Fragment} API
1551 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
1552 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07001554 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001556 return mLastNonConfigurationInstances != null
1557 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 }
1559
1560 /**
1561 * Called by the system, as part of destroying an
1562 * activity due to a configuration change, when it is known that a new
1563 * instance will immediately be created for the new configuration. You
1564 * can return any object you like here, including the activity instance
1565 * itself, which can later be retrieved by calling
1566 * {@link #getLastNonConfigurationInstance()} in the new activity
1567 * instance.
1568 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001569 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1570 * or later, consider instead using a {@link Fragment} with
1571 * {@link Fragment#setRetainInstance(boolean)
1572 * Fragment.setRetainInstance(boolean}.</em>
1573 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 * <p>This function is called purely as an optimization, and you must
1575 * not rely on it being called. When it is called, a number of guarantees
1576 * will be made to help optimize configuration switching:
1577 * <ul>
1578 * <li> The function will be called between {@link #onStop} and
1579 * {@link #onDestroy}.
1580 * <li> A new instance of the activity will <em>always</em> be immediately
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001581 * created after this one's {@link #onDestroy()} is called. In particular,
1582 * <em>no</em> messages will be dispatched during this time (when the returned
1583 * object does not have an activity to be associated with).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 * <li> The object you return here will <em>always</em> be available from
1585 * the {@link #getLastNonConfigurationInstance()} method of the following
1586 * activity instance as described there.
1587 * </ul>
1588 *
1589 * <p>These guarantees are designed so that an activity can use this API
1590 * to propagate extensive state from the old to new activity instance, from
1591 * loaded bitmaps, to network connections, to evenly actively running
1592 * threads. Note that you should <em>not</em> propagate any data that
1593 * may change based on the configuration, including any data loaded from
1594 * resources such as strings, layouts, or drawables.
1595 *
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001596 * <p>The guarantee of no message handling during the switch to the next
1597 * activity simplifies use with active objects. For example if your retained
1598 * state is an {@link android.os.AsyncTask} you are guaranteed that its
1599 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
1600 * not be called from the call here until you execute the next instance's
1601 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
1602 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
1603 * running in a separate thread.)
1604 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 * @return Return any Object holding the desired state to propagate to the
1606 * next activity instance.
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07001607 *
1608 * @deprecated Use the new {@link Fragment} API
1609 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
1610 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 */
1612 public Object onRetainNonConfigurationInstance() {
1613 return null;
1614 }
1615
1616 /**
1617 * Retrieve the non-configuration instance data that was previously
1618 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1619 * be available from the initial {@link #onCreate} and
1620 * {@link #onStart} calls to the new instance, allowing you to extract
1621 * any useful dynamic state from the previous instance.
1622 *
1623 * <p>Note that the data you retrieve here should <em>only</em> be used
1624 * as an optimization for handling configuration changes. You should always
1625 * be able to handle getting a null pointer back, and an activity must
1626 * still be able to restore itself to its previous state (through the
1627 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1628 * function returns null.
1629 *
1630 * @return Returns the object previously returned by
1631 * {@link #onRetainNonConfigurationChildInstances()}
1632 */
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001633 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1634 return mLastNonConfigurationInstances != null
1635 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 }
1637
1638 /**
1639 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1640 * it should return either a mapping from child activity id strings to arbitrary objects,
1641 * or null. This method is intended to be used by Activity framework subclasses that control a
1642 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1643 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1644 */
1645 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1646 return null;
1647 }
1648
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001649 NonConfigurationInstances retainNonConfigurationInstances() {
1650 Object activity = onRetainNonConfigurationInstance();
1651 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1652 ArrayList<Fragment> fragments = mFragments.retainNonConfig();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001653 boolean retainLoaders = false;
1654 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001655 // prune out any loader managers that were already stopped and so
Dianne Hackborn2707d602010-07-09 18:01:20 -07001656 // have nothing useful to retain.
Dianne Hackborn3e82ba12013-07-16 13:23:55 -07001657 final int N = mAllLoaderManagers.size();
1658 LoaderManagerImpl loaders[] = new LoaderManagerImpl[N];
1659 for (int i=N-1; i>=0; i--) {
1660 loaders[i] = mAllLoaderManagers.valueAt(i);
1661 }
1662 for (int i=0; i<N; i++) {
1663 LoaderManagerImpl lm = loaders[i];
1664 if (lm.mRetaining) {
1665 retainLoaders = true;
1666 } else {
1667 lm.doDestroy();
1668 mAllLoaderManagers.remove(lm.mWho);
Dianne Hackborn2707d602010-07-09 18:01:20 -07001669 }
1670 }
1671 }
1672 if (activity == null && children == null && fragments == null && !retainLoaders) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001673 return null;
1674 }
1675
1676 NonConfigurationInstances nci = new NonConfigurationInstances();
1677 nci.activity = activity;
1678 nci.children = children;
1679 nci.fragments = fragments;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001680 nci.loaders = mAllLoaderManagers;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001681 return nci;
1682 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 public void onLowMemory() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001685 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onLowMemory " + this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 mCalled = true;
Dianne Hackborn9d071802010-12-08 14:49:15 -08001687 mFragments.dispatchLowMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001689
1690 public void onTrimMemory(int level) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001691 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onTrimMemory " + this + ": " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001692 mCalled = true;
1693 mFragments.dispatchTrimMemory(level);
1694 }
1695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 /**
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07001697 * Return the FragmentManager for interacting with fragments associated
1698 * with this activity.
1699 */
1700 public FragmentManager getFragmentManager() {
1701 return mFragments;
1702 }
1703
Dianne Hackborn62bea2f2012-09-04 18:48:15 -07001704 void invalidateFragment(String who) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001705 //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001706 if (mAllLoaderManagers != null) {
Dianne Hackborn62bea2f2012-09-04 18:48:15 -07001707 LoaderManagerImpl lm = mAllLoaderManagers.get(who);
Dianne Hackbornd04ad542011-07-25 16:16:15 -07001708 if (lm != null && !lm.mRetaining) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001709 lm.doDestroy();
Dianne Hackborn62bea2f2012-09-04 18:48:15 -07001710 mAllLoaderManagers.remove(who);
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001711 }
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001712 }
1713 }
1714
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001715 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07001716 * Called when a Fragment is being attached to this activity, immediately
1717 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1718 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1719 */
1720 public void onAttachFragment(Fragment fragment) {
1721 }
1722
1723 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 * Wrapper around
1725 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1726 * that gives the resulting {@link Cursor} to call
1727 * {@link #startManagingCursor} so that the activity will manage its
1728 * lifecycle for you.
1729 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001730 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1731 * or later, consider instead using {@link LoaderManager} instead, available
1732 * via {@link #getLoaderManager()}.</em>
1733 *
Joe Fernandez8ef69702011-09-02 14:32:22 -07001734 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
1735 * this method, because the activity will do that for you at the appropriate time. However, if
1736 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
1737 * not</em> automatically close the cursor and, in that case, you must call
1738 * {@link Cursor#close()}.</p>
1739 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 * @param uri The URI of the content provider to query.
1741 * @param projection List of columns to return.
1742 * @param selection SQL WHERE clause.
1743 * @param sortOrder SQL ORDER BY clause.
1744 *
1745 * @return The Cursor that was returned by query().
1746 *
1747 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1748 * @see #startManagingCursor
1749 * @hide
Jason parks6ed50de2010-08-25 10:18:50 -05001750 *
1751 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 */
Jason parks6ed50de2010-08-25 10:18:50 -05001753 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001754 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1755 String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1757 if (c != null) {
1758 startManagingCursor(c);
1759 }
1760 return c;
1761 }
1762
1763 /**
1764 * Wrapper around
1765 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1766 * that gives the resulting {@link Cursor} to call
1767 * {@link #startManagingCursor} so that the activity will manage its
1768 * lifecycle for you.
1769 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001770 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1771 * or later, consider instead using {@link LoaderManager} instead, available
1772 * via {@link #getLoaderManager()}.</em>
1773 *
Joe Fernandez8ef69702011-09-02 14:32:22 -07001774 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
1775 * this method, because the activity will do that for you at the appropriate time. However, if
1776 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
1777 * not</em> automatically close the cursor and, in that case, you must call
1778 * {@link Cursor#close()}.</p>
1779 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 * @param uri The URI of the content provider to query.
1781 * @param projection List of columns to return.
1782 * @param selection SQL WHERE clause.
1783 * @param selectionArgs The arguments to selection, if any ?s are pesent
1784 * @param sortOrder SQL ORDER BY clause.
1785 *
1786 * @return The Cursor that was returned by query().
1787 *
1788 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1789 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001790 *
1791 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 */
Jason parks6ed50de2010-08-25 10:18:50 -05001793 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001794 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1795 String[] selectionArgs, String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1797 if (c != null) {
1798 startManagingCursor(c);
1799 }
1800 return c;
1801 }
1802
1803 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 * This method allows the activity to take care of managing the given
1805 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1806 * That is, when the activity is stopped it will automatically call
1807 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1808 * it will call {@link Cursor#requery} for you. When the activity is
1809 * destroyed, all managed Cursors will be closed automatically.
1810 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001811 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1812 * or later, consider instead using {@link LoaderManager} instead, available
1813 * via {@link #getLoaderManager()}.</em>
1814 *
Joe Fernandez8ef69702011-09-02 14:32:22 -07001815 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on cursor obtained from
1816 * {@link #managedQuery}, because the activity will do that for you at the appropriate time.
1817 * However, if you call {@link #stopManagingCursor} on a cursor from a managed query, the system
1818 * <em>will not</em> automatically close the cursor and, in that case, you must call
1819 * {@link Cursor#close()}.</p>
1820 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 * @param c The Cursor to be managed.
1822 *
1823 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1824 * @see #stopManagingCursor
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07001825 *
1826 * @deprecated Use the new {@link android.content.CursorLoader} class with
1827 * {@link LoaderManager} instead; this is also
1828 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 */
Jason parks6ed50de2010-08-25 10:18:50 -05001830 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 public void startManagingCursor(Cursor c) {
1832 synchronized (mManagedCursors) {
1833 mManagedCursors.add(new ManagedCursor(c));
1834 }
1835 }
1836
1837 /**
1838 * Given a Cursor that was previously given to
1839 * {@link #startManagingCursor}, stop the activity's management of that
1840 * cursor.
1841 *
Joe Fernandez8ef69702011-09-02 14:32:22 -07001842 * <p><strong>Warning:</strong> After calling this method on a cursor from a managed query,
1843 * the system <em>will not</em> automatically close the cursor and you must call
1844 * {@link Cursor#close()}.</p>
1845 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 * @param c The Cursor that was being managed.
1847 *
1848 * @see #startManagingCursor
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07001849 *
1850 * @deprecated Use the new {@link android.content.CursorLoader} class with
1851 * {@link LoaderManager} instead; this is also
1852 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 */
Jason parks6ed50de2010-08-25 10:18:50 -05001854 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 public void stopManagingCursor(Cursor c) {
1856 synchronized (mManagedCursors) {
1857 final int N = mManagedCursors.size();
1858 for (int i=0; i<N; i++) {
1859 ManagedCursor mc = mManagedCursors.get(i);
1860 if (mc.mCursor == c) {
1861 mManagedCursors.remove(i);
1862 break;
1863 }
1864 }
1865 }
1866 }
1867
1868 /**
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07001869 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
1870 * this is a no-op.
Dianne Hackborn4f3867e2010-12-14 22:09:51 -08001871 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 */
Dianne Hackbornd3efa392010-09-01 17:34:12 -07001873 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 public void setPersistent(boolean isPersistent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 }
1876
1877 /**
1878 * Finds a view that was identified by the id attribute from the XML that
1879 * was processed in {@link #onCreate}.
1880 *
1881 * @return The view if found or null otherwise.
1882 */
1883 public View findViewById(int id) {
1884 return getWindow().findViewById(id);
1885 }
Adam Powell33b97432010-04-20 10:01:14 -07001886
1887 /**
1888 * Retrieve a reference to this activity's ActionBar.
Adam Powell42c0fe82010-08-10 16:36:56 -07001889 *
Adam Powell33b97432010-04-20 10:01:14 -07001890 * @return The Activity's ActionBar, or null if it does not have one.
1891 */
1892 public ActionBar getActionBar() {
Adam Powell42c0fe82010-08-10 16:36:56 -07001893 initActionBar();
Adam Powell33b97432010-04-20 10:01:14 -07001894 return mActionBar;
1895 }
1896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 /**
Adam Powell33b97432010-04-20 10:01:14 -07001898 * Creates a new ActionBar, locates the inflated ActionBarView,
1899 * initializes the ActionBar with the view, and sets mActionBar.
1900 */
1901 private void initActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07001902 Window window = getWindow();
Adam Powella593d982011-05-13 14:09:54 -07001903
1904 // Initializing the window decor can change window feature flags.
1905 // Make sure that we have the correct set before performing the test below.
1906 window.getDecorView();
1907
Adam Powell9b4c8042010-08-10 15:36:44 -07001908 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07001909 return;
1910 }
Adam Powell04fe6eb2013-05-31 14:39:48 -07001911
Adam Powell661c9082010-07-02 10:09:44 -07001912 mActionBar = new ActionBarImpl(this);
Adam Powelldd8fab22012-03-22 17:47:27 -07001913 mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
Adam Powell04fe6eb2013-05-31 14:39:48 -07001914
1915 mWindow.setDefaultIcon(mActivityInfo.getIconResource());
1916 mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
Adam Powell33b97432010-04-20 10:01:14 -07001917 }
1918
1919 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 * Set the activity content from a layout resource. The resource will be
1921 * inflated, adding all top-level views to the activity.
Romain Guy482b34a2011-01-20 10:59:28 -08001922 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 * @param layoutResID Resource ID to be inflated.
Romain Guy482b34a2011-01-20 10:59:28 -08001924 *
1925 * @see #setContentView(android.view.View)
1926 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 */
1928 public void setContentView(int layoutResID) {
1929 getWindow().setContentView(layoutResID);
Adam Powell33b97432010-04-20 10:01:14 -07001930 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 }
1932
1933 /**
1934 * Set the activity content to an explicit view. This view is placed
1935 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a2011-01-20 10:59:28 -08001936 * view hierarchy. When calling this method, the layout parameters of the
1937 * specified view are ignored. Both the width and the height of the view are
1938 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
1939 * your own layout parameters, invoke
1940 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
1941 * instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 *
1943 * @param view The desired content to display.
Romain Guy482b34a2011-01-20 10:59:28 -08001944 *
1945 * @see #setContentView(int)
1946 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 */
1948 public void setContentView(View view) {
1949 getWindow().setContentView(view);
Adam Powell33b97432010-04-20 10:01:14 -07001950 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 }
1952
1953 /**
1954 * Set the activity content to an explicit view. This view is placed
1955 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a2011-01-20 10:59:28 -08001956 * view hierarchy.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 *
1958 * @param view The desired content to display.
1959 * @param params Layout parameters for the view.
Romain Guy482b34a2011-01-20 10:59:28 -08001960 *
1961 * @see #setContentView(android.view.View)
1962 * @see #setContentView(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 */
1964 public void setContentView(View view, ViewGroup.LayoutParams params) {
1965 getWindow().setContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001966 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 }
1968
1969 /**
1970 * Add an additional content view to the activity. Added after any existing
1971 * ones in the activity -- existing views are NOT removed.
1972 *
1973 * @param view The desired content to display.
1974 * @param params Layout parameters for the view.
1975 */
1976 public void addContentView(View view, ViewGroup.LayoutParams params) {
1977 getWindow().addContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001978 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 }
1980
1981 /**
Dianne Hackborncfaf8872011-01-18 13:57:54 -08001982 * Sets whether this activity is finished when touched outside its window's
1983 * bounds.
1984 */
1985 public void setFinishOnTouchOutside(boolean finish) {
1986 mWindow.setCloseOnTouchOutside(finish);
1987 }
1988
1989 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1991 * keys.
1992 *
1993 * @see #setDefaultKeyMode
1994 */
1995 static public final int DEFAULT_KEYS_DISABLE = 0;
1996 /**
1997 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1998 * key handling.
1999 *
2000 * @see #setDefaultKeyMode
2001 */
2002 static public final int DEFAULT_KEYS_DIALER = 1;
2003 /**
2004 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
2005 * default key handling.
2006 *
2007 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
2008 *
2009 * @see #setDefaultKeyMode
2010 */
2011 static public final int DEFAULT_KEYS_SHORTCUT = 2;
2012 /**
2013 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2014 * will start an application-defined search. (If the application or activity does not
2015 * actually define a search, the the keys will be ignored.)
2016 *
2017 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2018 *
2019 * @see #setDefaultKeyMode
2020 */
2021 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
2022
2023 /**
2024 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2025 * will start a global search (typically web search, but some platforms may define alternate
2026 * methods for global search)
2027 *
2028 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2029 *
2030 * @see #setDefaultKeyMode
2031 */
2032 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
2033
2034 /**
2035 * Select the default key handling for this activity. This controls what
2036 * will happen to key events that are not otherwise handled. The default
2037 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
2038 * floor. Other modes allow you to launch the dialer
2039 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
2040 * menu without requiring the menu key be held down
2041 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
2042 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
2043 *
2044 * <p>Note that the mode selected here does not impact the default
2045 * handling of system keys, such as the "back" and "menu" keys, and your
2046 * activity and its views always get a first chance to receive and handle
2047 * all application keys.
2048 *
2049 * @param mode The desired default key mode constant.
2050 *
2051 * @see #DEFAULT_KEYS_DISABLE
2052 * @see #DEFAULT_KEYS_DIALER
2053 * @see #DEFAULT_KEYS_SHORTCUT
2054 * @see #DEFAULT_KEYS_SEARCH_LOCAL
2055 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
2056 * @see #onKeyDown
2057 */
2058 public final void setDefaultKeyMode(int mode) {
2059 mDefaultKeyMode = mode;
2060
2061 // Some modes use a SpannableStringBuilder to track & dispatch input events
2062 // This list must remain in sync with the switch in onKeyDown()
2063 switch (mode) {
2064 case DEFAULT_KEYS_DISABLE:
2065 case DEFAULT_KEYS_SHORTCUT:
2066 mDefaultKeySsb = null; // not used in these modes
2067 break;
2068 case DEFAULT_KEYS_DIALER:
2069 case DEFAULT_KEYS_SEARCH_LOCAL:
2070 case DEFAULT_KEYS_SEARCH_GLOBAL:
2071 mDefaultKeySsb = new SpannableStringBuilder();
2072 Selection.setSelection(mDefaultKeySsb,0);
2073 break;
2074 default:
2075 throw new IllegalArgumentException();
2076 }
2077 }
2078
2079 /**
2080 * Called when a key was pressed down and not handled by any of the views
2081 * inside of the activity. So, for example, key presses while the cursor
2082 * is inside a TextView will not trigger the event (unless it is a navigation
2083 * to another object) because TextView handles its own key presses.
2084 *
2085 * <p>If the focused view didn't want this event, this method is called.
2086 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07002087 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
2088 * by calling {@link #onBackPressed()}, though the behavior varies based
2089 * on the application compatibility mode: for
2090 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
2091 * it will set up the dispatch to call {@link #onKeyUp} where the action
2092 * will be performed; for earlier applications, it will perform the
2093 * action immediately in on-down, as those versions of the platform
2094 * behaved.
2095 *
2096 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002097 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 *
2099 * @return Return <code>true</code> to prevent this event from being propagated
2100 * further, or <code>false</code> to indicate that you have not handled
2101 * this event and it should continue to be propagated.
2102 * @see #onKeyUp
2103 * @see android.view.KeyEvent
2104 */
2105 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002106 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002107 if (getApplicationInfo().targetSdkVersion
2108 >= Build.VERSION_CODES.ECLAIR) {
2109 event.startTracking();
2110 } else {
2111 onBackPressed();
2112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 return true;
2114 }
2115
2116 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
2117 return false;
2118 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002119 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
2120 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
2121 return true;
2122 }
2123 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 } else {
2125 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
2126 boolean clearSpannable = false;
2127 boolean handled;
2128 if ((event.getRepeatCount() != 0) || event.isSystem()) {
2129 clearSpannable = true;
2130 handled = false;
2131 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002132 handled = TextKeyListener.getInstance().onKeyDown(
2133 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 if (handled && mDefaultKeySsb.length() > 0) {
2135 // something useable has been typed - dispatch it now.
2136
2137 final String str = mDefaultKeySsb.toString();
2138 clearSpannable = true;
2139
2140 switch (mDefaultKeyMode) {
2141 case DEFAULT_KEYS_DIALER:
2142 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
2143 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2144 startActivity(intent);
2145 break;
2146 case DEFAULT_KEYS_SEARCH_LOCAL:
2147 startSearch(str, false, null, false);
2148 break;
2149 case DEFAULT_KEYS_SEARCH_GLOBAL:
2150 startSearch(str, false, null, true);
2151 break;
2152 }
2153 }
2154 }
2155 if (clearSpannable) {
2156 mDefaultKeySsb.clear();
2157 mDefaultKeySsb.clearSpans();
2158 Selection.setSelection(mDefaultKeySsb,0);
2159 }
2160 return handled;
2161 }
2162 }
2163
2164 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002165 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2166 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2167 * the event).
2168 */
2169 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2170 return false;
2171 }
2172
2173 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 * Called when a key was released and not handled by any of the views
2175 * inside of the activity. So, for example, key presses while the cursor
2176 * is inside a TextView will not trigger the event (unless it is a navigation
2177 * to another object) because TextView handles its own key presses.
2178 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002179 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2180 * and go back.
2181 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 * @return Return <code>true</code> to prevent this event from being propagated
2183 * further, or <code>false</code> to indicate that you have not handled
2184 * this event and it should continue to be propagated.
2185 * @see #onKeyDown
2186 * @see KeyEvent
2187 */
2188 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002189 if (getApplicationInfo().targetSdkVersion
2190 >= Build.VERSION_CODES.ECLAIR) {
2191 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2192 && !event.isCanceled()) {
2193 onBackPressed();
2194 return true;
2195 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 return false;
2198 }
2199
2200 /**
2201 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2202 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2203 * the event).
2204 */
2205 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2206 return false;
2207 }
2208
2209 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002210 * Called when the activity has detected the user's press of the back
2211 * key. The default implementation simply finishes the current activity,
2212 * but you can override this to do whatever you want.
2213 */
2214 public void onBackPressed() {
Dianne Hackborn3a57fb92010-11-15 17:58:52 -08002215 if (!mFragments.popBackStackImmediate()) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002216 finish();
2217 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002218 }
Jeff Brown64da12a2011-01-04 19:57:47 -08002219
2220 /**
2221 * Called when a key shortcut event is not handled by any of the views in the Activity.
2222 * Override this method to implement global key shortcuts for the Activity.
2223 * Key shortcuts can also be implemented by setting the
2224 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
2225 *
2226 * @param keyCode The value in event.getKeyCode().
2227 * @param event Description of the key event.
2228 * @return True if the key shortcut was handled.
2229 */
2230 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2231 return false;
2232 }
2233
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002234 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 * Called when a touch screen event was not handled by any of the views
2236 * under it. This is most useful to process touch events that happen
2237 * outside of your window bounds, where there is no view to receive it.
2238 *
2239 * @param event The touch screen event being processed.
2240 *
2241 * @return Return true if you have consumed the event, false if you haven't.
2242 * The default implementation always returns false.
2243 */
2244 public boolean onTouchEvent(MotionEvent event) {
Dianne Hackborncfaf8872011-01-18 13:57:54 -08002245 if (mWindow.shouldCloseOnTouch(this, event)) {
2246 finish();
2247 return true;
2248 }
2249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 return false;
2251 }
2252
2253 /**
2254 * Called when the trackball was moved and not handled by any of the
2255 * views inside of the activity. So, for example, if the trackball moves
2256 * while focus is on a button, you will receive a call here because
2257 * buttons do not normally do anything with trackball events. The call
2258 * here happens <em>before</em> trackball movements are converted to
2259 * DPAD key events, which then get sent back to the view hierarchy, and
2260 * will be processed at the point for things like focus navigation.
2261 *
2262 * @param event The trackball event being processed.
2263 *
2264 * @return Return true if you have consumed the event, false if you haven't.
2265 * The default implementation always returns false.
2266 */
2267 public boolean onTrackballEvent(MotionEvent event) {
2268 return false;
2269 }
Jeff Browncb1404e2011-01-15 18:14:15 -08002270
2271 /**
2272 * Called when a generic motion event was not handled by any of the
2273 * views inside of the activity.
2274 * <p>
Jeff Brown33bbfd22011-02-24 20:55:35 -08002275 * Generic motion events describe joystick movements, mouse hovers, track pad
2276 * touches, scroll wheel movements and other input events. The
Jeff Browncb1404e2011-01-15 18:14:15 -08002277 * {@link MotionEvent#getSource() source} of the motion event specifies
2278 * the class of input that was received. Implementations of this method
2279 * must examine the bits in the source before processing the event.
2280 * The following code example shows how this is done.
Jeff Brown33bbfd22011-02-24 20:55:35 -08002281 * </p><p>
2282 * Generic motion events with source class
2283 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
2284 * are delivered to the view under the pointer. All other generic motion events are
2285 * delivered to the focused view.
2286 * </p><p>
2287 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
2288 * handle this event.
Jeff Browncb1404e2011-01-15 18:14:15 -08002289 * </p>
Jeff Browncb1404e2011-01-15 18:14:15 -08002290 *
2291 * @param event The generic motion event being processed.
2292 *
2293 * @return Return true if you have consumed the event, false if you haven't.
2294 * The default implementation always returns false.
2295 */
2296 public boolean onGenericMotionEvent(MotionEvent event) {
2297 return false;
2298 }
2299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002300 /**
2301 * Called whenever a key, touch, or trackball event is dispatched to the
2302 * activity. Implement this method if you wish to know that the user has
2303 * interacted with the device in some way while your activity is running.
2304 * This callback and {@link #onUserLeaveHint} are intended to help
2305 * activities manage status bar notifications intelligently; specifically,
2306 * for helping activities determine the proper time to cancel a notfication.
2307 *
2308 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2309 * be accompanied by calls to {@link #onUserInteraction}. This
2310 * ensures that your activity will be told of relevant user activity such
2311 * as pulling down the notification pane and touching an item there.
2312 *
2313 * <p>Note that this callback will be invoked for the touch down action
2314 * that begins a touch gesture, but may not be invoked for the touch-moved
2315 * and touch-up actions that follow.
2316 *
2317 * @see #onUserLeaveHint()
2318 */
2319 public void onUserInteraction() {
2320 }
2321
2322 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2323 // Update window manager if: we have a view, that view is
2324 // attached to its parent (which will be a RootView), and
2325 // this activity is not embedded.
2326 if (mParent == null) {
2327 View decor = mDecor;
2328 if (decor != null && decor.getParent() != null) {
2329 getWindowManager().updateViewLayout(decor, params);
2330 }
2331 }
2332 }
2333
2334 public void onContentChanged() {
2335 }
2336
2337 /**
2338 * Called when the current {@link Window} of the activity gains or loses
2339 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002340 * to the user. The default implementation clears the key tracking
2341 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002343 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 * is managed independently of activity lifecycles. As such, while focus
2345 * changes will generally have some relation to lifecycle changes (an
2346 * activity that is stopped will not generally get window focus), you
2347 * should not rely on any particular order between the callbacks here and
2348 * those in the other lifecycle methods such as {@link #onResume}.
2349 *
2350 * <p>As a general rule, however, a resumed activity will have window
2351 * focus... unless it has displayed other dialogs or popups that take
2352 * input focus, in which case the activity itself will not have focus
2353 * when the other windows have it. Likewise, the system may display
2354 * system-level windows (such as the status bar notification panel or
2355 * a system alert) which will temporarily take window input focus without
2356 * pausing the foreground activity.
2357 *
2358 * @param hasFocus Whether the window of this activity has focus.
2359 *
2360 * @see #hasWindowFocus()
2361 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002362 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 */
2364 public void onWindowFocusChanged(boolean hasFocus) {
2365 }
2366
2367 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002368 * Called when the main window associated with the activity has been
2369 * attached to the window manager.
2370 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2371 * for more information.
2372 * @see View#onAttachedToWindow
2373 */
2374 public void onAttachedToWindow() {
2375 }
2376
2377 /**
2378 * Called when the main window associated with the activity has been
2379 * detached from the window manager.
2380 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2381 * for more information.
2382 * @see View#onDetachedFromWindow
2383 */
2384 public void onDetachedFromWindow() {
2385 }
2386
2387 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 * Returns true if this activity's <em>main</em> window currently has window focus.
2389 * Note that this is not the same as the view itself having focus.
2390 *
2391 * @return True if this activity's main window currently has window focus.
2392 *
2393 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2394 */
2395 public boolean hasWindowFocus() {
2396 Window w = getWindow();
2397 if (w != null) {
2398 View d = w.getDecorView();
2399 if (d != null) {
2400 return d.hasWindowFocus();
2401 }
2402 }
2403 return false;
2404 }
2405
2406 /**
2407 * Called to process key events. You can override this to intercept all
2408 * key events before they are dispatched to the window. Be sure to call
2409 * this implementation for key events that should be handled normally.
2410 *
2411 * @param event The key event.
2412 *
2413 * @return boolean Return true if this event was consumed.
2414 */
2415 public boolean dispatchKeyEvent(KeyEvent event) {
2416 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002417 Window win = getWindow();
2418 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 return true;
2420 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002421 View decor = mDecor;
2422 if (decor == null) decor = win.getDecorView();
2423 return event.dispatch(this, decor != null
2424 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 }
2426
2427 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08002428 * Called to process a key shortcut event.
2429 * You can override this to intercept all key shortcut events before they are
2430 * dispatched to the window. Be sure to call this implementation for key shortcut
2431 * events that should be handled normally.
2432 *
2433 * @param event The key shortcut event.
2434 * @return True if this event was consumed.
2435 */
2436 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
2437 onUserInteraction();
2438 if (getWindow().superDispatchKeyShortcutEvent(event)) {
2439 return true;
2440 }
2441 return onKeyShortcut(event.getKeyCode(), event);
2442 }
2443
2444 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 * Called to process touch screen events. You can override this to
2446 * intercept all touch screen events before they are dispatched to the
2447 * window. Be sure to call this implementation for touch screen events
2448 * that should be handled normally.
2449 *
2450 * @param ev The touch screen event.
2451 *
2452 * @return boolean Return true if this event was consumed.
2453 */
2454 public boolean dispatchTouchEvent(MotionEvent ev) {
2455 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2456 onUserInteraction();
2457 }
2458 if (getWindow().superDispatchTouchEvent(ev)) {
2459 return true;
2460 }
2461 return onTouchEvent(ev);
2462 }
2463
2464 /**
2465 * Called to process trackball events. You can override this to
2466 * intercept all trackball events before they are dispatched to the
2467 * window. Be sure to call this implementation for trackball events
2468 * that should be handled normally.
2469 *
2470 * @param ev The trackball event.
2471 *
2472 * @return boolean Return true if this event was consumed.
2473 */
2474 public boolean dispatchTrackballEvent(MotionEvent ev) {
2475 onUserInteraction();
2476 if (getWindow().superDispatchTrackballEvent(ev)) {
2477 return true;
2478 }
2479 return onTrackballEvent(ev);
2480 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002481
Jeff Browncb1404e2011-01-15 18:14:15 -08002482 /**
2483 * Called to process generic motion events. You can override this to
2484 * intercept all generic motion events before they are dispatched to the
2485 * window. Be sure to call this implementation for generic motion events
2486 * that should be handled normally.
2487 *
2488 * @param ev The generic motion event.
2489 *
2490 * @return boolean Return true if this event was consumed.
2491 */
2492 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
2493 onUserInteraction();
2494 if (getWindow().superDispatchGenericMotionEvent(ev)) {
2495 return true;
2496 }
2497 return onGenericMotionEvent(ev);
2498 }
2499
svetoslavganov75986cf2009-05-14 22:28:01 -07002500 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2501 event.setClassName(getClass().getName());
2502 event.setPackageName(getPackageName());
2503
2504 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002505 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2506 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002507 event.setFullScreen(isFullScreen);
2508
2509 CharSequence title = getTitle();
2510 if (!TextUtils.isEmpty(title)) {
2511 event.getText().add(title);
2512 }
2513
2514 return true;
2515 }
2516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 /**
2518 * Default implementation of
2519 * {@link android.view.Window.Callback#onCreatePanelView}
2520 * for activities. This
2521 * simply returns null so that all panel sub-windows will have the default
2522 * menu behavior.
2523 */
2524 public View onCreatePanelView(int featureId) {
2525 return null;
2526 }
2527
2528 /**
2529 * Default implementation of
2530 * {@link android.view.Window.Callback#onCreatePanelMenu}
2531 * for activities. This calls through to the new
2532 * {@link #onCreateOptionsMenu} method for the
2533 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2534 * so that subclasses of Activity don't need to deal with feature codes.
2535 */
2536 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2537 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84b2010-06-08 18:04:35 -07002538 boolean show = onCreateOptionsMenu(menu);
2539 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2540 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 }
2542 return false;
2543 }
2544
2545 /**
2546 * Default implementation of
2547 * {@link android.view.Window.Callback#onPreparePanel}
2548 * for activities. This
2549 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2550 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2551 * panel, so that subclasses of
2552 * Activity don't need to deal with feature codes.
2553 */
2554 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2555 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2556 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84b2010-06-08 18:04:35 -07002557 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
Adam Powellef31e7c2012-05-08 09:59:40 -07002558 return goforit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 }
2560 return true;
2561 }
2562
2563 /**
2564 * {@inheritDoc}
2565 *
2566 * @return The default implementation returns true.
2567 */
2568 public boolean onMenuOpened(int featureId, Menu menu) {
Adam Powell8515ee82010-11-30 14:09:55 -08002569 if (featureId == Window.FEATURE_ACTION_BAR) {
Adam Powell763cbb12011-03-01 10:45:34 -08002570 initActionBar();
Adam Powell049dd3d2010-12-02 13:43:59 -08002571 if (mActionBar != null) {
2572 mActionBar.dispatchMenuVisibilityChanged(true);
2573 } else {
2574 Log.e(TAG, "Tried to open action bar menu with no action bar");
2575 }
Adam Powell8515ee82010-11-30 14:09:55 -08002576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 return true;
2578 }
2579
2580 /**
2581 * Default implementation of
2582 * {@link android.view.Window.Callback#onMenuItemSelected}
2583 * for activities. This calls through to the new
2584 * {@link #onOptionsItemSelected} method for the
2585 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2586 * panel, so that subclasses of
2587 * Activity don't need to deal with feature codes.
2588 */
2589 public boolean onMenuItemSelected(int featureId, MenuItem item) {
zobject686a8052012-12-14 21:11:08 +09002590 CharSequence titleCondensed = item.getTitleCondensed();
2591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 switch (featureId) {
2593 case Window.FEATURE_OPTIONS_PANEL:
2594 // Put event logging here so it gets called even if subclass
2595 // doesn't call through to superclass's implmeentation of each
2596 // of these methods below
zobject686a8052012-12-14 21:11:08 +09002597 if(titleCondensed != null) {
2598 EventLog.writeEvent(50000, 0, titleCondensed.toString());
2599 }
Dianne Hackbornb31e84b2010-06-08 18:04:35 -07002600 if (onOptionsItemSelected(item)) {
2601 return true;
2602 }
Adam Powell04d58112012-04-09 10:22:12 -07002603 if (mFragments.dispatchOptionsItemSelected(item)) {
2604 return true;
2605 }
2606 if (item.getItemId() == android.R.id.home && mActionBar != null &&
2607 (mActionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
2608 if (mParent == null) {
Adam Powell07304f52012-05-07 17:32:44 -07002609 return onNavigateUp();
Adam Powell04d58112012-04-09 10:22:12 -07002610 } else {
Adam Powell07304f52012-05-07 17:32:44 -07002611 return mParent.onNavigateUpFromChild(this);
Adam Powell04d58112012-04-09 10:22:12 -07002612 }
Adam Powell04d58112012-04-09 10:22:12 -07002613 }
2614 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615
2616 case Window.FEATURE_CONTEXT_MENU:
zobject686a8052012-12-14 21:11:08 +09002617 if(titleCondensed != null) {
2618 EventLog.writeEvent(50000, 1, titleCondensed.toString());
2619 }
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07002620 if (onContextItemSelected(item)) {
2621 return true;
2622 }
2623 return mFragments.dispatchContextItemSelected(item);
Adam Powell8515ee82010-11-30 14:09:55 -08002624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 default:
2626 return false;
2627 }
2628 }
2629
2630 /**
2631 * Default implementation of
2632 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2633 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2634 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2635 * so that subclasses of Activity don't need to deal with feature codes.
2636 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2637 * {@link #onContextMenuClosed(Menu)} will be called.
2638 */
2639 public void onPanelClosed(int featureId, Menu menu) {
2640 switch (featureId) {
2641 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84b2010-06-08 18:04:35 -07002642 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 onOptionsMenuClosed(menu);
2644 break;
2645
2646 case Window.FEATURE_CONTEXT_MENU:
2647 onContextMenuClosed(menu);
2648 break;
Adam Powell8515ee82010-11-30 14:09:55 -08002649
2650 case Window.FEATURE_ACTION_BAR:
Adam Powell9b4bee02011-04-27 19:24:47 -07002651 initActionBar();
Adam Powell8515ee82010-11-30 14:09:55 -08002652 mActionBar.dispatchMenuVisibilityChanged(false);
2653 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 }
2655 }
2656
2657 /**
Dianne Hackbornb31e84b2010-06-08 18:04:35 -07002658 * Declare that the options menu has changed, so should be recreated.
2659 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2660 * time it needs to be displayed.
2661 */
2662 public void invalidateOptionsMenu() {
2663 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2664 }
2665
2666 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 * Initialize the contents of the Activity's standard options menu. You
2668 * should place your menu items in to <var>menu</var>.
2669 *
2670 * <p>This is only called once, the first time the options menu is
2671 * displayed. To update the menu every time it is displayed, see
2672 * {@link #onPrepareOptionsMenu}.
2673 *
2674 * <p>The default implementation populates the menu with standard system
2675 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2676 * they will be correctly ordered with application-defined menu items.
2677 * Deriving classes should always call through to the base implementation.
2678 *
2679 * <p>You can safely hold on to <var>menu</var> (and any items created
2680 * from it), making modifications to it as desired, until the next
2681 * time onCreateOptionsMenu() is called.
2682 *
2683 * <p>When you add items to the menu, you can implement the Activity's
2684 * {@link #onOptionsItemSelected} method to handle them there.
2685 *
2686 * @param menu The options menu in which you place your items.
2687 *
2688 * @return You must return true for the menu to be displayed;
2689 * if you return false it will not be shown.
2690 *
2691 * @see #onPrepareOptionsMenu
2692 * @see #onOptionsItemSelected
2693 */
2694 public boolean onCreateOptionsMenu(Menu menu) {
2695 if (mParent != null) {
2696 return mParent.onCreateOptionsMenu(menu);
2697 }
2698 return true;
2699 }
2700
2701 /**
2702 * Prepare the Screen's standard options menu to be displayed. This is
2703 * called right before the menu is shown, every time it is shown. You can
2704 * use this method to efficiently enable/disable items or otherwise
2705 * dynamically modify the contents.
2706 *
2707 * <p>The default implementation updates the system menu items based on the
2708 * activity's state. Deriving classes should always call through to the
2709 * base class implementation.
2710 *
2711 * @param menu The options menu as last shown or first initialized by
2712 * onCreateOptionsMenu().
2713 *
2714 * @return You must return true for the menu to be displayed;
2715 * if you return false it will not be shown.
2716 *
2717 * @see #onCreateOptionsMenu
2718 */
2719 public boolean onPrepareOptionsMenu(Menu menu) {
2720 if (mParent != null) {
2721 return mParent.onPrepareOptionsMenu(menu);
2722 }
2723 return true;
2724 }
2725
2726 /**
2727 * This hook is called whenever an item in your options menu is selected.
2728 * The default implementation simply returns false to have the normal
2729 * processing happen (calling the item's Runnable or sending a message to
2730 * its Handler as appropriate). You can use this method for any items
2731 * for which you would like to do processing without those other
2732 * facilities.
2733 *
2734 * <p>Derived classes should call through to the base class for it to
Adam Powelldd8fab22012-03-22 17:47:27 -07002735 * perform the default menu handling.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 *
2737 * @param item The menu item that was selected.
2738 *
2739 * @return boolean Return false to allow normal menu processing to
2740 * proceed, true to consume it here.
2741 *
2742 * @see #onCreateOptionsMenu
2743 */
2744 public boolean onOptionsItemSelected(MenuItem item) {
2745 if (mParent != null) {
2746 return mParent.onOptionsItemSelected(item);
2747 }
2748 return false;
2749 }
2750
2751 /**
Adam Powelldd8fab22012-03-22 17:47:27 -07002752 * This method is called whenever the user chooses to navigate Up within your application's
2753 * activity hierarchy from the action bar.
2754 *
2755 * <p>If the attribute {@link android.R.attr#parentActivityName parentActivityName}
2756 * was specified in the manifest for this activity or an activity-alias to it,
2757 * default Up navigation will be handled automatically. If any activity
2758 * along the parent chain requires extra Intent arguments, the Activity subclass
2759 * should override the method {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}
2760 * to supply those arguments.</p>
2761 *
2762 * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
2763 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
2764 * from the design guide for more information about navigating within your app.</p>
2765 *
2766 * <p>See the {@link TaskStackBuilder} class and the Activity methods
2767 * {@link #getParentActivityIntent()}, {@link #shouldUpRecreateTask(Intent)}, and
2768 * {@link #navigateUpTo(Intent)} for help implementing custom Up navigation.
2769 * The AppNavigation sample application in the Android SDK is also available for reference.</p>
2770 *
2771 * @return true if Up navigation completed successfully and this Activity was finished,
2772 * false otherwise.
2773 */
2774 public boolean onNavigateUp() {
2775 // Automatically handle hierarchical Up navigation if the proper
2776 // metadata is available.
2777 Intent upIntent = getParentActivityIntent();
2778 if (upIntent != null) {
Adam Powell0fc5b2b2012-07-18 18:20:29 -07002779 if (mActivityInfo.taskAffinity == null) {
2780 // Activities with a null affinity are special; they really shouldn't
2781 // specify a parent activity intent in the first place. Just finish
2782 // the current activity and call it a day.
2783 finish();
2784 } else if (shouldUpRecreateTask(upIntent)) {
Adam Powellf78a8442012-05-01 18:09:32 -07002785 TaskStackBuilder b = TaskStackBuilder.create(this);
Adam Powelldd8fab22012-03-22 17:47:27 -07002786 onCreateNavigateUpTaskStack(b);
2787 onPrepareNavigateUpTaskStack(b);
2788 b.startActivities();
Adam Powell3d193d92012-05-15 16:51:55 -07002789
2790 // We can't finishAffinity if we have a result.
2791 // Fall back and simply finish the current activity instead.
2792 if (mResultCode != RESULT_CANCELED || mResultData != null) {
2793 // Tell the developer what's going on to avoid hair-pulling.
2794 Log.i(TAG, "onNavigateUp only finishing topmost activity to return a result");
2795 finish();
2796 } else {
2797 finishAffinity();
2798 }
Adam Powelldd8fab22012-03-22 17:47:27 -07002799 } else {
2800 navigateUpTo(upIntent);
2801 }
2802 return true;
2803 }
2804 return false;
2805 }
2806
2807 /**
2808 * This is called when a child activity of this one attempts to navigate up.
2809 * The default implementation simply calls onNavigateUp() on this activity (the parent).
2810 *
2811 * @param child The activity making the call.
2812 */
2813 public boolean onNavigateUpFromChild(Activity child) {
2814 return onNavigateUp();
2815 }
2816
2817 /**
2818 * Define the synthetic task stack that will be generated during Up navigation from
2819 * a different task.
2820 *
2821 * <p>The default implementation of this method adds the parent chain of this activity
2822 * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications
2823 * may choose to override this method to construct the desired task stack in a different
2824 * way.</p>
2825 *
Adam Powellf0195952012-05-02 21:38:54 -07002826 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
2827 * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent
2828 * returned by {@link #getParentActivityIntent()}.</p>
2829 *
Adam Powelldd8fab22012-03-22 17:47:27 -07002830 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
2831 * by the manifest should override {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}.</p>
2832 *
2833 * @param builder An empty TaskStackBuilder - the application should add intents representing
2834 * the desired task stack
2835 */
2836 public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) {
2837 builder.addParentStack(this);
2838 }
2839
2840 /**
2841 * Prepare the synthetic task stack that will be generated during Up navigation
2842 * from a different task.
2843 *
2844 * <p>This method receives the {@link TaskStackBuilder} with the constructed series of
2845 * Intents as generated by {@link #onCreateNavigateUpTaskStack(TaskStackBuilder)}.
2846 * If any extra data should be added to these intents before launching the new task,
2847 * the application should override this method and add that data here.</p>
2848 *
2849 * @param builder A TaskStackBuilder that has been populated with Intents by
2850 * onCreateNavigateUpTaskStack.
2851 */
2852 public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) {
2853 }
2854
2855 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 * This hook is called whenever the options menu is being closed (either by the user canceling
2857 * the menu with the back/menu button, or when an item is selected).
2858 *
2859 * @param menu The options menu as last shown or first initialized by
2860 * onCreateOptionsMenu().
2861 */
2862 public void onOptionsMenuClosed(Menu menu) {
2863 if (mParent != null) {
2864 mParent.onOptionsMenuClosed(menu);
2865 }
2866 }
2867
2868 /**
2869 * Programmatically opens the options menu. If the options menu is already
2870 * open, this method does nothing.
2871 */
2872 public void openOptionsMenu() {
2873 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2874 }
2875
2876 /**
2877 * Progammatically closes the options menu. If the options menu is already
2878 * closed, this method does nothing.
2879 */
2880 public void closeOptionsMenu() {
2881 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2882 }
2883
2884 /**
2885 * Called when a context menu for the {@code view} is about to be shown.
2886 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2887 * time the context menu is about to be shown and should be populated for
2888 * the view (or item inside the view for {@link AdapterView} subclasses,
2889 * this can be found in the {@code menuInfo})).
2890 * <p>
2891 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2892 * item has been selected.
2893 * <p>
2894 * It is not safe to hold onto the context menu after this method returns.
Scott Maincdf51062013-01-08 20:03:05 -08002895 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 */
2897 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2898 }
2899
2900 /**
2901 * Registers a context menu to be shown for the given view (multiple views
2902 * can show the context menu). This method will set the
2903 * {@link OnCreateContextMenuListener} on the view to this activity, so
2904 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2905 * called when it is time to show the context menu.
2906 *
2907 * @see #unregisterForContextMenu(View)
2908 * @param view The view that should show a context menu.
2909 */
2910 public void registerForContextMenu(View view) {
2911 view.setOnCreateContextMenuListener(this);
2912 }
2913
2914 /**
2915 * Prevents a context menu to be shown for the given view. This method will remove the
2916 * {@link OnCreateContextMenuListener} on the view.
2917 *
2918 * @see #registerForContextMenu(View)
2919 * @param view The view that should stop showing a context menu.
2920 */
2921 public void unregisterForContextMenu(View view) {
2922 view.setOnCreateContextMenuListener(null);
2923 }
2924
2925 /**
2926 * Programmatically opens the context menu for a particular {@code view}.
2927 * The {@code view} should have been added via
2928 * {@link #registerForContextMenu(View)}.
2929 *
2930 * @param view The view to show the context menu for.
2931 */
2932 public void openContextMenu(View view) {
2933 view.showContextMenu();
2934 }
2935
2936 /**
2937 * Programmatically closes the most recently opened context menu, if showing.
2938 */
2939 public void closeContextMenu() {
2940 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2941 }
2942
2943 /**
2944 * This hook is called whenever an item in a context menu is selected. The
2945 * default implementation simply returns false to have the normal processing
2946 * happen (calling the item's Runnable or sending a message to its Handler
2947 * as appropriate). You can use this method for any items for which you
2948 * would like to do processing without those other facilities.
2949 * <p>
2950 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2951 * View that added this menu item.
2952 * <p>
2953 * Derived classes should call through to the base class for it to perform
2954 * the default menu handling.
2955 *
2956 * @param item The context menu item that was selected.
2957 * @return boolean Return false to allow normal context menu processing to
2958 * proceed, true to consume it here.
2959 */
2960 public boolean onContextItemSelected(MenuItem item) {
2961 if (mParent != null) {
2962 return mParent.onContextItemSelected(item);
2963 }
2964 return false;
2965 }
2966
2967 /**
2968 * This hook is called whenever the context menu is being closed (either by
2969 * the user canceling the menu with the back/menu button, or when an item is
2970 * selected).
2971 *
2972 * @param menu The context menu that is being closed.
2973 */
2974 public void onContextMenuClosed(Menu menu) {
2975 if (mParent != null) {
2976 mParent.onContextMenuClosed(menu);
2977 }
2978 }
2979
2980 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002981 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002983 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 protected Dialog onCreateDialog(int id) {
2985 return null;
2986 }
2987
2988 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002989 * Callback for creating dialogs that are managed (saved and restored) for you
2990 * by the activity. The default implementation calls through to
2991 * {@link #onCreateDialog(int)} for compatibility.
2992 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002993 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2994 * or later, consider instead using a {@link DialogFragment} instead.</em>
2995 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002996 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2997 * this method the first time, and hang onto it thereafter. Any dialog
2998 * that is created by this method will automatically be saved and restored
2999 * for you, including whether it is showing.
3000 *
3001 * <p>If you would like the activity to manage saving and restoring dialogs
3002 * for you, you should override this method and handle any ids that are
3003 * passed to {@link #showDialog}.
3004 *
3005 * <p>If you would like an opportunity to prepare your dialog before it is shown,
3006 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
3007 *
3008 * @param id The id of the dialog.
3009 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3010 * @return The dialog. If you return null, the dialog will not be created.
3011 *
3012 * @see #onPrepareDialog(int, Dialog, Bundle)
3013 * @see #showDialog(int, Bundle)
3014 * @see #dismissDialog(int)
3015 * @see #removeDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003016 *
3017 * @deprecated Use the new {@link DialogFragment} class with
3018 * {@link FragmentManager} instead; this is also
3019 * available on older platforms through the Android compatibility package.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003020 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07003021 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003022 protected Dialog onCreateDialog(int id, Bundle args) {
3023 return onCreateDialog(id);
3024 }
3025
3026 /**
3027 * @deprecated Old no-arguments version of
3028 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
3029 */
3030 @Deprecated
3031 protected void onPrepareDialog(int id, Dialog dialog) {
3032 dialog.setOwnerActivity(this);
3033 }
3034
3035 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003037 * shown. The default implementation calls through to
3038 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
3039 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 * <p>
3041 * Override this if you need to update a managed dialog based on the state
3042 * of the application each time it is shown. For example, a time picker
3043 * dialog might want to be updated with the current time. You should call
3044 * through to the superclass's implementation. The default implementation
3045 * will set this Activity as the owner activity on the Dialog.
3046 *
3047 * @param id The id of the managed dialog.
3048 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003049 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3050 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 * @see #showDialog(int)
3052 * @see #dismissDialog(int)
3053 * @see #removeDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003054 *
3055 * @deprecated Use the new {@link DialogFragment} class with
3056 * {@link FragmentManager} instead; this is also
3057 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07003059 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003060 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
3061 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 }
3063
3064 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003065 * Simple version of {@link #showDialog(int, Bundle)} that does not
3066 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
3067 * with null arguments.
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003068 *
3069 * @deprecated Use the new {@link DialogFragment} class with
3070 * {@link FragmentManager} instead; this is also
3071 * available on older platforms through the Android compatibility package.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003072 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07003073 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003074 public final void showDialog(int id) {
3075 showDialog(id, null);
3076 }
3077
3078 /**
3079 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 * will be made with the same id the first time this is called for a given
3081 * id. From thereafter, the dialog will be automatically saved and restored.
3082 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07003083 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3084 * or later, consider instead using a {@link DialogFragment} instead.</em>
3085 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003086 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 * be made to provide an opportunity to do any timely preparation.
3088 *
3089 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003090 * @param args Arguments to pass through to the dialog. These will be saved
3091 * and restored for you. Note that if the dialog is already created,
3092 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
3093 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08003094 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003095 * @return Returns true if the Dialog was created; false is returned if
3096 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
3097 *
Joe Onorato37296dc2009-07-31 17:58:55 -07003098 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003099 * @see #onCreateDialog(int, Bundle)
3100 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 * @see #dismissDialog(int)
3102 * @see #removeDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003103 *
3104 * @deprecated Use the new {@link DialogFragment} class with
3105 * {@link FragmentManager} instead; this is also
3106 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07003108 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003109 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003111 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003113 ManagedDialog md = mManagedDialogs.get(id);
3114 if (md == null) {
3115 md = new ManagedDialog();
3116 md.mDialog = createDialog(id, null, args);
3117 if (md.mDialog == null) {
3118 return false;
3119 }
3120 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 }
3122
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003123 md.mArgs = args;
3124 onPrepareDialog(id, md.mDialog, args);
3125 md.mDialog.show();
3126 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 }
3128
3129 /**
3130 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
3131 *
3132 * @param id The id of the managed dialog.
3133 *
3134 * @throws IllegalArgumentException if the id was not previously shown via
3135 * {@link #showDialog(int)}.
3136 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003137 * @see #onCreateDialog(int, Bundle)
3138 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 * @see #showDialog(int)
3140 * @see #removeDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003141 *
3142 * @deprecated Use the new {@link DialogFragment} class with
3143 * {@link FragmentManager} instead; this is also
3144 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07003146 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 public final void dismissDialog(int id) {
3148 if (mManagedDialogs == null) {
3149 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003151
3152 final ManagedDialog md = mManagedDialogs.get(id);
3153 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 throw missingDialog(id);
3155 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003156 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 }
3158
3159 /**
3160 * Creates an exception to throw if a user passed in a dialog id that is
3161 * unexpected.
3162 */
3163 private IllegalArgumentException missingDialog(int id) {
3164 return new IllegalArgumentException("no dialog with id " + id + " was ever "
3165 + "shown via Activity#showDialog");
3166 }
3167
3168 /**
3169 * Removes any internal references to a dialog managed by this Activity.
3170 * If the dialog is showing, it will dismiss it as part of the clean up.
3171 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003172 * <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 -08003173 * want to avoid the overhead of saving and restoring it in the future.
3174 *
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07003175 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
3176 * will not throw an exception if you try to remove an ID that does not
3177 * currently have an associated dialog.</p>
3178 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 * @param id The id of the managed dialog.
3180 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08003181 * @see #onCreateDialog(int, Bundle)
3182 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003183 * @see #showDialog(int)
3184 * @see #dismissDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003185 *
3186 * @deprecated Use the new {@link DialogFragment} class with
3187 * {@link FragmentManager} instead; this is also
3188 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07003190 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 public final void removeDialog(int id) {
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07003192 if (mManagedDialogs != null) {
3193 final ManagedDialog md = mManagedDialogs.get(id);
3194 if (md != null) {
3195 md.mDialog.dismiss();
3196 mManagedDialogs.remove(id);
3197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 }
3200
3201 /**
3202 * This hook is called when the user signals the desire to start a search.
3203 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01003204 * <p>You can use this function as a simple way to launch the search UI, in response to a
3205 * menu item, search button, or other widgets within your activity. Unless overidden,
3206 * calling this function is the same as calling
3207 * {@link #startSearch startSearch(null, false, null, false)}, which launches
3208 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 *
3210 * <p>You can override this function to force global search, e.g. in response to a dedicated
3211 * search key, or to block search entirely (by simply returning false).
3212 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01003213 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
3214 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 *
3216 * @see android.app.SearchManager
3217 */
3218 public boolean onSearchRequested() {
3219 startSearch(null, false, null, false);
3220 return true;
3221 }
3222
3223 /**
3224 * This hook is called to launch the search UI.
3225 *
3226 * <p>It is typically called from onSearchRequested(), either directly from
3227 * Activity.onSearchRequested() or from an overridden version in any given
3228 * Activity. If your goal is simply to activate search, it is preferred to call
3229 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
3230 * is to inject specific data such as context data, it is preferred to <i>override</i>
3231 * onSearchRequested(), so that any callers to it will benefit from the override.
3232 *
3233 * @param initialQuery Any non-null non-empty string will be inserted as
3234 * pre-entered text in the search query box.
3235 * @param selectInitialQuery If true, the intial query will be preselected, which means that
3236 * any further typing will replace it. This is useful for cases where an entire pre-formed
3237 * query is being inserted. If false, the selection point will be placed at the end of the
3238 * inserted query. This is useful when the inserted query is text that the user entered,
3239 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
3240 * if initialQuery is a non-empty string.</i>
3241 * @param appSearchData An application can insert application-specific
3242 * context here, in order to improve quality or specificity of its own
3243 * searches. This data will be returned with SEARCH intent(s). Null if
3244 * no extra data is required.
3245 * @param globalSearch If false, this will only launch the search that has been specifically
3246 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07003247 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248 * If true, this will always launch a platform-global (e.g. web-based) search instead.
3249 *
3250 * @see android.app.SearchManager
3251 * @see #onSearchRequested
3252 */
3253 public void startSearch(String initialQuery, boolean selectInitialQuery,
3254 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003255 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003256 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 appSearchData, globalSearch);
3258 }
3259
3260 /**
krosaend2d60142009-08-17 08:56:48 -07003261 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
3262 * the search dialog. Made available for testing purposes.
3263 *
3264 * @param query The query to trigger. If empty, the request will be ignored.
3265 * @param appSearchData An application can insert application-specific
3266 * context here, in order to improve quality or specificity of its own
3267 * searches. This data will be returned with SEARCH intent(s). Null if
3268 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07003269 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01003270 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07003271 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01003272 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07003273 }
3274
3275 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 * Request that key events come to this activity. Use this if your
3277 * activity has no views with focus, but the activity still wants
3278 * a chance to process key events.
3279 *
3280 * @see android.view.Window#takeKeyEvents
3281 */
3282 public void takeKeyEvents(boolean get) {
3283 getWindow().takeKeyEvents(get);
3284 }
3285
3286 /**
3287 * Enable extended window features. This is a convenience for calling
3288 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
3289 *
3290 * @param featureId The desired feature as defined in
3291 * {@link android.view.Window}.
3292 * @return Returns true if the requested feature is supported and now
3293 * enabled.
3294 *
3295 * @see android.view.Window#requestFeature
3296 */
3297 public final boolean requestWindowFeature(int featureId) {
3298 return getWindow().requestFeature(featureId);
3299 }
3300
3301 /**
3302 * Convenience for calling
3303 * {@link android.view.Window#setFeatureDrawableResource}.
3304 */
3305 public final void setFeatureDrawableResource(int featureId, int resId) {
3306 getWindow().setFeatureDrawableResource(featureId, resId);
3307 }
3308
3309 /**
3310 * Convenience for calling
3311 * {@link android.view.Window#setFeatureDrawableUri}.
3312 */
3313 public final void setFeatureDrawableUri(int featureId, Uri uri) {
3314 getWindow().setFeatureDrawableUri(featureId, uri);
3315 }
3316
3317 /**
3318 * Convenience for calling
3319 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
3320 */
3321 public final void setFeatureDrawable(int featureId, Drawable drawable) {
3322 getWindow().setFeatureDrawable(featureId, drawable);
3323 }
3324
3325 /**
3326 * Convenience for calling
3327 * {@link android.view.Window#setFeatureDrawableAlpha}.
3328 */
3329 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
3330 getWindow().setFeatureDrawableAlpha(featureId, alpha);
3331 }
3332
3333 /**
3334 * Convenience for calling
3335 * {@link android.view.Window#getLayoutInflater}.
3336 */
3337 public LayoutInflater getLayoutInflater() {
3338 return getWindow().getLayoutInflater();
3339 }
3340
3341 /**
3342 * Returns a {@link MenuInflater} with this context.
3343 */
3344 public MenuInflater getMenuInflater() {
Adam Powell88ab6972011-07-28 11:25:01 -07003345 // Make sure that action views can get an appropriate theme.
3346 if (mMenuInflater == null) {
3347 initActionBar();
3348 if (mActionBar != null) {
Dianne Hackborn92751972012-05-18 19:22:14 -07003349 mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this);
Adam Powell88ab6972011-07-28 11:25:01 -07003350 } else {
3351 mMenuInflater = new MenuInflater(this);
3352 }
3353 }
3354 return mMenuInflater;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 }
3356
3357 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003358 protected void onApplyThemeResource(Resources.Theme theme, int resid,
3359 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 if (mParent == null) {
3361 super.onApplyThemeResource(theme, resid, first);
3362 } else {
3363 try {
3364 theme.setTo(mParent.getTheme());
3365 } catch (Exception e) {
3366 // Empty
3367 }
3368 theme.applyStyle(resid, false);
3369 }
3370 }
3371
3372 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003373 * Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
3374 * with no options.
3375 *
3376 * @param intent The intent to start.
3377 * @param requestCode If >= 0, this code will be returned in
3378 * onActivityResult() when the activity exits.
3379 *
3380 * @throws android.content.ActivityNotFoundException
3381 *
3382 * @see #startActivity
3383 */
3384 public void startActivityForResult(Intent intent, int requestCode) {
3385 startActivityForResult(intent, requestCode, null);
3386 }
3387
3388 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 * Launch an activity for which you would like a result when it finished.
3390 * When this activity exits, your
3391 * onActivityResult() method will be called with the given requestCode.
3392 * Using a negative requestCode is the same as calling
3393 * {@link #startActivity} (the activity is not launched as a sub-activity).
Dianne Hackborna4972e92012-03-14 10:38:05 -07003394 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 * <p>Note that this method should only be used with Intent protocols
3396 * that are defined to return a result. In other protocols (such as
3397 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3398 * not get the result when you expect. For example, if the activity you
3399 * are launching uses the singleTask launch mode, it will not run in your
3400 * task and thus you will immediately receive a cancel result.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003401 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 * <p>As a special case, if you call startActivityForResult() with a requestCode
3403 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3404 * activity, then your window will not be displayed until a result is
3405 * returned back from the started activity. This is to avoid visible
3406 * flickering when redirecting to another activity.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003407 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 * <p>This method throws {@link android.content.ActivityNotFoundException}
3409 * if there was no Activity found to run the given Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003410 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 * @param intent The intent to start.
3412 * @param requestCode If >= 0, this code will be returned in
3413 * onActivityResult() when the activity exits.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003414 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003415 * See {@link android.content.Context#startActivity(Intent, Bundle)
3416 * Context.startActivity(Intent, Bundle)} for more details.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003417 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 * @throws android.content.ActivityNotFoundException
Dianne Hackborna4972e92012-03-14 10:38:05 -07003419 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 * @see #startActivity
3421 */
Dianne Hackborna4972e92012-03-14 10:38:05 -07003422 public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423 if (mParent == null) {
3424 Instrumentation.ActivityResult ar =
3425 mInstrumentation.execStartActivity(
3426 this, mMainThread.getApplicationThread(), mToken, this,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003427 intent, requestCode, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 if (ar != null) {
3429 mMainThread.sendActivityResult(
3430 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3431 ar.getResultData());
3432 }
3433 if (requestCode >= 0) {
3434 // If this start is requesting a result, we can avoid making
3435 // the activity visible until the result is received. Setting
3436 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3437 // activity hidden during this time, to avoid flickering.
3438 // This can only be done when a result is requested because
3439 // that guarantees we will get information back when the
3440 // activity is finished, no matter what happens to it.
3441 mStartedActivity = true;
3442 }
Adam Powell14874662013-07-18 19:42:41 -07003443
3444 final View decor = mWindow != null ? mWindow.peekDecorView() : null;
3445 if (decor != null) {
3446 decor.cancelPendingInputEvents();
3447 }
3448 // TODO Consider clearing/flushing other event sources and events for child windows.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 } else {
Dianne Hackborna4972e92012-03-14 10:38:05 -07003450 if (options != null) {
3451 mParent.startActivityFromChild(this, intent, requestCode, options);
3452 } else {
3453 // Note we want to go through this method for compatibility with
3454 // existing applications that may have overridden it.
3455 mParent.startActivityFromChild(this, intent, requestCode);
3456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 }
3458 }
3459
3460 /**
Dianne Hackbornf1c26e22012-08-23 13:54:58 -07003461 * @hide Implement to provide correct calling token.
3462 */
3463 public void startActivityAsUser(Intent intent, UserHandle user) {
3464 startActivityAsUser(intent, null, user);
3465 }
3466
3467 /**
3468 * @hide Implement to provide correct calling token.
3469 */
3470 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
3471 if (mParent != null) {
3472 throw new RuntimeException("Called be called from a child");
3473 }
3474 Instrumentation.ActivityResult ar =
3475 mInstrumentation.execStartActivity(
3476 this, mMainThread.getApplicationThread(), mToken, this,
3477 intent, -1, options, user);
3478 if (ar != null) {
3479 mMainThread.sendActivityResult(
3480 mToken, mEmbeddedID, -1, ar.getResultCode(),
3481 ar.getResultData());
3482 }
3483 }
3484
3485 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003486 * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
3487 * Intent, int, int, int, Bundle)} with no options.
3488 *
3489 * @param intent The IntentSender to launch.
3490 * @param requestCode If >= 0, this code will be returned in
3491 * onActivityResult() when the activity exits.
3492 * @param fillInIntent If non-null, this will be provided as the
3493 * intent parameter to {@link IntentSender#sendIntent}.
3494 * @param flagsMask Intent flags in the original IntentSender that you
3495 * would like to change.
3496 * @param flagsValues Desired values for any bits set in
3497 * <var>flagsMask</var>
3498 * @param extraFlags Always set to 0.
3499 */
3500 public void startIntentSenderForResult(IntentSender intent, int requestCode,
3501 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3502 throws IntentSender.SendIntentException {
3503 startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
3504 flagsValues, extraFlags, null);
3505 }
3506
3507 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003508 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003509 * to use a IntentSender to describe the activity to be started. If
3510 * the IntentSender is for an activity, that activity will be started
3511 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
3512 * here; otherwise, its associated action will be executed (such as
3513 * sending a broadcast) as if you had called
3514 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003515 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003516 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003517 * @param requestCode If >= 0, this code will be returned in
3518 * onActivityResult() when the activity exits.
3519 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003520 * intent parameter to {@link IntentSender#sendIntent}.
3521 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003522 * would like to change.
3523 * @param flagsValues Desired values for any bits set in
3524 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003525 * @param extraFlags Always set to 0.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003526 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003527 * See {@link android.content.Context#startActivity(Intent, Bundle)
3528 * Context.startActivity(Intent, Bundle)} for more details. If options
3529 * have also been supplied by the IntentSender, options given here will
3530 * override any that conflict with those given by the IntentSender.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003531 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003532 public void startIntentSenderForResult(IntentSender intent, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003533 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
3534 Bundle options) throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003535 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003536 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003537 flagsMask, flagsValues, this, options);
3538 } else if (options != null) {
3539 mParent.startIntentSenderFromChild(this, intent, requestCode,
3540 fillInIntent, flagsMask, flagsValues, extraFlags, options);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003541 } else {
Dianne Hackborna4972e92012-03-14 10:38:05 -07003542 // Note we want to go through this call for compatibility with
3543 // existing applications that may have overridden the method.
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003544 mParent.startIntentSenderFromChild(this, intent, requestCode,
3545 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003546 }
3547 }
3548
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003549 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003550 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity,
3551 Bundle options)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003552 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003553 try {
3554 String resolvedType = null;
3555 if (fillInIntent != null) {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07003556 fillInIntent.migrateExtraStreamToClipData();
3557 fillInIntent.prepareToLeaveProcess();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003558 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
3559 }
3560 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003561 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003562 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003563 requestCode, flagsMask, flagsValues, options);
3564 if (result == ActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003565 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003566 }
3567 Instrumentation.checkStartActivityResult(result, null);
3568 } catch (RemoteException e) {
3569 }
3570 if (requestCode >= 0) {
3571 // If this start is requesting a result, we can avoid making
3572 // the activity visible until the result is received. Setting
3573 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3574 // activity hidden during this time, to avoid flickering.
3575 // This can only be done when a result is requested because
3576 // that guarantees we will get information back when the
3577 // activity is finished, no matter what happens to it.
3578 mStartedActivity = true;
3579 }
3580 }
3581
3582 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003583 * Same as {@link #startActivity(Intent, Bundle)} with no options
3584 * specified.
3585 *
3586 * @param intent The intent to start.
3587 *
3588 * @throws android.content.ActivityNotFoundException
3589 *
3590 * @see {@link #startActivity(Intent, Bundle)}
3591 * @see #startActivityForResult
3592 */
3593 @Override
3594 public void startActivity(Intent intent) {
3595 startActivity(intent, null);
3596 }
3597
3598 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 * Launch a new activity. You will not receive any information about when
3600 * the activity exits. This implementation overrides the base version,
3601 * providing information about
3602 * the activity performing the launch. Because of this additional
3603 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3604 * required; if not specified, the new activity will be added to the
3605 * task of the caller.
3606 *
3607 * <p>This method throws {@link android.content.ActivityNotFoundException}
3608 * if there was no Activity found to run the given Intent.
3609 *
3610 * @param intent The intent to start.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003611 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003612 * See {@link android.content.Context#startActivity(Intent, Bundle)
3613 * Context.startActivity(Intent, Bundle)} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003614 *
3615 * @throws android.content.ActivityNotFoundException
Dianne Hackborna4972e92012-03-14 10:38:05 -07003616 *
3617 * @see {@link #startActivity(Intent)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 * @see #startActivityForResult
3619 */
3620 @Override
Dianne Hackborna4972e92012-03-14 10:38:05 -07003621 public void startActivity(Intent intent, Bundle options) {
3622 if (options != null) {
3623 startActivityForResult(intent, -1, options);
3624 } else {
3625 // Note we want to go through this call for compatibility with
3626 // applications that may have overridden the method.
3627 startActivityForResult(intent, -1);
3628 }
3629 }
3630
3631 /**
3632 * Same as {@link #startActivities(Intent[], Bundle)} with no options
3633 * specified.
3634 *
3635 * @param intents The intents to start.
3636 *
3637 * @throws android.content.ActivityNotFoundException
3638 *
3639 * @see {@link #startActivities(Intent[], Bundle)}
3640 * @see #startActivityForResult
3641 */
3642 @Override
3643 public void startActivities(Intent[] intents) {
3644 startActivities(intents, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 }
3646
3647 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003648 * Launch a new activity. You will not receive any information about when
3649 * the activity exits. This implementation overrides the base version,
3650 * providing information about
3651 * the activity performing the launch. Because of this additional
3652 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3653 * required; if not specified, the new activity will be added to the
3654 * task of the caller.
3655 *
3656 * <p>This method throws {@link android.content.ActivityNotFoundException}
3657 * if there was no Activity found to run the given Intent.
3658 *
3659 * @param intents The intents to start.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003660 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003661 * See {@link android.content.Context#startActivity(Intent, Bundle)
3662 * Context.startActivity(Intent, Bundle)} for more details.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003663 *
3664 * @throws android.content.ActivityNotFoundException
3665 *
Dianne Hackborna4972e92012-03-14 10:38:05 -07003666 * @see {@link #startActivities(Intent[])}
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003667 * @see #startActivityForResult
3668 */
3669 @Override
Dianne Hackborna4972e92012-03-14 10:38:05 -07003670 public void startActivities(Intent[] intents, Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003671 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
Dianne Hackborna4972e92012-03-14 10:38:05 -07003672 mToken, this, intents, options);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003673 }
3674
3675 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003676 * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
3677 * with no options.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003678 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003679 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003680 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003681 * intent parameter to {@link IntentSender#sendIntent}.
3682 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003683 * would like to change.
3684 * @param flagsValues Desired values for any bits set in
3685 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003686 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003687 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003688 public void startIntentSender(IntentSender intent,
3689 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3690 throws IntentSender.SendIntentException {
Dianne Hackborna4972e92012-03-14 10:38:05 -07003691 startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
3692 extraFlags, null);
3693 }
3694
3695 /**
3696 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
3697 * to start; see
3698 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
3699 * for more information.
3700 *
3701 * @param intent The IntentSender to launch.
3702 * @param fillInIntent If non-null, this will be provided as the
3703 * intent parameter to {@link IntentSender#sendIntent}.
3704 * @param flagsMask Intent flags in the original IntentSender that you
3705 * would like to change.
3706 * @param flagsValues Desired values for any bits set in
3707 * <var>flagsMask</var>
3708 * @param extraFlags Always set to 0.
3709 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003710 * See {@link android.content.Context#startActivity(Intent, Bundle)
3711 * Context.startActivity(Intent, Bundle)} for more details. If options
3712 * have also been supplied by the IntentSender, options given here will
3713 * override any that conflict with those given by the IntentSender.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003714 */
3715 public void startIntentSender(IntentSender intent,
3716 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
3717 Bundle options) throws IntentSender.SendIntentException {
3718 if (options != null) {
3719 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3720 flagsValues, extraFlags, options);
3721 } else {
3722 // Note we want to go through this call for compatibility with
3723 // applications that may have overridden the method.
3724 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3725 flagsValues, extraFlags);
3726 }
3727 }
3728
3729 /**
3730 * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
3731 * with no options.
3732 *
3733 * @param intent The intent to start.
3734 * @param requestCode If >= 0, this code will be returned in
3735 * onActivityResult() when the activity exits, as described in
3736 * {@link #startActivityForResult}.
3737 *
3738 * @return If a new activity was launched then true is returned; otherwise
3739 * false is returned and you must handle the Intent yourself.
3740 *
3741 * @see #startActivity
3742 * @see #startActivityForResult
3743 */
3744 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
3745 return startActivityIfNeeded(intent, requestCode, null);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003746 }
3747
3748 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 * A special variation to launch an activity only if a new activity
3750 * instance is needed to handle the given Intent. In other words, this is
3751 * just like {@link #startActivityForResult(Intent, int)} except: if you are
3752 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
3753 * singleTask or singleTop
3754 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
3755 * and the activity
3756 * that handles <var>intent</var> is the same as your currently running
3757 * activity, then a new instance is not needed. In this case, instead of
3758 * the normal behavior of calling {@link #onNewIntent} this function will
3759 * return and you can handle the Intent yourself.
3760 *
3761 * <p>This function can only be called from a top-level activity; if it is
3762 * called from a child activity, a runtime exception will be thrown.
3763 *
3764 * @param intent The intent to start.
3765 * @param requestCode If >= 0, this code will be returned in
3766 * onActivityResult() when the activity exits, as described in
3767 * {@link #startActivityForResult}.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003768 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003769 * See {@link android.content.Context#startActivity(Intent, Bundle)
3770 * Context.startActivity(Intent, Bundle)} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 *
3772 * @return If a new activity was launched then true is returned; otherwise
3773 * false is returned and you must handle the Intent yourself.
3774 *
3775 * @see #startActivity
3776 * @see #startActivityForResult
3777 */
Dianne Hackborna4972e92012-03-14 10:38:05 -07003778 public boolean startActivityIfNeeded(Intent intent, int requestCode, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 if (mParent == null) {
Dianne Hackborna4972e92012-03-14 10:38:05 -07003780 int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 try {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07003782 intent.migrateExtraStreamToClipData();
3783 intent.prepareToLeaveProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 result = ActivityManagerNative.getDefault()
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003785 .startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
Siva Velusamy92a8b222012-03-09 16:24:04 -08003786 intent, intent.resolveTypeIfNeeded(getContentResolver()),
Dianne Hackborna4972e92012-03-14 10:38:05 -07003787 mToken, mEmbeddedID, requestCode,
3788 ActivityManager.START_FLAG_ONLY_IF_NEEDED, null, null,
3789 options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 } catch (RemoteException e) {
3791 // Empty
3792 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 Instrumentation.checkStartActivityResult(result, intent);
Siva Velusamy92a8b222012-03-09 16:24:04 -08003795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796 if (requestCode >= 0) {
3797 // If this start is requesting a result, we can avoid making
3798 // the activity visible until the result is received. Setting
3799 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3800 // activity hidden during this time, to avoid flickering.
3801 // This can only be done when a result is requested because
3802 // that guarantees we will get information back when the
3803 // activity is finished, no matter what happens to it.
3804 mStartedActivity = true;
3805 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07003806 return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807 }
3808
3809 throw new UnsupportedOperationException(
3810 "startActivityIfNeeded can only be called from a top-level activity");
3811 }
3812
3813 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003814 * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
3815 * no options.
3816 *
3817 * @param intent The intent to dispatch to the next activity. For
3818 * correct behavior, this must be the same as the Intent that started
3819 * your own activity; the only changes you can make are to the extras
3820 * inside of it.
3821 *
3822 * @return Returns a boolean indicating whether there was another Activity
3823 * to start: true if there was a next activity to start, false if there
3824 * wasn't. In general, if true is returned you will then want to call
3825 * finish() on yourself.
3826 */
3827 public boolean startNextMatchingActivity(Intent intent) {
3828 return startNextMatchingActivity(intent, null);
3829 }
3830
3831 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 * Special version of starting an activity, for use when you are replacing
3833 * other activity components. You can use this to hand the Intent off
3834 * to the next Activity that can handle it. You typically call this in
3835 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3836 *
3837 * @param intent The intent to dispatch to the next activity. For
3838 * correct behavior, this must be the same as the Intent that started
3839 * your own activity; the only changes you can make are to the extras
3840 * inside of it.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003841 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003842 * See {@link android.content.Context#startActivity(Intent, Bundle)
3843 * Context.startActivity(Intent, Bundle)} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 *
3845 * @return Returns a boolean indicating whether there was another Activity
3846 * to start: true if there was a next activity to start, false if there
3847 * wasn't. In general, if true is returned you will then want to call
3848 * finish() on yourself.
3849 */
Dianne Hackborna4972e92012-03-14 10:38:05 -07003850 public boolean startNextMatchingActivity(Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 if (mParent == null) {
3852 try {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07003853 intent.migrateExtraStreamToClipData();
3854 intent.prepareToLeaveProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 return ActivityManagerNative.getDefault()
Dianne Hackborna4972e92012-03-14 10:38:05 -07003856 .startNextMatchingActivity(mToken, intent, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 } catch (RemoteException e) {
3858 // Empty
3859 }
3860 return false;
3861 }
3862
3863 throw new UnsupportedOperationException(
3864 "startNextMatchingActivity can only be called from a top-level activity");
3865 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07003866
3867 /**
3868 * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
3869 * with no options.
3870 *
3871 * @param child The activity making the call.
3872 * @param intent The intent to start.
3873 * @param requestCode Reply request code. < 0 if reply is not requested.
3874 *
3875 * @throws android.content.ActivityNotFoundException
3876 *
3877 * @see #startActivity
3878 * @see #startActivityForResult
3879 */
3880 public void startActivityFromChild(Activity child, Intent intent,
3881 int requestCode) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003882 startActivityFromChild(child, intent, requestCode, null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003883 }
3884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 /**
3886 * This is called when a child activity of this one calls its
3887 * {@link #startActivity} or {@link #startActivityForResult} method.
3888 *
3889 * <p>This method throws {@link android.content.ActivityNotFoundException}
3890 * if there was no Activity found to run the given Intent.
3891 *
3892 * @param child The activity making the call.
3893 * @param intent The intent to start.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003894 * @param requestCode Reply request code. < 0 if reply is not requested.
3895 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003896 * See {@link android.content.Context#startActivity(Intent, Bundle)
3897 * Context.startActivity(Intent, Bundle)} for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 *
3899 * @throws android.content.ActivityNotFoundException
3900 *
3901 * @see #startActivity
3902 * @see #startActivityForResult
3903 */
3904 public void startActivityFromChild(Activity child, Intent intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003905 int requestCode, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 Instrumentation.ActivityResult ar =
3907 mInstrumentation.execStartActivity(
3908 this, mMainThread.getApplicationThread(), mToken, child,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003909 intent, requestCode, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 if (ar != null) {
3911 mMainThread.sendActivityResult(
3912 mToken, child.mEmbeddedID, requestCode,
3913 ar.getResultCode(), ar.getResultData());
3914 }
3915 }
3916
3917 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003918 * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
3919 * with no options.
3920 *
3921 * @param fragment The fragment making the call.
3922 * @param intent The intent to start.
3923 * @param requestCode Reply request code. < 0 if reply is not requested.
3924 *
3925 * @throws android.content.ActivityNotFoundException
3926 *
3927 * @see Fragment#startActivity
3928 * @see Fragment#startActivityForResult
3929 */
3930 public void startActivityFromFragment(Fragment fragment, Intent intent,
3931 int requestCode) {
3932 startActivityFromFragment(fragment, intent, requestCode, null);
3933 }
3934
3935 /**
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003936 * This is called when a Fragment in this activity calls its
3937 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
3938 * method.
3939 *
3940 * <p>This method throws {@link android.content.ActivityNotFoundException}
3941 * if there was no Activity found to run the given Intent.
3942 *
3943 * @param fragment The fragment making the call.
3944 * @param intent The intent to start.
3945 * @param requestCode Reply request code. < 0 if reply is not requested.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003946 * @param options Additional options for how the Activity should be started.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003947 * See {@link android.content.Context#startActivity(Intent, Bundle)
3948 * Context.startActivity(Intent, Bundle)} for more details.
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003949 *
3950 * @throws android.content.ActivityNotFoundException
3951 *
3952 * @see Fragment#startActivity
3953 * @see Fragment#startActivityForResult
3954 */
3955 public void startActivityFromFragment(Fragment fragment, Intent intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003956 int requestCode, Bundle options) {
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003957 Instrumentation.ActivityResult ar =
3958 mInstrumentation.execStartActivity(
3959 this, mMainThread.getApplicationThread(), mToken, fragment,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003960 intent, requestCode, options);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003961 if (ar != null) {
3962 mMainThread.sendActivityResult(
3963 mToken, fragment.mWho, requestCode,
3964 ar.getResultCode(), ar.getResultData());
3965 }
3966 }
3967
3968 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07003969 * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
3970 * int, Intent, int, int, int, Bundle)} with no options.
3971 */
3972 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3973 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3974 int extraFlags)
3975 throws IntentSender.SendIntentException {
3976 startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
3977 flagsMask, flagsValues, extraFlags, null);
3978 }
3979
3980 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003981 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003982 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003983 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003984 * for more information.
3985 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003986 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3987 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003988 int extraFlags, Bundle options)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003989 throws IntentSender.SendIntentException {
3990 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003991 flagsMask, flagsValues, child, options);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003992 }
3993
3994 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003995 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3996 * or {@link #finish} to specify an explicit transition animation to
3997 * perform next.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003998 *
3999 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
4000 * to using this with starting activities is to supply the desired animation
4001 * information through a {@link ActivityOptions} bundle to
4002 * {@link #startActivity(Intent, Bundle) or a related function. This allows
4003 * you to specify a custom animation even when starting an activity from
4004 * outside the context of the current top activity.
4005 *
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07004006 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07004007 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07004008 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07004009 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07004010 */
4011 public void overridePendingTransition(int enterAnim, int exitAnim) {
4012 try {
4013 ActivityManagerNative.getDefault().overridePendingTransition(
4014 mToken, getPackageName(), enterAnim, exitAnim);
4015 } catch (RemoteException e) {
4016 }
4017 }
4018
4019 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 * Call this to set the result that your activity will return to its
4021 * caller.
4022 *
4023 * @param resultCode The result code to propagate back to the originating
4024 * activity, often RESULT_CANCELED or RESULT_OK
4025 *
4026 * @see #RESULT_CANCELED
4027 * @see #RESULT_OK
4028 * @see #RESULT_FIRST_USER
4029 * @see #setResult(int, Intent)
4030 */
4031 public final void setResult(int resultCode) {
4032 synchronized (this) {
4033 mResultCode = resultCode;
4034 mResultData = null;
4035 }
4036 }
4037
4038 /**
4039 * Call this to set the result that your activity will return to its
4040 * caller.
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004041 *
4042 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
4043 * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
4044 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4045 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the
4046 * Activity receiving the result access to the specific URIs in the Intent.
4047 * Access will remain until the Activity has finished (it will remain across the hosting
4048 * process being killed and other temporary destruction) and will be added
4049 * to any existing set of URI permissions it already holds.
4050 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 * @param resultCode The result code to propagate back to the originating
4052 * activity, often RESULT_CANCELED or RESULT_OK
4053 * @param data The data to propagate back to the originating activity.
4054 *
4055 * @see #RESULT_CANCELED
4056 * @see #RESULT_OK
4057 * @see #RESULT_FIRST_USER
4058 * @see #setResult(int)
4059 */
4060 public final void setResult(int resultCode, Intent data) {
4061 synchronized (this) {
4062 mResultCode = resultCode;
4063 mResultData = data;
4064 }
4065 }
4066
4067 /**
4068 * Return the name of the package that invoked this activity. This is who
4069 * the data in {@link #setResult setResult()} will be sent to. You can
4070 * use this information to validate that the recipient is allowed to
4071 * receive the data.
4072 *
Dianne Hackborn7b924672013-04-11 18:08:42 -07004073 * <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 -08004074 * did not use the {@link #startActivityForResult}
4075 * form that includes a request code), then the calling package will be
Dianne Hackborn7b924672013-04-11 18:08:42 -07004076 * null.</p>
4077 *
4078 * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
4079 * the result from this method was unstable. If the process hosting the calling
4080 * package was no longer running, it would return null instead of the proper package
4081 * name. You can use {@link #getCallingActivity()} and retrieve the package name
4082 * from that instead.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 *
4084 * @return The package of the activity that will receive your
4085 * reply, or null if none.
4086 */
4087 public String getCallingPackage() {
4088 try {
4089 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
4090 } catch (RemoteException e) {
4091 return null;
4092 }
4093 }
4094
4095 /**
4096 * Return the name of the activity that invoked this activity. This is
4097 * who the data in {@link #setResult setResult()} will be sent to. You
4098 * can use this information to validate that the recipient is allowed to
4099 * receive the data.
4100 *
Dianne Hackborn7b924672013-04-11 18:08:42 -07004101 * <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 -08004102 * did not use the {@link #startActivityForResult}
4103 * form that includes a request code), then the calling package will be
4104 * null.
4105 *
Dianne Hackborn7b924672013-04-11 18:08:42 -07004106 * @return The ComponentName of the activity that will receive your
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 * reply, or null if none.
4108 */
4109 public ComponentName getCallingActivity() {
4110 try {
4111 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
4112 } catch (RemoteException e) {
4113 return null;
4114 }
4115 }
4116
4117 /**
4118 * Control whether this activity's main window is visible. This is intended
4119 * only for the special case of an activity that is not going to show a
4120 * UI itself, but can't just finish prior to onResume() because it needs
4121 * to wait for a service binding or such. Setting this to false allows
4122 * you to prevent your UI from being shown during that time.
4123 *
4124 * <p>The default value for this is taken from the
4125 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
4126 */
4127 public void setVisible(boolean visible) {
4128 if (mVisibleFromClient != visible) {
4129 mVisibleFromClient = visible;
4130 if (mVisibleFromServer) {
4131 if (visible) makeVisible();
4132 else mDecor.setVisibility(View.INVISIBLE);
4133 }
4134 }
4135 }
4136
4137 void makeVisible() {
4138 if (!mWindowAdded) {
4139 ViewManager wm = getWindowManager();
4140 wm.addView(mDecor, getWindow().getAttributes());
4141 mWindowAdded = true;
4142 }
4143 mDecor.setVisibility(View.VISIBLE);
4144 }
4145
4146 /**
4147 * Check to see whether this activity is in the process of finishing,
4148 * either because you called {@link #finish} on it or someone else
4149 * has requested that it finished. This is often used in
4150 * {@link #onPause} to determine whether the activity is simply pausing or
4151 * completely finishing.
4152 *
4153 * @return If the activity is finishing, returns true; else returns false.
4154 *
4155 * @see #finish
4156 */
4157 public boolean isFinishing() {
4158 return mFinished;
4159 }
4160
4161 /**
Dianne Hackborn6d9dcbc2012-10-02 17:51:13 -07004162 * Returns true if the final {@link #onDestroy()} call has been made
4163 * on the Activity, so this instance is now dead.
4164 */
4165 public boolean isDestroyed() {
4166 return mDestroyed;
4167 }
4168
4169 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05004170 * Check to see whether this activity is in the process of being destroyed in order to be
4171 * recreated with a new configuration. This is often used in
4172 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
4173 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
4174 *
4175 * @return If the activity is being torn down in order to be recreated with a new configuration,
4176 * returns true; else returns false.
4177 */
4178 public boolean isChangingConfigurations() {
4179 return mChangingConfigurations;
4180 }
4181
4182 /**
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004183 * Cause this Activity to be recreated with a new instance. This results
4184 * in essentially the same flow as when the Activity is created due to
4185 * a configuration change -- the current instance will go through its
4186 * lifecycle to {@link #onDestroy} and a new instance then created after it.
4187 */
4188 public void recreate() {
4189 if (mParent != null) {
4190 throw new IllegalStateException("Can only be called on top-level activity");
4191 }
4192 if (Looper.myLooper() != mMainThread.getLooper()) {
4193 throw new IllegalStateException("Must be called from main thread");
4194 }
4195 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, false);
4196 }
4197
4198 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 * Call this when your activity is done and should be closed. The
4200 * ActivityResult is propagated back to whoever launched you via
4201 * onActivityResult().
4202 */
4203 public void finish() {
4204 if (mParent == null) {
4205 int resultCode;
4206 Intent resultData;
4207 synchronized (this) {
4208 resultCode = mResultCode;
4209 resultData = mResultData;
4210 }
Joe Onorato43a17652011-04-06 19:22:23 -07004211 if (false) Log.v(TAG, "Finishing self: token=" + mToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 try {
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04004213 if (resultData != null) {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07004214 resultData.prepareToLeaveProcess();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04004215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 if (ActivityManagerNative.getDefault()
4217 .finishActivity(mToken, resultCode, resultData)) {
4218 mFinished = true;
4219 }
4220 } catch (RemoteException e) {
4221 // Empty
4222 }
4223 } else {
4224 mParent.finishFromChild(this);
4225 }
4226 }
4227
4228 /**
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07004229 * Finish this activity as well as all activities immediately below it
4230 * in the current task that have the same affinity. This is typically
4231 * used when an application can be launched on to another task (such as
4232 * from an ACTION_VIEW of a content type it understands) and the user
4233 * has used the up navigation to switch out of the current task and in
4234 * to its own task. In this case, if the user has navigated down into
4235 * any other activities of the second application, all of those should
4236 * be removed from the original task as part of the task switch.
4237 *
4238 * <p>Note that this finish does <em>not</em> allow you to deliver results
4239 * to the previous activity, and an exception will be thrown if you are trying
4240 * to do so.</p>
4241 */
4242 public void finishAffinity() {
4243 if (mParent != null) {
4244 throw new IllegalStateException("Can not be called from an embedded activity");
4245 }
4246 if (mResultCode != RESULT_CANCELED || mResultData != null) {
4247 throw new IllegalStateException("Can not be called to deliver a result");
4248 }
4249 try {
4250 if (ActivityManagerNative.getDefault().finishActivityAffinity(mToken)) {
4251 mFinished = true;
4252 }
4253 } catch (RemoteException e) {
4254 // Empty
4255 }
4256 }
4257
4258 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 * This is called when a child activity of this one calls its
4260 * {@link #finish} method. The default implementation simply calls
4261 * finish() on this activity (the parent), finishing the entire group.
4262 *
4263 * @param child The activity making the call.
4264 *
4265 * @see #finish
4266 */
4267 public void finishFromChild(Activity child) {
4268 finish();
4269 }
4270
4271 /**
4272 * Force finish another activity that you had previously started with
4273 * {@link #startActivityForResult}.
4274 *
4275 * @param requestCode The request code of the activity that you had
4276 * given to startActivityForResult(). If there are multiple
4277 * activities started with this request code, they
4278 * will all be finished.
4279 */
4280 public void finishActivity(int requestCode) {
4281 if (mParent == null) {
4282 try {
4283 ActivityManagerNative.getDefault()
4284 .finishSubActivity(mToken, mEmbeddedID, requestCode);
4285 } catch (RemoteException e) {
4286 // Empty
4287 }
4288 } else {
4289 mParent.finishActivityFromChild(this, requestCode);
4290 }
4291 }
4292
4293 /**
4294 * This is called when a child activity of this one calls its
4295 * finishActivity().
4296 *
4297 * @param child The activity making the call.
4298 * @param requestCode Request code that had been used to start the
4299 * activity.
4300 */
4301 public void finishActivityFromChild(Activity child, int requestCode) {
4302 try {
4303 ActivityManagerNative.getDefault()
4304 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
4305 } catch (RemoteException e) {
4306 // Empty
4307 }
4308 }
4309
4310 /**
4311 * Called when an activity you launched exits, giving you the requestCode
4312 * you started it with, the resultCode it returned, and any additional
4313 * data from it. The <var>resultCode</var> will be
4314 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
4315 * didn't return any result, or crashed during its operation.
4316 *
4317 * <p>You will receive this call immediately before onResume() when your
4318 * activity is re-starting.
Ricardo Cervera92f6a742014-04-04 11:17:06 -07004319 *
4320 * <p>This method is never invoked if your activity sets
4321 * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
4322 * <code>true</code>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004323 *
4324 * @param requestCode The integer request code originally supplied to
4325 * startActivityForResult(), allowing you to identify who this
4326 * result came from.
4327 * @param resultCode The integer result code returned by the child activity
4328 * through its setResult().
4329 * @param data An Intent, which can return result data to the caller
4330 * (various data can be attached to Intent "extras").
4331 *
4332 * @see #startActivityForResult
4333 * @see #createPendingResult
4334 * @see #setResult(int)
4335 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004336 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 }
4338
4339 /**
4340 * Create a new PendingIntent object which you can hand to others
4341 * for them to use to send result data back to your
4342 * {@link #onActivityResult} callback. The created object will be either
4343 * one-shot (becoming invalid after a result is sent back) or multiple
4344 * (allowing any number of results to be sent through it).
4345 *
4346 * @param requestCode Private request code for the sender that will be
4347 * associated with the result data when it is returned. The sender can not
4348 * modify this value, allowing you to identify incoming results.
4349 * @param data Default data to supply in the result, which may be modified
4350 * by the sender.
4351 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
4352 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
4353 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
4354 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
4355 * or any of the flags as supported by
4356 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
4357 * of the intent that can be supplied when the actual send happens.
4358 *
4359 * @return Returns an existing or new PendingIntent matching the given
4360 * parameters. May return null only if
4361 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
4362 * supplied.
4363 *
4364 * @see PendingIntent
4365 */
4366 public PendingIntent createPendingResult(int requestCode, Intent data,
4367 int flags) {
4368 String packageName = getPackageName();
4369 try {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07004370 data.prepareToLeaveProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 IIntentSender target =
4372 ActivityManagerNative.getDefault().getIntentSender(
Dianne Hackborna4972e92012-03-14 10:38:05 -07004373 ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 mParent == null ? mToken : mParent.mToken,
Dianne Hackborn41203752012-08-31 14:05:51 -07004375 mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null,
4376 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004377 return target != null ? new PendingIntent(target) : null;
4378 } catch (RemoteException e) {
4379 // Empty
4380 }
4381 return null;
4382 }
4383
4384 /**
4385 * Change the desired orientation of this activity. If the activity
4386 * is currently in the foreground or otherwise impacting the screen
4387 * orientation, the screen will immediately be changed (possibly causing
4388 * the activity to be restarted). Otherwise, this will be used the next
4389 * time the activity is visible.
4390 *
4391 * @param requestedOrientation An orientation constant as used in
4392 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
4393 */
4394 public void setRequestedOrientation(int requestedOrientation) {
4395 if (mParent == null) {
4396 try {
4397 ActivityManagerNative.getDefault().setRequestedOrientation(
4398 mToken, requestedOrientation);
4399 } catch (RemoteException e) {
4400 // Empty
4401 }
4402 } else {
4403 mParent.setRequestedOrientation(requestedOrientation);
4404 }
4405 }
4406
4407 /**
4408 * Return the current requested orientation of the activity. This will
4409 * either be the orientation requested in its component's manifest, or
4410 * the last requested orientation given to
4411 * {@link #setRequestedOrientation(int)}.
4412 *
4413 * @return Returns an orientation constant as used in
4414 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
4415 */
4416 public int getRequestedOrientation() {
4417 if (mParent == null) {
4418 try {
4419 return ActivityManagerNative.getDefault()
4420 .getRequestedOrientation(mToken);
4421 } catch (RemoteException e) {
4422 // Empty
4423 }
4424 } else {
4425 return mParent.getRequestedOrientation();
4426 }
4427 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
4428 }
4429
4430 /**
4431 * Return the identifier of the task this activity is in. This identifier
4432 * will remain the same for the lifetime of the activity.
4433 *
4434 * @return Task identifier, an opaque integer.
4435 */
4436 public int getTaskId() {
4437 try {
4438 return ActivityManagerNative.getDefault()
4439 .getTaskForActivity(mToken, false);
4440 } catch (RemoteException e) {
4441 return -1;
4442 }
4443 }
4444
4445 /**
4446 * Return whether this activity is the root of a task. The root is the
4447 * first activity in a task.
4448 *
4449 * @return True if this is the root activity, else false.
4450 */
4451 public boolean isTaskRoot() {
4452 try {
4453 return ActivityManagerNative.getDefault()
4454 .getTaskForActivity(mToken, true) >= 0;
4455 } catch (RemoteException e) {
4456 return false;
4457 }
4458 }
4459
4460 /**
4461 * Move the task containing this activity to the back of the activity
4462 * stack. The activity's order within the task is unchanged.
4463 *
4464 * @param nonRoot If false then this only works if the activity is the root
4465 * of a task; if true it will work for any activity in
4466 * a task.
4467 *
4468 * @return If the task was moved (or it was already at the
4469 * back) true is returned, else false.
4470 */
4471 public boolean moveTaskToBack(boolean nonRoot) {
4472 try {
4473 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
4474 mToken, nonRoot);
4475 } catch (RemoteException e) {
4476 // Empty
4477 }
4478 return false;
4479 }
4480
4481 /**
4482 * Returns class name for this activity with the package prefix removed.
4483 * This is the default name used to read and write settings.
4484 *
4485 * @return The local class name.
4486 */
4487 public String getLocalClassName() {
4488 final String pkg = getPackageName();
4489 final String cls = mComponent.getClassName();
4490 int packageLen = pkg.length();
4491 if (!cls.startsWith(pkg) || cls.length() <= packageLen
4492 || cls.charAt(packageLen) != '.') {
4493 return cls;
4494 }
4495 return cls.substring(packageLen+1);
4496 }
4497
4498 /**
4499 * Returns complete component name of this activity.
4500 *
4501 * @return Returns the complete component name for this activity
4502 */
4503 public ComponentName getComponentName()
4504 {
4505 return mComponent;
4506 }
4507
4508 /**
4509 * Retrieve a {@link SharedPreferences} object for accessing preferences
4510 * that are private to this activity. This simply calls the underlying
4511 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
4512 * class name as the preferences name.
4513 *
4514 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
4515 * operation, {@link #MODE_WORLD_READABLE} and
4516 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
4517 *
4518 * @return Returns the single SharedPreferences instance that can be used
4519 * to retrieve and modify the preference values.
4520 */
4521 public SharedPreferences getPreferences(int mode) {
4522 return getSharedPreferences(getLocalClassName(), mode);
4523 }
4524
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004525 private void ensureSearchManager() {
4526 if (mSearchManager != null) {
4527 return;
4528 }
4529
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08004530 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004531 }
4532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533 @Override
4534 public Object getSystemService(String name) {
4535 if (getBaseContext() == null) {
4536 throw new IllegalStateException(
4537 "System services not available to Activities before onCreate()");
4538 }
4539
4540 if (WINDOW_SERVICE.equals(name)) {
4541 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01004542 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004543 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01004544 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 }
4546 return super.getSystemService(name);
4547 }
4548
4549 /**
4550 * Change the title associated with this activity. If this is a
4551 * top-level activity, the title for its window will change. If it
4552 * is an embedded activity, the parent can do whatever it wants
4553 * with it.
4554 */
4555 public void setTitle(CharSequence title) {
4556 mTitle = title;
4557 onTitleChanged(title, mTitleColor);
4558
4559 if (mParent != null) {
4560 mParent.onChildTitleChanged(this, title);
4561 }
4562 }
4563
4564 /**
4565 * Change the title associated with this activity. If this is a
4566 * top-level activity, the title for its window will change. If it
4567 * is an embedded activity, the parent can do whatever it wants
4568 * with it.
4569 */
4570 public void setTitle(int titleId) {
4571 setTitle(getText(titleId));
4572 }
4573
4574 public void setTitleColor(int textColor) {
4575 mTitleColor = textColor;
4576 onTitleChanged(mTitle, textColor);
4577 }
4578
4579 public final CharSequence getTitle() {
4580 return mTitle;
4581 }
4582
4583 public final int getTitleColor() {
4584 return mTitleColor;
4585 }
4586
4587 protected void onTitleChanged(CharSequence title, int color) {
4588 if (mTitleReady) {
4589 final Window win = getWindow();
4590 if (win != null) {
4591 win.setTitle(title);
4592 if (color != 0) {
4593 win.setTitleColor(color);
4594 }
4595 }
4596 }
4597 }
4598
4599 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
4600 }
4601
4602 /**
4603 * Sets the visibility of the progress bar in the title.
4604 * <p>
4605 * In order for the progress bar to be shown, the feature must be requested
4606 * via {@link #requestWindowFeature(int)}.
4607 *
4608 * @param visible Whether to show the progress bars in the title.
4609 */
4610 public final void setProgressBarVisibility(boolean visible) {
4611 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
4612 Window.PROGRESS_VISIBILITY_OFF);
4613 }
4614
4615 /**
4616 * Sets the visibility of the indeterminate progress bar in the title.
4617 * <p>
4618 * In order for the progress bar to be shown, the feature must be requested
4619 * via {@link #requestWindowFeature(int)}.
4620 *
4621 * @param visible Whether to show the progress bars in the title.
4622 */
4623 public final void setProgressBarIndeterminateVisibility(boolean visible) {
4624 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
4625 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
4626 }
4627
4628 /**
4629 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
4630 * is always indeterminate).
4631 * <p>
4632 * In order for the progress bar to be shown, the feature must be requested
4633 * via {@link #requestWindowFeature(int)}.
4634 *
4635 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
4636 */
4637 public final void setProgressBarIndeterminate(boolean indeterminate) {
4638 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4639 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
4640 }
4641
4642 /**
4643 * Sets the progress for the progress bars in the title.
4644 * <p>
4645 * In order for the progress bar to be shown, the feature must be requested
4646 * via {@link #requestWindowFeature(int)}.
4647 *
4648 * @param progress The progress for the progress bar. Valid ranges are from
4649 * 0 to 10000 (both inclusive). If 10000 is given, the progress
4650 * bar will be completely filled and will fade out.
4651 */
4652 public final void setProgress(int progress) {
4653 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
4654 }
4655
4656 /**
4657 * Sets the secondary progress for the progress bar in the title. This
4658 * progress is drawn between the primary progress (set via
4659 * {@link #setProgress(int)} and the background. It can be ideal for media
4660 * scenarios such as showing the buffering progress while the default
4661 * progress shows the play progress.
4662 * <p>
4663 * In order for the progress bar to be shown, the feature must be requested
4664 * via {@link #requestWindowFeature(int)}.
4665 *
4666 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
4667 * 0 to 10000 (both inclusive).
4668 */
4669 public final void setSecondaryProgress(int secondaryProgress) {
4670 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4671 secondaryProgress + Window.PROGRESS_SECONDARY_START);
4672 }
4673
4674 /**
4675 * Suggests an audio stream whose volume should be changed by the hardware
4676 * volume controls.
4677 * <p>
4678 * The suggested audio stream will be tied to the window of this Activity.
4679 * If the Activity is switched, the stream set here is no longer the
4680 * suggested stream. The client does not need to save and restore the old
4681 * suggested stream value in onPause and onResume.
4682 *
4683 * @param streamType The type of the audio stream whose volume should be
4684 * changed by the hardware volume controls. It is not guaranteed that
4685 * the hardware volume controls will always change this stream's
4686 * volume (for example, if a call is in progress, its stream's volume
4687 * may be changed instead). To reset back to the default, use
4688 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
4689 */
4690 public final void setVolumeControlStream(int streamType) {
4691 getWindow().setVolumeControlStream(streamType);
4692 }
4693
4694 /**
4695 * Gets the suggested audio stream whose volume should be changed by the
4696 * harwdare volume controls.
4697 *
4698 * @return The suggested audio stream type whose volume should be changed by
4699 * the hardware volume controls.
4700 * @see #setVolumeControlStream(int)
4701 */
4702 public final int getVolumeControlStream() {
4703 return getWindow().getVolumeControlStream();
4704 }
4705
4706 /**
4707 * Runs the specified action on the UI thread. If the current thread is the UI
4708 * thread, then the action is executed immediately. If the current thread is
4709 * not the UI thread, the action is posted to the event queue of the UI thread.
4710 *
4711 * @param action the action to run on the UI thread
4712 */
4713 public final void runOnUiThread(Runnable action) {
4714 if (Thread.currentThread() != mUiThread) {
4715 mHandler.post(action);
4716 } else {
4717 action.run();
4718 }
4719 }
4720
4721 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004722 * Standard implementation of
4723 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
4724 * inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004725 * This implementation does nothing and is for
4726 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
4727 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
4728 *
4729 * @see android.view.LayoutInflater#createView
4730 * @see android.view.Window#getLayoutInflater
4731 */
4732 public View onCreateView(String name, Context context, AttributeSet attrs) {
4733 return null;
4734 }
4735
4736 /**
4737 * Standard implementation of
4738 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
4739 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004740 * This implementation handles <fragment> tags to embed fragments inside
4741 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 *
4743 * @see android.view.LayoutInflater#createView
4744 * @see android.view.Window#getLayoutInflater
4745 */
Dianne Hackborn625ac272010-09-17 18:29:22 -07004746 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004747 if (!"fragment".equals(name)) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07004748 return onCreateView(name, context, attrs);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004749 }
4750
Dianne Hackborndef15372010-08-15 12:43:52 -07004751 String fname = attrs.getAttributeValue(null, "class");
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004752 TypedArray a =
4753 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment);
Dianne Hackborndef15372010-08-15 12:43:52 -07004754 if (fname == null) {
4755 fname = a.getString(com.android.internal.R.styleable.Fragment_name);
4756 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004757 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, View.NO_ID);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004758 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag);
4759 a.recycle();
4760
Dianne Hackborn625ac272010-09-17 18:29:22 -07004761 int containerId = parent != null ? parent.getId() : 0;
4762 if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004763 throw new IllegalArgumentException(attrs.getPositionDescription()
Dianne Hackborn625ac272010-09-17 18:29:22 -07004764 + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004765 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004766
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004767 // If we restored from a previous state, we may already have
4768 // instantiated this fragment from the state and should use
4769 // that instance instead of making a new one.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004770 Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
4771 if (fragment == null && tag != null) {
4772 fragment = mFragments.findFragmentByTag(tag);
4773 }
4774 if (fragment == null && containerId != View.NO_ID) {
4775 fragment = mFragments.findFragmentById(containerId);
4776 }
4777
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004778 if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
4779 + Integer.toHexString(id) + " fname=" + fname
4780 + " existing=" + fragment);
4781 if (fragment == null) {
4782 fragment = Fragment.instantiate(this, fname);
4783 fragment.mFromLayout = true;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004784 fragment.mFragmentId = id != 0 ? id : containerId;
4785 fragment.mContainerId = containerId;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004786 fragment.mTag = tag;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004787 fragment.mInLayout = true;
Dianne Hackborn3e449ce2010-09-11 20:52:31 -07004788 fragment.mFragmentManager = mFragments;
Dianne Hackborne3a7f622011-03-03 21:48:24 -08004789 fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004790 mFragments.addFragment(fragment, true);
4791
4792 } else if (fragment.mInLayout) {
4793 // A fragment already exists and it is not one we restored from
4794 // previous state.
4795 throw new IllegalArgumentException(attrs.getPositionDescription()
4796 + ": Duplicate id 0x" + Integer.toHexString(id)
4797 + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
4798 + " with another fragment for " + fname);
4799 } else {
4800 // This fragment was retained from a previous instance; get it
4801 // going now.
4802 fragment.mInLayout = true;
Dianne Hackborndef15372010-08-15 12:43:52 -07004803 // If this fragment is newly instantiated (either right now, or
4804 // from last saved state), then give it the attributes to
4805 // initialize itself.
4806 if (!fragment.mRetaining) {
Dianne Hackborne3a7f622011-03-03 21:48:24 -08004807 fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
Dianne Hackborndef15372010-08-15 12:43:52 -07004808 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004809 mFragments.moveToState(fragment);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004810 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004811
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004812 if (fragment.mView == null) {
4813 throw new IllegalStateException("Fragment " + fname
4814 + " did not create a view.");
4815 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004816 if (id != 0) {
4817 fragment.mView.setId(id);
4818 }
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004819 if (fragment.mView.getTag() == null) {
4820 fragment.mView.setTag(tag);
4821 }
4822 return fragment.mView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004823 }
4824
Daniel Sandler69a48172010-06-23 16:29:36 -04004825 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -07004826 * Print the Activity's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07004827 * you run "adb shell dumpsys activity &lt;activity_component_name&gt;".
Dianne Hackborn625ac272010-09-17 18:29:22 -07004828 *
Dianne Hackborn30d71892010-12-11 10:37:55 -08004829 * @param prefix Desired prefix to prepend at each line of output.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004830 * @param fd The raw file descriptor that the dump is being sent to.
4831 * @param writer The PrintWriter to which you should dump your state. This will be
4832 * closed for you after you return.
4833 * @param args additional arguments to the dump request.
4834 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08004835 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
Dianne Hackborn62bea2f2012-09-04 18:48:15 -07004836 dumpInner(prefix, fd, writer, args);
4837 }
4838
4839 void dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
Dianne Hackborn30d71892010-12-11 10:37:55 -08004840 writer.print(prefix); writer.print("Local Activity ");
4841 writer.print(Integer.toHexString(System.identityHashCode(this)));
4842 writer.println(" State:");
4843 String innerPrefix = prefix + " ";
4844 writer.print(innerPrefix); writer.print("mResumed=");
4845 writer.print(mResumed); writer.print(" mStopped=");
4846 writer.print(mStopped); writer.print(" mFinished=");
4847 writer.println(mFinished);
4848 writer.print(innerPrefix); writer.print("mLoadersStarted=");
4849 writer.println(mLoadersStarted);
4850 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
4851 writer.println(mChangingConfigurations);
4852 writer.print(innerPrefix); writer.print("mCurrentConfig=");
4853 writer.println(mCurrentConfig);
Jeff Brown5182c782013-10-15 20:31:52 -07004854
Dianne Hackborn30d71892010-12-11 10:37:55 -08004855 if (mLoaderManager != null) {
4856 writer.print(prefix); writer.print("Loader Manager ");
4857 writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
4858 writer.println(":");
4859 mLoaderManager.dump(prefix + " ", fd, writer, args);
4860 }
Dianne Hackborn4702a852012-08-17 15:18:29 -07004861
Jeff Brown5182c782013-10-15 20:31:52 -07004862 mFragments.dump(prefix, fd, writer, args);
4863
Michael Wright5f48dc72013-11-01 12:42:49 -07004864 if (getWindow() != null &&
4865 getWindow().peekDecorView() != null &&
4866 getWindow().peekDecorView().getViewRootImpl() != null) {
4867 getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args);
4868 }
Jeff Brown5182c782013-10-15 20:31:52 -07004869
4870 mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004871 }
4872
4873 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04004874 * Bit indicating that this activity is "immersive" and should not be
4875 * interrupted by notifications if possible.
4876 *
4877 * This value is initially set by the manifest property
4878 * <code>android:immersive</code> but may be changed at runtime by
4879 * {@link #setImmersive}.
4880 *
Christopher Tate73c2aee2012-03-15 16:27:14 -07004881 * @see #setImmersive(boolean)
Daniel Sandler69a48172010-06-23 16:29:36 -04004882 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4883 */
4884 public boolean isImmersive() {
4885 try {
4886 return ActivityManagerNative.getDefault().isImmersive(mToken);
4887 } catch (RemoteException e) {
4888 return false;
4889 }
4890 }
4891
4892 /**
Craig Mautner4addfc52013-06-25 08:05:45 -07004893 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} to a
4894 * fullscreen opaque Activity.
Craig Mautner5eda9b32013-07-02 11:58:16 -07004895 * <p>
Craig Mautner4addfc52013-06-25 08:05:45 -07004896 * Call this whenever the background of a translucent Activity has changed to become opaque.
Craig Mautner5eda9b32013-07-02 11:58:16 -07004897 * Doing so will allow the {@link android.view.Surface} of the Activity behind to be released.
4898 * <p>
Craig Mautner4addfc52013-06-25 08:05:45 -07004899 * This call has no effect on non-translucent activities or on activities with the
4900 * {@link android.R.attr#windowIsFloating} attribute.
Craig Mautner5eda9b32013-07-02 11:58:16 -07004901 *
4902 * @see #convertToTranslucent(TranslucentConversionListener)
4903 * @see TranslucentConversionListener
Chet Haaseabd3d772013-09-11 14:33:05 -07004904 *
4905 * @hide
Craig Mautner4addfc52013-06-25 08:05:45 -07004906 */
Craig Mautner5eda9b32013-07-02 11:58:16 -07004907 public void convertFromTranslucent() {
Craig Mautner4addfc52013-06-25 08:05:45 -07004908 try {
Craig Mautner5eda9b32013-07-02 11:58:16 -07004909 mTranslucentCallback = null;
Craig Mautnerbc57cd12013-08-19 15:47:42 -07004910 if (ActivityManagerNative.getDefault().convertFromTranslucent(mToken)) {
4911 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true);
4912 }
Craig Mautner4addfc52013-06-25 08:05:45 -07004913 } catch (RemoteException e) {
4914 // pass
4915 }
4916 }
4917
4918 /**
Craig Mautner5eda9b32013-07-02 11:58:16 -07004919 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} back from
4920 * opaque to translucent following a call to {@link #convertFromTranslucent()}.
4921 * <p>
4922 * Calling this allows the Activity behind this one to be seen again. Once all such Activities
4923 * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
4924 * be called indicating that it is safe to make this activity translucent again. Until
4925 * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
4926 * behind the frontmost Activity will be indeterminate.
4927 * <p>
4928 * This call has no effect on non-translucent activities or on activities with the
4929 * {@link android.R.attr#windowIsFloating} attribute.
4930 *
4931 * @param callback the method to call when all visible Activities behind this one have been
4932 * drawn and it is safe to make this Activity translucent again.
4933 *
4934 * @see #convertFromTranslucent()
4935 * @see TranslucentConversionListener
Chet Haaseabd3d772013-09-11 14:33:05 -07004936 *
4937 * @hide
Craig Mautner5eda9b32013-07-02 11:58:16 -07004938 */
4939 public void convertToTranslucent(TranslucentConversionListener callback) {
4940 try {
4941 mTranslucentCallback = callback;
Craig Mautnerbc57cd12013-08-19 15:47:42 -07004942 mChangeCanvasToTranslucent =
4943 ActivityManagerNative.getDefault().convertToTranslucent(mToken);
Craig Mautner5eda9b32013-07-02 11:58:16 -07004944 } catch (RemoteException e) {
4945 // pass
4946 }
4947 }
4948
4949 /** @hide */
4950 void onTranslucentConversionComplete(boolean drawComplete) {
4951 if (mTranslucentCallback != null) {
4952 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
4953 mTranslucentCallback = null;
4954 }
Craig Mautnerbc57cd12013-08-19 15:47:42 -07004955 if (mChangeCanvasToTranslucent) {
4956 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
4957 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07004958 }
4959
4960 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04004961 * Adjust the current immersive mode setting.
Christopher Tate73c2aee2012-03-15 16:27:14 -07004962 *
Daniel Sandler69a48172010-06-23 16:29:36 -04004963 * Note that changing this value will have no effect on the activity's
4964 * {@link android.content.pm.ActivityInfo} structure; that is, if
4965 * <code>android:immersive</code> is set to <code>true</code>
4966 * in the application's manifest entry for this activity, the {@link
4967 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
4968 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4969 * FLAG_IMMERSIVE} bit set.
4970 *
Christopher Tate73c2aee2012-03-15 16:27:14 -07004971 * @see #isImmersive()
Daniel Sandler69a48172010-06-23 16:29:36 -04004972 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4973 */
4974 public void setImmersive(boolean i) {
4975 try {
4976 ActivityManagerNative.getDefault().setImmersive(mToken, i);
4977 } catch (RemoteException e) {
4978 // pass
4979 }
4980 }
4981
Adam Powell6e346362010-07-23 10:18:23 -07004982 /**
Adam Powelldebf3be2010-11-15 18:58:48 -08004983 * Start an action mode.
Adam Powell6e346362010-07-23 10:18:23 -07004984 *
4985 * @param callback Callback that will manage lifecycle events for this context mode
4986 * @return The ContextMode that was started, or null if it was canceled
4987 *
4988 * @see ActionMode
4989 */
Adam Powell5d279772010-07-27 16:34:07 -07004990 public ActionMode startActionMode(ActionMode.Callback callback) {
Adam Powell6e346362010-07-23 10:18:23 -07004991 return mWindow.getDecorView().startActionMode(callback);
4992 }
4993
Adam Powelldebf3be2010-11-15 18:58:48 -08004994 /**
4995 * Give the Activity a chance to control the UI for an action mode requested
4996 * by the system.
4997 *
4998 * <p>Note: If you are looking for a notification callback that an action mode
4999 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
5000 *
5001 * @param callback The callback that should control the new action mode
5002 * @return The new action mode, or <code>null</code> if the activity does not want to
5003 * provide special handling for this action mode. (It will be handled by the system.)
5004 */
Craig Mautner5eda9b32013-07-02 11:58:16 -07005005 @Override
Adam Powelldebf3be2010-11-15 18:58:48 -08005006 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
Adam Powell42c0fe82010-08-10 16:36:56 -07005007 initActionBar();
Adam Powell6e346362010-07-23 10:18:23 -07005008 if (mActionBar != null) {
Adam Powell5d279772010-07-27 16:34:07 -07005009 return mActionBar.startActionMode(callback);
Adam Powell6e346362010-07-23 10:18:23 -07005010 }
5011 return null;
5012 }
5013
Adam Powelldebf3be2010-11-15 18:58:48 -08005014 /**
5015 * Notifies the Activity that an action mode has been started.
5016 * Activity subclasses overriding this method should call the superclass implementation.
5017 *
5018 * @param mode The new action mode.
5019 */
Craig Mautner5eda9b32013-07-02 11:58:16 -07005020 @Override
Adam Powelldebf3be2010-11-15 18:58:48 -08005021 public void onActionModeStarted(ActionMode mode) {
5022 }
5023
5024 /**
5025 * Notifies the activity that an action mode has finished.
5026 * Activity subclasses overriding this method should call the superclass implementation.
5027 *
5028 * @param mode The action mode that just finished.
5029 */
Craig Mautner5eda9b32013-07-02 11:58:16 -07005030 @Override
Adam Powelldebf3be2010-11-15 18:58:48 -08005031 public void onActionModeFinished(ActionMode mode) {
5032 }
5033
Adam Powelldd8fab22012-03-22 17:47:27 -07005034 /**
5035 * Returns true if the app should recreate the task when navigating 'up' from this activity
5036 * by using targetIntent.
5037 *
5038 * <p>If this method returns false the app can trivially call
5039 * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
5040 * up navigation. If this method returns false, the app should synthesize a new task stack
5041 * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
5042 *
5043 * @param targetIntent An intent representing the target destination for up navigation
5044 * @return true if navigating up should recreate a new task stack, false if the same task
5045 * should be used for the destination
5046 */
5047 public boolean shouldUpRecreateTask(Intent targetIntent) {
5048 try {
5049 PackageManager pm = getPackageManager();
5050 ComponentName cn = targetIntent.getComponent();
5051 if (cn == null) {
5052 cn = targetIntent.resolveActivity(pm);
5053 }
5054 ActivityInfo info = pm.getActivityInfo(cn, 0);
5055 if (info.taskAffinity == null) {
5056 return false;
5057 }
5058 return !ActivityManagerNative.getDefault()
5059 .targetTaskAffinityMatchesActivity(mToken, info.taskAffinity);
5060 } catch (RemoteException e) {
5061 return false;
5062 } catch (NameNotFoundException e) {
5063 return false;
5064 }
5065 }
5066
5067 /**
5068 * Navigate from this activity to the activity specified by upIntent, finishing this activity
5069 * in the process. If the activity indicated by upIntent already exists in the task's history,
5070 * this activity and all others before the indicated activity in the history stack will be
Adam Powell35c064b2012-05-02 11:37:15 -07005071 * finished.
5072 *
5073 * <p>If the indicated activity does not appear in the history stack, this will finish
5074 * each activity in this task until the root activity of the task is reached, resulting in
5075 * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
5076 * when an activity may be reached by a path not passing through a canonical parent
5077 * activity.</p>
Adam Powelldd8fab22012-03-22 17:47:27 -07005078 *
5079 * <p>This method should be used when performing up navigation from within the same task
5080 * as the destination. If up navigation should cross tasks in some cases, see
5081 * {@link #shouldUpRecreateTask(Intent)}.</p>
5082 *
5083 * @param upIntent An intent representing the target destination for up navigation
5084 *
5085 * @return true if up navigation successfully reached the activity indicated by upIntent and
5086 * upIntent was delivered to it. false if an instance of the indicated activity could
5087 * not be found and this activity was simply finished normally.
5088 */
5089 public boolean navigateUpTo(Intent upIntent) {
5090 if (mParent == null) {
5091 ComponentName destInfo = upIntent.getComponent();
5092 if (destInfo == null) {
5093 destInfo = upIntent.resolveActivity(getPackageManager());
5094 if (destInfo == null) {
5095 return false;
5096 }
5097 upIntent = new Intent(upIntent);
5098 upIntent.setComponent(destInfo);
5099 }
5100 int resultCode;
5101 Intent resultData;
5102 synchronized (this) {
5103 resultCode = mResultCode;
5104 resultData = mResultData;
5105 }
5106 if (resultData != null) {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07005107 resultData.prepareToLeaveProcess();
Adam Powelldd8fab22012-03-22 17:47:27 -07005108 }
5109 try {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07005110 upIntent.prepareToLeaveProcess();
Adam Powelldd8fab22012-03-22 17:47:27 -07005111 return ActivityManagerNative.getDefault().navigateUpTo(mToken, upIntent,
5112 resultCode, resultData);
5113 } catch (RemoteException e) {
5114 return false;
5115 }
5116 } else {
5117 return mParent.navigateUpToFromChild(this, upIntent);
5118 }
5119 }
5120
5121 /**
5122 * This is called when a child activity of this one calls its
5123 * {@link #navigateUpTo} method. The default implementation simply calls
5124 * navigateUpTo(upIntent) on this activity (the parent).
5125 *
5126 * @param child The activity making the call.
5127 * @param upIntent An intent representing the target destination for up navigation
5128 *
5129 * @return true if up navigation successfully reached the activity indicated by upIntent and
5130 * upIntent was delivered to it. false if an instance of the indicated activity could
5131 * not be found and this activity was simply finished normally.
5132 */
5133 public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
5134 return navigateUpTo(upIntent);
5135 }
5136
5137 /**
5138 * Obtain an {@link Intent} that will launch an explicit target activity specified by
5139 * this activity's logical parent. The logical parent is named in the application's manifest
5140 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
Adam Powell04d58112012-04-09 10:22:12 -07005141 * Activity subclasses may override this method to modify the Intent returned by
5142 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
5143 * the parent intent entirely.
Adam Powelldd8fab22012-03-22 17:47:27 -07005144 *
Adam Powell04d58112012-04-09 10:22:12 -07005145 * @return a new Intent targeting the defined parent of this activity or null if
5146 * there is no valid parent.
Adam Powelldd8fab22012-03-22 17:47:27 -07005147 */
5148 public Intent getParentActivityIntent() {
Adam Powell04d58112012-04-09 10:22:12 -07005149 final String parentName = mActivityInfo.parentActivityName;
5150 if (TextUtils.isEmpty(parentName)) {
5151 return null;
5152 }
Adam Powell5a4010c2012-09-16 15:14:05 -07005153
5154 // If the parent itself has no parent, generate a main activity intent.
5155 final ComponentName target = new ComponentName(this, parentName);
5156 try {
5157 final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
5158 final String parentActivity = parentInfo.parentActivityName;
5159 final Intent parentIntent = parentActivity == null
5160 ? Intent.makeMainActivity(target)
5161 : new Intent().setComponent(target);
5162 return parentIntent;
5163 } catch (NameNotFoundException e) {
5164 Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
5165 "' in manifest");
5166 return null;
5167 }
Adam Powelldd8fab22012-03-22 17:47:27 -07005168 }
5169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005170 // ------------------ Internal API ------------------
5171
5172 final void setParent(Activity parent) {
5173 mParent = parent;
5174 }
5175
5176 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
5177 Application application, Intent intent, ActivityInfo info, CharSequence title,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07005178 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005180 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07005181 lastNonConfigurationInstances, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005182 }
5183
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005184 final void attach(Context context, ActivityThread aThread,
5185 Instrumentation instr, IBinder token, int ident,
5186 Application application, Intent intent, ActivityInfo info,
5187 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07005188 NonConfigurationInstances lastNonConfigurationInstances,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005189 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005190 attachBaseContext(context);
5191
Dianne Hackborn62bea2f2012-09-04 18:48:15 -07005192 mFragments.attachActivity(this, mContainer, null);
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005194 mWindow = PolicyManager.makeNewWindow(this);
5195 mWindow.setCallback(this);
Dianne Hackborn420829e2011-01-28 11:30:35 -08005196 mWindow.getLayoutInflater().setPrivateFactory(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005197 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
5198 mWindow.setSoftInputMode(info.softInputMode);
5199 }
Adam Powell269248d2011-08-02 10:26:54 -07005200 if (info.uiOptions != 0) {
5201 mWindow.setUiOptions(info.uiOptions);
5202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 mUiThread = Thread.currentThread();
Romain Guy529b60a2010-08-03 18:05:47 -07005204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 mMainThread = aThread;
5206 mInstrumentation = instr;
5207 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005208 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 mApplication = application;
5210 mIntent = intent;
5211 mComponent = intent.getComponent();
5212 mActivityInfo = info;
5213 mTitle = title;
5214 mParent = parent;
5215 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07005216 mLastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217
Jeff Brown98365d72012-08-19 20:30:52 -07005218 mWindow.setWindowManager(
5219 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
5220 mToken, mComponent.flattenToString(),
Romain Guy529b60a2010-08-03 18:05:47 -07005221 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222 if (mParent != null) {
5223 mWindow.setContainer(mParent.getWindow());
5224 }
5225 mWindowManager = mWindow.getWindowManager();
5226 mCurrentConfig = config;
5227 }
5228
Dianne Hackborn5320eb82012-05-18 12:05:04 -07005229 /** @hide */
5230 public final IBinder getActivityToken() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005231 return mParent != null ? mParent.getActivityToken() : mToken;
5232 }
5233
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005234 final void performCreate(Bundle icicle) {
5235 onCreate(icicle);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005236 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
5237 com.android.internal.R.styleable.Window_windowNoDisplay, false);
Dianne Hackbornc8017682010-07-06 13:34:38 -07005238 mFragments.dispatchActivityCreated();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005239 }
5240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005241 final void performStart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07005242 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005243 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07005244 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005245 mInstrumentation.callActivityOnStart(this);
5246 if (!mCalled) {
5247 throw new SuperNotCalledException(
5248 "Activity " + mComponent.toShortString() +
5249 " did not call through to super.onStart()");
5250 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005251 mFragments.dispatchStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07005252 if (mAllLoaderManagers != null) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -07005253 final int N = mAllLoaderManagers.size();
5254 LoaderManagerImpl loaders[] = new LoaderManagerImpl[N];
5255 for (int i=N-1; i>=0; i--) {
5256 loaders[i] = mAllLoaderManagers.valueAt(i);
5257 }
5258 for (int i=0; i<N; i++) {
5259 LoaderManagerImpl lm = loaders[i];
5260 lm.finishRetain();
5261 lm.doReportStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07005262 }
5263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005264 }
5265
5266 final void performRestart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07005267 mFragments.noteStateNotSaved();
Dianne Hackborna21e3da2010-09-12 19:27:46 -07005268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 if (mStopped) {
5270 mStopped = false;
Dianne Hackbornce418e62011-03-01 14:31:38 -08005271 if (mToken != null && mParent == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07005272 WindowManagerGlobal.getInstance().setStoppedState(mToken, false);
Dianne Hackbornce418e62011-03-01 14:31:38 -08005273 }
Dianne Hackborn185e3e22011-06-03 15:26:01 -07005274
5275 synchronized (mManagedCursors) {
5276 final int N = mManagedCursors.size();
5277 for (int i=0; i<N; i++) {
5278 ManagedCursor mc = mManagedCursors.get(i);
5279 if (mc.mReleased || mc.mUpdated) {
5280 if (!mc.mCursor.requery()) {
Dianne Hackborna5445d32011-09-01 14:38:24 -07005281 if (getApplicationInfo().targetSdkVersion
5282 >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
5283 throw new IllegalStateException(
5284 "trying to requery an already closed cursor "
5285 + mc.mCursor);
5286 }
Dianne Hackborn185e3e22011-06-03 15:26:01 -07005287 }
5288 mc.mReleased = false;
5289 mc.mUpdated = false;
5290 }
5291 }
5292 }
5293
5294 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005295 mInstrumentation.callActivityOnRestart(this);
5296 if (!mCalled) {
5297 throw new SuperNotCalledException(
5298 "Activity " + mComponent.toShortString() +
5299 " did not call through to super.onRestart()");
5300 }
5301 performStart();
5302 }
5303 }
5304
5305 final void performResume() {
5306 performRestart();
5307
Dianne Hackborn445646c2010-06-25 15:52:59 -07005308 mFragments.execPendingActions();
5309
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07005310 mLastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 mCalled = false;
Jeff Hamilton52d32032011-01-08 15:31:26 -06005313 // mResumed is set by the instrumentation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 mInstrumentation.callActivityOnResume(this);
5315 if (!mCalled) {
5316 throw new SuperNotCalledException(
5317 "Activity " + mComponent.toShortString() +
5318 " did not call through to super.onResume()");
5319 }
5320
5321 // Now really resume, and install the current status bar and menu.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005322 mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005323
5324 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07005325 mFragments.execPendingActions();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 onPostResume();
5328 if (!mCalled) {
5329 throw new SuperNotCalledException(
5330 "Activity " + mComponent.toShortString() +
5331 " did not call through to super.onPostResume()");
5332 }
5333 }
5334
5335 final void performPause() {
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07005336 mDoReportFullyDrawn = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005337 mFragments.dispatchPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07005338 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005339 onPause();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08005340 mResumed = false;
Dianne Hackborne794e9f2010-08-24 12:32:10 -07005341 if (!mCalled && getApplicationInfo().targetSdkVersion
5342 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
5343 throw new SuperNotCalledException(
5344 "Activity " + mComponent.toShortString() +
5345 " did not call through to super.onPause()");
5346 }
Jeff Hamilton52d32032011-01-08 15:31:26 -06005347 mResumed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005348 }
5349
5350 final void performUserLeaving() {
5351 onUserInteraction();
5352 onUserLeaveHint();
5353 }
5354
5355 final void performStop() {
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07005356 mDoReportFullyDrawn = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07005357 if (mLoadersStarted) {
5358 mLoadersStarted = false;
Dianne Hackborn2707d602010-07-09 18:01:20 -07005359 if (mLoaderManager != null) {
5360 if (!mChangingConfigurations) {
5361 mLoaderManager.doStop();
5362 } else {
5363 mLoaderManager.doRetain();
5364 }
5365 }
5366 }
5367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005368 if (!mStopped) {
5369 if (mWindow != null) {
5370 mWindow.closeAllPanels();
5371 }
5372
Dianne Hackbornce418e62011-03-01 14:31:38 -08005373 if (mToken != null && mParent == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07005374 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
Dianne Hackbornce418e62011-03-01 14:31:38 -08005375 }
5376
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005377 mFragments.dispatchStop();
5378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005379 mCalled = false;
5380 mInstrumentation.callActivityOnStop(this);
5381 if (!mCalled) {
5382 throw new SuperNotCalledException(
5383 "Activity " + mComponent.toShortString() +
5384 " did not call through to super.onStop()");
5385 }
5386
Makoto Onuki2f6a0182010-02-22 13:26:59 -08005387 synchronized (mManagedCursors) {
5388 final int N = mManagedCursors.size();
5389 for (int i=0; i<N; i++) {
5390 ManagedCursor mc = mManagedCursors.get(i);
5391 if (!mc.mReleased) {
5392 mc.mCursor.deactivate();
5393 mc.mReleased = true;
5394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 }
5396 }
5397
5398 mStopped = true;
5399 }
5400 mResumed = false;
5401 }
5402
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005403 final void performDestroy() {
Dianne Hackborn6d9dcbc2012-10-02 17:51:13 -07005404 mDestroyed = true;
Dianne Hackborn291905e2010-08-17 15:17:15 -07005405 mWindow.destroy();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005406 mFragments.dispatchDestroy();
5407 onDestroy();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07005408 if (mLoaderManager != null) {
5409 mLoaderManager.doDestroy();
5410 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005411 }
5412
Jeff Hamilton52d32032011-01-08 15:31:26 -06005413 /**
5414 * @hide
5415 */
5416 public final boolean isResumed() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005417 return mResumed;
5418 }
5419
5420 void dispatchActivityResult(String who, int requestCode,
5421 int resultCode, Intent data) {
Joe Onorato43a17652011-04-06 19:22:23 -07005422 if (false) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005423 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
5424 + ", resCode=" + resultCode + ", data=" + data);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07005425 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426 if (who == null) {
5427 onActivityResult(requestCode, resultCode, data);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07005428 } else {
5429 Fragment frag = mFragments.findFragmentByWho(who);
5430 if (frag != null) {
5431 frag.onActivityResult(requestCode, resultCode, data);
5432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005433 }
5434 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07005435
5436 /**
5437 * Interface for informing a translucent {@link Activity} once all visible activities below it
5438 * have completed drawing. This is necessary only after an {@link Activity} has been made
5439 * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
5440 * translucent again following a call to {@link
5441 * Activity#convertToTranslucent(TranslucentConversionListener)}.
Chet Haaseabd3d772013-09-11 14:33:05 -07005442 *
5443 * @hide
Craig Mautner5eda9b32013-07-02 11:58:16 -07005444 */
5445 public interface TranslucentConversionListener {
5446 /**
5447 * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
5448 * below the top one have been redrawn. Following this callback it is safe to make the top
5449 * Activity translucent because the underlying Activity has been drawn.
5450 *
5451 * @param drawComplete True if the background Activity has drawn itself. False if a timeout
5452 * occurred waiting for the Activity to complete drawing.
5453 *
5454 * @see Activity#convertFromTranslucent()
5455 * @see Activity#convertToTranslucent(TranslucentConversionListener)
5456 */
5457 public void onTranslucentConversionComplete(boolean drawComplete);
5458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459}