2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 import android.annotation.CallSuper;
20 import android.annotation.DrawableRes;
21 import android.annotation.IdRes;
22 import android.annotation.IntDef;
23 import android.annotation.LayoutRes;
24 import android.annotation.MainThread;
25 import android.annotation.NonNull;
26 import android.annotation.Nullable;
27 import android.annotation.StyleRes;
28 import android.os.PersistableBundle;
29 import android.transition.Scene;
30 import android.transition.TransitionManager;
31 import android.util.ArrayMap;
32 import android.util.SuperNotCalledException;
33 import android.widget.Toolbar;
35 import com.android.internal.app.IVoiceInteractor;
36 import com.android.internal.app.WindowDecorActionBar;
37 import com.android.internal.app.ToolbarActionBar;
39 import android.annotation.SystemApi;
40 import android.app.admin.DevicePolicyManager;
41 import android.app.assist.AssistContent;
42 import android.content.ComponentCallbacks2;
43 import android.content.ComponentName;
44 import android.content.ContentResolver;
45 import android.content.Context;
46 import android.content.CursorLoader;
47 import android.content.IIntentSender;
48 import android.content.Intent;
49 import android.content.IntentSender;
50 import android.content.SharedPreferences;
51 import android.content.pm.ActivityInfo;
52 import android.content.pm.PackageManager;
53 import android.content.pm.PackageManager.NameNotFoundException;
54 import android.content.res.Configuration;
55 import android.content.res.Resources;
56 import android.content.res.TypedArray;
57 import android.database.Cursor;
58 import android.graphics.Bitmap;
59 import android.graphics.Canvas;
60 import android.graphics.drawable.Drawable;
61 import android.media.AudioManager;
62 import android.media.session.MediaController;
63 import android.net.Uri;
64 import android.os.Build;
65 import android.os.Bundle;
66 import android.os.Handler;
67 import android.os.IBinder;
68 import android.os.Looper;
69 import android.os.Parcelable;
70 import android.os.RemoteException;
71 import android.os.StrictMode;
72 import android.os.SystemProperties;
73 import android.os.UserHandle;
74 import android.text.Selection;
75 import android.text.SpannableStringBuilder;
76 import android.text.TextUtils;
77 import android.text.method.TextKeyListener;
78 import android.util.AttributeSet;
79 import android.util.EventLog;
80 import android.util.Log;
81 import android.util.PrintWriterPrinter;
82 import android.util.Slog;
83 import android.util.SparseArray;
84 import android.view.ActionMode;
85 import android.view.ContextMenu;
86 import android.view.ContextMenu.ContextMenuInfo;
87 import android.view.ContextThemeWrapper;
88 import android.view.KeyEvent;
89 import android.view.LayoutInflater;
90 import android.view.Menu;
91 import android.view.MenuInflater;
92 import android.view.MenuItem;
93 import android.view.MotionEvent;
94 import com.android.internal.policy.PhoneWindow;
95 import android.view.SearchEvent;
96 import android.view.View;
97 import android.view.View.OnCreateContextMenuListener;
98 import android.view.ViewGroup;
99 import android.view.ViewGroup.LayoutParams;
100 import android.view.ViewManager;
101 import android.view.ViewRootImpl;
102 import android.view.Window;
103 import android.view.WindowManager;
104 import android.view.WindowManagerGlobal;
105 import android.view.accessibility.AccessibilityEvent;
106 import android.widget.AdapterView;
108 import org.android_x86.analytics.AnalyticsHelper;
110 import java.io.FileDescriptor;
111 import java.io.PrintWriter;
112 import java.lang.annotation.Retention;
113 import java.lang.annotation.RetentionPolicy;
114 import java.util.ArrayList;
115 import java.util.HashMap;
116 import java.util.List;
119 * An activity is a single, focused thing that the user can do. Almost all
120 * activities interact with the user, so the Activity class takes care of
121 * creating a window for you in which you can place your UI with
122 * {@link #setContentView}. While activities are often presented to the user
123 * as full-screen windows, they can also be used in other ways: as floating
124 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
125 * or embedded inside of another activity (using {@link ActivityGroup}).
127 * There are two methods almost all subclasses of Activity will implement:
130 * <li> {@link #onCreate} is where you initialize your activity. Most
131 * importantly, here you will usually call {@link #setContentView(int)}
132 * with a layout resource defining your UI, and using {@link #findViewById}
133 * to retrieve the widgets in that UI that you need to interact with
136 * <li> {@link #onPause} is where you deal with the user leaving your
137 * activity. Most importantly, any changes made by the user should at this
138 * point be committed (usually to the
139 * {@link android.content.ContentProvider} holding the data).
142 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
143 * activity classes must have a corresponding
144 * {@link android.R.styleable#AndroidManifestActivity <activity>}
145 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
147 * <p>Topics covered here:
149 * <li><a href="#Fragments">Fragments</a>
150 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
151 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
152 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
153 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
154 * <li><a href="#Permissions">Permissions</a>
155 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
158 * <div class="special reference">
159 * <h3>Developer Guides</h3>
160 * <p>The Activity class is an important part of an application's overall lifecycle,
161 * and the way activities are launched and put together is a fundamental
162 * part of the platform's application model. For a detailed perspective on the structure of an
163 * Android application and how activities behave, please read the
164 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and
165 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
166 * developer guides.</p>
168 * <p>You can also find a detailed discussion about how to create activities in the
169 * <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a>
170 * developer guide.</p>
173 * <a name="Fragments"></a>
176 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
177 * implementations can make use of the {@link Fragment} class to better
178 * modularize their code, build more sophisticated user interfaces for larger
179 * screens, and help scale their application between small and large screens.
181 * <a name="ActivityLifecycle"></a>
182 * <h3>Activity Lifecycle</h3>
184 * <p>Activities in the system are managed as an <em>activity stack</em>.
185 * When a new activity is started, it is placed on the top of the stack
186 * and becomes the running activity -- the previous activity always remains
187 * below it in the stack, and will not come to the foreground again until
188 * the new activity exits.</p>
190 * <p>An activity has essentially four states:</p>
192 * <li> If an activity in the foreground of the screen (at the top of
194 * it is <em>active</em> or <em>running</em>. </li>
195 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
196 * or transparent activity has focus on top of your activity), it
197 * is <em>paused</em>. A paused activity is completely alive (it
198 * maintains all state and member information and remains attached to
199 * the window manager), but can be killed by the system in extreme
200 * low memory situations.
201 * <li>If an activity is completely obscured by another activity,
202 * it is <em>stopped</em>. It still retains all state and member information,
203 * however, it is no longer visible to the user so its window is hidden
204 * and it will often be killed by the system when memory is needed
206 * <li>If an activity is paused or stopped, the system can drop the activity
207 * from memory by either asking it to finish, or simply killing its
208 * process. When it is displayed again to the user, it must be
209 * completely restarted and restored to its previous state.</li>
212 * <p>The following diagram shows the important state paths of an Activity.
213 * The square rectangles represent callback methods you can implement to
214 * perform operations when the Activity moves between states. The colored
215 * ovals are major states the Activity can be in.</p>
217 * <p><img src="../../../images/activity_lifecycle.png"
218 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
220 * <p>There are three key loops you may be interested in monitoring within your
224 * <li>The <b>entire lifetime</b> of an activity happens between the first call
225 * to {@link android.app.Activity#onCreate} through to a single final call
226 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
227 * of "global" state in onCreate(), and release all remaining resources in
228 * onDestroy(). For example, if it has a thread running in the background
229 * to download data from the network, it may create that thread in onCreate()
230 * and then stop the thread in onDestroy().
232 * <li>The <b>visible lifetime</b> of an activity happens between a call to
233 * {@link android.app.Activity#onStart} until a corresponding call to
234 * {@link android.app.Activity#onStop}. During this time the user can see the
235 * activity on-screen, though it may not be in the foreground and interacting
236 * with the user. Between these two methods you can maintain resources that
237 * are needed to show the activity to the user. For example, you can register
238 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
239 * that impact your UI, and unregister it in onStop() when the user no
240 * longer sees what you are displaying. The onStart() and onStop() methods
241 * can be called multiple times, as the activity becomes visible and hidden
244 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
245 * {@link android.app.Activity#onResume} until a corresponding call to
246 * {@link android.app.Activity#onPause}. During this time the activity is
247 * in front of all other activities and interacting with the user. An activity
248 * can frequently go between the resumed and paused states -- for example when
249 * the device goes to sleep, when an activity result is delivered, when a new
250 * intent is delivered -- so the code in these methods should be fairly
254 * <p>The entire lifecycle of an activity is defined by the following
255 * Activity methods. All of these are hooks that you can override
256 * to do appropriate work when the activity changes state. All
257 * activities will implement {@link android.app.Activity#onCreate}
258 * to do their initial setup; many will also implement
259 * {@link android.app.Activity#onPause} to commit changes to data and
260 * otherwise prepare to stop interacting with the user. You should always
261 * call up to your superclass when implementing these methods.</p>
264 * <pre class="prettyprint">
265 * public class Activity extends ApplicationContext {
266 * protected void onCreate(Bundle savedInstanceState);
268 * protected void onStart();
270 * protected void onRestart();
272 * protected void onResume();
274 * protected void onPause();
276 * protected void onStop();
278 * protected void onDestroy();
282 * <p>In general the movement through an activity's lifecycle looks like
285 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
286 * <colgroup align="left" span="3" />
287 * <colgroup align="left" />
288 * <colgroup align="center" />
289 * <colgroup align="center" />
292 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
296 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
297 * <td>Called when the activity is first created.
298 * This is where you should do all of your normal static set up:
299 * create views, bind data to lists, etc. This method also
300 * provides you with a Bundle containing the activity's previously
301 * frozen state, if there was one.
302 * <p>Always followed by <code>onStart()</code>.</td>
303 * <td align="center">No</td>
304 * <td align="center"><code>onStart()</code></td>
307 * <tr><td rowspan="5" style="border-left: none; border-right: none;"> </td>
308 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
309 * <td>Called after your activity has been stopped, prior to it being
311 * <p>Always followed by <code>onStart()</code></td>
312 * <td align="center">No</td>
313 * <td align="center"><code>onStart()</code></td>
316 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
317 * <td>Called when the activity is becoming visible to the user.
318 * <p>Followed by <code>onResume()</code> if the activity comes
319 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
320 * <td align="center">No</td>
321 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
324 * <tr><td rowspan="2" style="border-left: none;"> </td>
325 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
326 * <td>Called when the activity will start
327 * interacting with the user. At this point your activity is at
328 * the top of the activity stack, with user input going to it.
329 * <p>Always followed by <code>onPause()</code>.</td>
330 * <td align="center">No</td>
331 * <td align="center"><code>onPause()</code></td>
334 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
335 * <td>Called when the system is about to start resuming a previous
336 * activity. This is typically used to commit unsaved changes to
337 * persistent data, stop animations and other things that may be consuming
338 * CPU, etc. Implementations of this method must be very quick because
339 * the next activity will not be resumed until this method returns.
340 * <p>Followed by either <code>onResume()</code> if the activity
341 * returns back to the front, or <code>onStop()</code> if it becomes
342 * invisible to the user.</td>
343 * <td align="center"><font color="#800000"><strong>Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB}</strong></font></td>
344 * <td align="center"><code>onResume()</code> or<br>
345 * <code>onStop()</code></td>
348 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
349 * <td>Called when the activity is no longer visible to the user, because
350 * another activity has been resumed and is covering this one. This
351 * may happen either because a new activity is being started, an existing
352 * one is being brought in front of this one, or this one is being
354 * <p>Followed by either <code>onRestart()</code> if
355 * this activity is coming back to interact with the user, or
356 * <code>onDestroy()</code> if this activity is going away.</td>
357 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
358 * <td align="center"><code>onRestart()</code> or<br>
359 * <code>onDestroy()</code></td>
362 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
363 * <td>The final call you receive before your
364 * activity is destroyed. This can happen either because the
365 * activity is finishing (someone called {@link Activity#finish} on
366 * it, or because the system is temporarily destroying this
367 * instance of the activity to save space. You can distinguish
368 * between these two scenarios with the {@link
369 * Activity#isFinishing} method.</td>
370 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
371 * <td align="center"><em>nothing</em></td>
376 * <p>Note the "Killable" column in the above table -- for those methods that
377 * are marked as being killable, after that method returns the process hosting the
378 * activity may be killed by the system <em>at any time</em> without another line
379 * of its code being executed. Because of this, you should use the
380 * {@link #onPause} method to write any persistent data (such as user edits)
381 * to storage. In addition, the method
382 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
383 * in such a background state, allowing you to save away any dynamic instance
384 * state in your activity into the given Bundle, to be later received in
385 * {@link #onCreate} if the activity needs to be re-created.
386 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
387 * section for more information on how the lifecycle of a process is tied
388 * to the activities it is hosting. Note that it is important to save
389 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
390 * because the latter is not part of the lifecycle callbacks, so will not
391 * be called in every situation as described in its documentation.</p>
393 * <p class="note">Be aware that these semantics will change slightly between
394 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
395 * vs. those targeting prior platforms. Starting with Honeycomb, an application
396 * is not in the killable state until its {@link #onStop} has returned. This
397 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
398 * safely called after {@link #onPause()} and allows and application to safely
399 * wait until {@link #onStop()} to save persistent state.</p>
401 * <p>For those methods that are not marked as being killable, the activity's
402 * process will not be killed by the system starting from the time the method
403 * is called and continuing after it returns. Thus an activity is in the killable
404 * state, for example, between after <code>onPause()</code> to the start of
405 * <code>onResume()</code>.</p>
407 * <a name="ConfigurationChanges"></a>
408 * <h3>Configuration Changes</h3>
410 * <p>If the configuration of the device (as defined by the
411 * {@link Configuration Resources.Configuration} class) changes,
412 * then anything displaying a user interface will need to update to match that
413 * configuration. Because Activity is the primary mechanism for interacting
414 * with the user, it includes special support for handling configuration
417 * <p>Unless you specify otherwise, a configuration change (such as a change
418 * in screen orientation, language, input devices, etc) will cause your
419 * current activity to be <em>destroyed</em>, going through the normal activity
420 * lifecycle process of {@link #onPause},
421 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
422 * had been in the foreground or visible to the user, once {@link #onDestroy} is
423 * called in that instance then a new instance of the activity will be
424 * created, with whatever savedInstanceState the previous instance had generated
425 * from {@link #onSaveInstanceState}.</p>
427 * <p>This is done because any application resource,
428 * including layout files, can change based on any configuration value. Thus
429 * the only safe way to handle a configuration change is to re-retrieve all
430 * resources, including layouts, drawables, and strings. Because activities
431 * must already know how to save their state and re-create themselves from
432 * that state, this is a convenient way to have an activity restart itself
433 * with a new configuration.</p>
435 * <p>In some special cases, you may want to bypass restarting of your
436 * activity based on one or more types of configuration changes. This is
437 * done with the {@link android.R.attr#configChanges android:configChanges}
438 * attribute in its manifest. For any types of configuration changes you say
439 * that you handle there, you will receive a call to your current activity's
440 * {@link #onConfigurationChanged} method instead of being restarted. If
441 * a configuration change involves any that you do not handle, however, the
442 * activity will still be restarted and {@link #onConfigurationChanged}
443 * will not be called.</p>
445 * <a name="StartingActivities"></a>
446 * <h3>Starting Activities and Getting Results</h3>
448 * <p>The {@link android.app.Activity#startActivity}
449 * method is used to start a
450 * new activity, which will be placed at the top of the activity stack. It
451 * takes a single argument, an {@link android.content.Intent Intent},
452 * which describes the activity
453 * to be executed.</p>
455 * <p>Sometimes you want to get a result back from an activity when it
456 * ends. For example, you may start an activity that lets the user pick
457 * a person in a list of contacts; when it ends, it returns the person
458 * that was selected. To do this, you call the
459 * {@link android.app.Activity#startActivityForResult(Intent, int)}
460 * version with a second integer parameter identifying the call. The result
461 * will come back through your {@link android.app.Activity#onActivityResult}
464 * <p>When an activity exits, it can call
465 * {@link android.app.Activity#setResult(int)}
466 * to return data back to its parent. It must always supply a result code,
467 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
468 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
469 * return back an Intent containing any additional data it wants. All of this
470 * information appears back on the
471 * parent's <code>Activity.onActivityResult()</code>, along with the integer
472 * identifier it originally supplied.</p>
474 * <p>If a child activity fails for any reason (such as crashing), the parent
475 * activity will receive a result with the code RESULT_CANCELED.</p>
477 * <pre class="prettyprint">
478 * public class MyActivity extends Activity {
481 * static final int PICK_CONTACT_REQUEST = 0;
483 * public boolean onKeyDown(int keyCode, KeyEvent event) {
484 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
485 * // When the user center presses, let them pick a contact.
486 * startActivityForResult(
487 * new Intent(Intent.ACTION_PICK,
488 * new Uri("content://contacts")),
489 * PICK_CONTACT_REQUEST);
495 * protected void onActivityResult(int requestCode, int resultCode,
497 * if (requestCode == PICK_CONTACT_REQUEST) {
498 * if (resultCode == RESULT_OK) {
499 * // A contact was picked. Here we will just display it
501 * startActivity(new Intent(Intent.ACTION_VIEW, data));
508 * <a name="SavingPersistentState"></a>
509 * <h3>Saving Persistent State</h3>
511 * <p>There are generally two kinds of persistent state than an activity
512 * will deal with: shared document-like data (typically stored in a SQLite
513 * database using a {@linkplain android.content.ContentProvider content provider})
514 * and internal state such as user preferences.</p>
516 * <p>For content provider data, we suggest that activities use a
517 * "edit in place" user model. That is, any edits a user makes are effectively
518 * made immediately without requiring an additional confirmation step.
519 * Supporting this model is generally a simple matter of following two rules:</p>
522 * <li> <p>When creating a new document, the backing database entry or file for
523 * it is created immediately. For example, if the user chooses to write
524 * a new e-mail, a new entry for that e-mail is created as soon as they
525 * start entering data, so that if they go to any other activity after
526 * that point this e-mail will now appear in the list of drafts.</p>
527 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
528 * commit to the backing content provider or file any changes the user
529 * has made. This ensures that those changes will be seen by any other
530 * activity that is about to run. You will probably want to commit
531 * your data even more aggressively at key times during your
532 * activity's lifecycle: for example before starting a new
533 * activity, before finishing your own activity, when the user
534 * switches between input fields, etc.</p>
537 * <p>This model is designed to prevent data loss when a user is navigating
538 * between activities, and allows the system to safely kill an activity (because
539 * system resources are needed somewhere else) at any time after it has been
540 * paused. Note this implies
541 * that the user pressing BACK from your activity does <em>not</em>
542 * mean "cancel" -- it means to leave the activity with its current contents
543 * saved away. Canceling edits in an activity must be provided through
544 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
546 * <p>See the {@linkplain android.content.ContentProvider content package} for
547 * more information about content providers. These are a key aspect of how
548 * different activities invoke and propagate data between themselves.</p>
550 * <p>The Activity class also provides an API for managing internal persistent state
551 * associated with an activity. This can be used, for example, to remember
552 * the user's preferred initial display in a calendar (day view or week view)
553 * or the user's default home page in a web browser.</p>
555 * <p>Activity persistent state is managed
556 * with the method {@link #getPreferences},
557 * allowing you to retrieve and
558 * modify a set of name/value pairs associated with the activity. To use
559 * preferences that are shared across multiple application components
560 * (activities, receivers, services, providers), you can use the underlying
561 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
562 * to retrieve a preferences
563 * object stored under a specific name.
564 * (Note that it is not possible to share settings data across application
565 * packages -- for that you will need a content provider.)</p>
567 * <p>Here is an excerpt from a calendar activity that stores the user's
568 * preferred view mode in its persistent settings:</p>
570 * <pre class="prettyprint">
571 * public class CalendarActivity extends Activity {
574 * static final int DAY_VIEW_MODE = 0;
575 * static final int WEEK_VIEW_MODE = 1;
577 * private SharedPreferences mPrefs;
578 * private int mCurViewMode;
580 * protected void onCreate(Bundle savedInstanceState) {
581 * super.onCreate(savedInstanceState);
583 * SharedPreferences mPrefs = getSharedPreferences();
584 * mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
587 * protected void onPause() {
590 * SharedPreferences.Editor ed = mPrefs.edit();
591 * ed.putInt("view_mode", mCurViewMode);
597 * <a name="Permissions"></a>
598 * <h3>Permissions</h3>
600 * <p>The ability to start a particular Activity can be enforced when it is
602 * manifest's {@link android.R.styleable#AndroidManifestActivity <activity>}
603 * tag. By doing so, other applications will need to declare a corresponding
604 * {@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>}
605 * element in their own manifest to be able to start that activity.
607 * <p>When starting an Activity you can set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
608 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
609 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the
610 * Activity access to the specific URIs in the Intent. Access will remain
611 * until the Activity has finished (it will remain across the hosting
612 * process being killed and other temporary destruction). As of
613 * {@link android.os.Build.VERSION_CODES#GINGERBREAD}, if the Activity
614 * was already created and a new Intent is being delivered to
615 * {@link #onNewIntent(Intent)}, any newly granted URI permissions will be added
616 * to the existing ones it holds.
618 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
619 * document for more information on permissions and security in general.
621 * <a name="ProcessLifecycle"></a>
622 * <h3>Process Lifecycle</h3>
624 * <p>The Android system attempts to keep application process around for as
625 * long as possible, but eventually will need to remove old processes when
626 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
627 * Lifecycle</a>, the decision about which process to remove is intimately
628 * tied to the state of the user's interaction with it. In general, there
629 * are four states a process can be in based on the activities running in it,
630 * listed here in order of importance. The system will kill less important
631 * processes (the last ones) before it resorts to killing more important
632 * processes (the first ones).
635 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
636 * that the user is currently interacting with) is considered the most important.
637 * Its process will only be killed as a last resort, if it uses more memory
638 * than is available on the device. Generally at this point the device has
639 * reached a memory paging state, so this is required in order to keep the user
640 * interface responsive.
641 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
642 * but not in the foreground, such as one sitting behind a foreground dialog)
643 * is considered extremely important and will not be killed unless that is
644 * required to keep the foreground activity running.
645 * <li> <p>A <b>background activity</b> (an activity that is not visible to
646 * the user and has been paused) is no longer critical, so the system may
647 * safely kill its process to reclaim memory for other foreground or
648 * visible processes. If its process needs to be killed, when the user navigates
649 * back to the activity (making it visible on the screen again), its
650 * {@link #onCreate} method will be called with the savedInstanceState it had previously
651 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
652 * state as the user last left it.
653 * <li> <p>An <b>empty process</b> is one hosting no activities or other
654 * application components (such as {@link Service} or
655 * {@link android.content.BroadcastReceiver} classes). These are killed very
656 * quickly by the system as memory becomes low. For this reason, any
657 * background operation you do outside of an activity must be executed in the
658 * context of an activity BroadcastReceiver or Service to ensure that the system
659 * knows it needs to keep your process around.
662 * <p>Sometimes an Activity may need to do a long-running operation that exists
663 * independently of the activity lifecycle itself. An example may be a camera
664 * application that allows you to upload a picture to a web site. The upload
665 * may take a long time, and the application should allow the user to leave
666 * the application will it is executing. To accomplish this, your Activity
667 * should start a {@link Service} in which the upload takes place. This allows
668 * the system to properly prioritize your process (considering it to be more
669 * important than other non-visible applications) for the duration of the
670 * upload, independent of whether the original activity is paused, stopped,
673 public class Activity extends ContextThemeWrapper
674 implements LayoutInflater.Factory2,
675 Window.Callback, KeyEvent.Callback,
676 OnCreateContextMenuListener, ComponentCallbacks2,
677 Window.OnWindowDismissedCallback {
678 private static final String TAG = "Activity";
679 private static final boolean DEBUG_LIFECYCLE = false;
681 /** Standard activity result: operation canceled. */
682 public static final int RESULT_CANCELED = 0;
683 /** Standard activity result: operation succeeded. */
684 public static final int RESULT_OK = -1;
685 /** Start of user-defined activity results. */
686 public static final int RESULT_FIRST_USER = 1;
688 static final String FRAGMENTS_TAG = "android:fragments";
690 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
691 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
692 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
693 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
694 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
695 private static final String HAS_CURENT_PERMISSIONS_REQUEST_KEY =
696 "android:hasCurrentPermissionsRequest";
698 private static final String REQUEST_PERMISSIONS_WHO_PREFIX = "@android:requestPermissions:";
700 private static class ManagedDialog {
704 private SparseArray<ManagedDialog> mManagedDialogs;
706 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
707 private Instrumentation mInstrumentation;
708 private IBinder mToken;
710 /*package*/ String mEmbeddedID;
711 private Application mApplication;
712 /*package*/ Intent mIntent;
713 /*package*/ String mReferrer;
714 private ComponentName mComponent;
715 /*package*/ ActivityInfo mActivityInfo;
716 /*package*/ ActivityThread mMainThread;
719 /*package*/ boolean mResumed;
720 private boolean mStopped;
722 boolean mStartedActivity;
723 private boolean mDestroyed;
724 private boolean mAppsStatistics;
725 private boolean mDoReportFullyDrawn = true;
726 /** true if the activity is going through a transient pause */
727 /*package*/ boolean mTemporaryPause = false;
728 /** true if the activity is being destroyed in order to recreate it with a new configuration */
729 /*package*/ boolean mChangingConfigurations = false;
730 /*package*/ int mConfigChangeFlags;
731 /*package*/ Configuration mCurrentConfig;
732 private SearchManager mSearchManager;
733 private MenuInflater mMenuInflater;
735 static final class NonConfigurationInstances {
737 HashMap<String, Object> children;
738 List<Fragment> fragments;
739 ArrayMap<String, LoaderManager> loaders;
740 VoiceInteractor voiceInteractor;
742 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
744 private Window mWindow;
746 private WindowManager mWindowManager;
747 /*package*/ View mDecor = null;
748 /*package*/ boolean mWindowAdded = false;
749 /*package*/ boolean mVisibleFromServer = false;
750 /*package*/ boolean mVisibleFromClient = true;
751 /*package*/ ActionBar mActionBar = null;
752 private boolean mEnableDefaultActionBarUp;
754 private VoiceInteractor mVoiceInteractor;
756 private CharSequence mTitle;
757 private int mTitleColor = 0;
759 // we must have a handler before the FragmentController is constructed
760 final Handler mHandler = new Handler();
761 final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
763 // Most recent call to requestVisibleBehind().
764 boolean mVisibleBehind;
766 private static final class ManagedCursor {
767 ManagedCursor(Cursor cursor) {
773 private final Cursor mCursor;
774 private boolean mReleased;
775 private boolean mUpdated;
777 private final ArrayList<ManagedCursor> mManagedCursors =
778 new ArrayList<ManagedCursor>();
780 // protected by synchronized (this)
781 int mResultCode = RESULT_CANCELED;
782 Intent mResultData = null;
784 private TranslucentConversionListener mTranslucentCallback;
785 private boolean mChangeCanvasToTranslucent;
787 private SearchEvent mSearchEvent;
789 private boolean mTitleReady = false;
790 private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
792 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
793 private SpannableStringBuilder mDefaultKeySsb = null;
795 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
797 @SuppressWarnings("unused")
798 private final Object mInstanceTracker = StrictMode.trackActivity(this);
800 private Thread mUiThread;
802 ActivityTransitionState mActivityTransitionState = new ActivityTransitionState();
803 SharedElementCallback mEnterTransitionListener = SharedElementCallback.NULL_CALLBACK;
804 SharedElementCallback mExitTransitionListener = SharedElementCallback.NULL_CALLBACK;
806 private boolean mHasCurrentPermissionsRequest;
808 /** Return the intent that started this activity. */
809 public Intent getIntent() {
814 * Change the intent returned by {@link #getIntent}. This holds a
815 * reference to the given intent; it does not copy it. Often used in
816 * conjunction with {@link #onNewIntent}.
818 * @param newIntent The new Intent object to return from getIntent
823 public void setIntent(Intent newIntent) {
827 /** Return the application that owns this activity. */
828 public final Application getApplication() {
832 /** Is this activity embedded inside of another activity? */
833 public final boolean isChild() {
834 return mParent != null;
837 /** Return the parent activity if this view is an embedded child. */
838 public final Activity getParent() {
842 /** Retrieve the window manager for showing custom windows. */
843 public WindowManager getWindowManager() {
844 return mWindowManager;
848 * Retrieve the current {@link android.view.Window} for the activity.
849 * This can be used to directly access parts of the Window API that
850 * are not available through Activity/Screen.
852 * @return Window The current window, or null if the activity is not
855 public Window getWindow() {
860 * Return the LoaderManager for this activity, creating it if needed.
862 public LoaderManager getLoaderManager() {
863 return mFragments.getLoaderManager();
867 * Calls {@link android.view.Window#getCurrentFocus} on the
868 * Window of this Activity to return the currently focused view.
870 * @return View The current View with focus or null.
873 * @see android.view.Window#getCurrentFocus
876 public View getCurrentFocus() {
877 return mWindow != null ? mWindow.getCurrentFocus() : null;
881 * Called when the activity is starting. This is where most initialization
882 * should go: calling {@link #setContentView(int)} to inflate the
883 * activity's UI, using {@link #findViewById} to programmatically interact
884 * with widgets in the UI, calling
885 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
886 * cursors for data being displayed, etc.
888 * <p>You can call {@link #finish} from within this function, in
889 * which case onDestroy() will be immediately called without any of the rest
890 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
891 * {@link #onPause}, etc) executing.
893 * <p><em>Derived classes must call through to the super class's
894 * implementation of this method. If they do not, an exception will be
897 * @param savedInstanceState If the activity is being re-initialized after
898 * previously being shut down then this Bundle contains the data it most
899 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
902 * @see #onSaveInstanceState
903 * @see #onRestoreInstanceState
908 protected void onCreate(@Nullable Bundle savedInstanceState) {
909 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
910 if (mLastNonConfigurationInstances != null) {
911 mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
913 if (mActivityInfo.parentActivityName != null) {
914 if (mActionBar == null) {
915 mEnableDefaultActionBarUp = true;
917 mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
920 if (savedInstanceState != null) {
921 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
922 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
923 ? mLastNonConfigurationInstances.fragments : null);
925 mFragments.dispatchCreate();
926 getApplication().dispatchActivityCreated(this, savedInstanceState);
927 if (mVoiceInteractor != null) {
928 mVoiceInteractor.attachActivity(this);
931 mAppsStatistics = SystemProperties.getBoolean("persist.sys.apps_statistics", false);
935 * Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
936 * the attribute {@link android.R.attr#persistableMode} set to
937 * <code>persistAcrossReboots</code>.
939 * @param savedInstanceState if the activity is being re-initialized after
940 * previously being shut down then this Bundle contains the data it most
941 * recently supplied in {@link #onSaveInstanceState}.
942 * <b><i>Note: Otherwise it is null.</i></b>
943 * @param persistentState if the activity is being re-initialized after
944 * previously being shut down or powered off then this Bundle contains the data it most
945 * recently supplied to outPersistentState in {@link #onSaveInstanceState}.
946 * <b><i>Note: Otherwise it is null.</i></b>
948 * @see #onCreate(android.os.Bundle)
950 * @see #onSaveInstanceState
951 * @see #onRestoreInstanceState
954 public void onCreate(@Nullable Bundle savedInstanceState,
955 @Nullable PersistableBundle persistentState) {
956 onCreate(savedInstanceState);
960 * The hook for {@link ActivityThread} to restore the state of this activity.
962 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
963 * {@link #restoreManagedDialogs(android.os.Bundle)}.
965 * @param savedInstanceState contains the saved state
967 final void performRestoreInstanceState(Bundle savedInstanceState) {
968 onRestoreInstanceState(savedInstanceState);
969 restoreManagedDialogs(savedInstanceState);
973 * The hook for {@link ActivityThread} to restore the state of this activity.
975 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
976 * {@link #restoreManagedDialogs(android.os.Bundle)}.
978 * @param savedInstanceState contains the saved state
979 * @param persistentState contains the persistable saved state
981 final void performRestoreInstanceState(Bundle savedInstanceState,
982 PersistableBundle persistentState) {
983 onRestoreInstanceState(savedInstanceState, persistentState);
984 if (savedInstanceState != null) {
985 restoreManagedDialogs(savedInstanceState);
990 * This method is called after {@link #onStart} when the activity is
991 * being re-initialized from a previously saved state, given here in
992 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
993 * to restore their state, but it is sometimes convenient to do it here
994 * after all of the initialization has been done or to allow subclasses to
995 * decide whether to use your default implementation. The default
996 * implementation of this method performs a restore of any view state that
997 * had previously been frozen by {@link #onSaveInstanceState}.
999 * <p>This method is called between {@link #onStart} and
1000 * {@link #onPostCreate}.
1002 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1005 * @see #onPostCreate
1007 * @see #onSaveInstanceState
1009 protected void onRestoreInstanceState(Bundle savedInstanceState) {
1010 if (mWindow != null) {
1011 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
1012 if (windowState != null) {
1013 mWindow.restoreHierarchyState(windowState);
1019 * This is the same as {@link #onRestoreInstanceState(Bundle)} but is called for activities
1020 * created with the attribute {@link android.R.attr#persistableMode} set to
1021 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1022 * came from the restored PersistableBundle first
1023 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1025 * <p>This method is called between {@link #onStart} and
1026 * {@link #onPostCreate}.
1028 * <p>If this method is called {@link #onRestoreInstanceState(Bundle)} will not be called.
1030 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1031 * @param persistentState the data most recently supplied in {@link #onSaveInstanceState}.
1033 * @see #onRestoreInstanceState(Bundle)
1035 * @see #onPostCreate
1037 * @see #onSaveInstanceState
1039 public void onRestoreInstanceState(Bundle savedInstanceState,
1040 PersistableBundle persistentState) {
1041 if (savedInstanceState != null) {
1042 onRestoreInstanceState(savedInstanceState);
1047 * Restore the state of any saved managed dialogs.
1049 * @param savedInstanceState The bundle to restore from.
1051 private void restoreManagedDialogs(Bundle savedInstanceState) {
1052 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
1057 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
1058 final int numDialogs = ids.length;
1059 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
1060 for (int i = 0; i < numDialogs; i++) {
1061 final Integer dialogId = ids[i];
1062 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
1063 if (dialogState != null) {
1064 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
1065 // so tell createDialog() not to do it, otherwise we get an exception
1066 final ManagedDialog md = new ManagedDialog();
1067 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
1068 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
1069 if (md.mDialog != null) {
1070 mManagedDialogs.put(dialogId, md);
1071 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
1072 md.mDialog.onRestoreInstanceState(dialogState);
1078 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
1079 final Dialog dialog = onCreateDialog(dialogId, args);
1080 if (dialog == null) {
1083 dialog.dispatchOnCreate(state);
1087 private static String savedDialogKeyFor(int key) {
1088 return SAVED_DIALOG_KEY_PREFIX + key;
1091 private static String savedDialogArgsKeyFor(int key) {
1092 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
1096 * Called when activity start-up is complete (after {@link #onStart}
1097 * and {@link #onRestoreInstanceState} have been called). Applications will
1098 * generally not implement this method; it is intended for system
1099 * classes to do final initialization after application code has run.
1101 * <p><em>Derived classes must call through to the super class's
1102 * implementation of this method. If they do not, an exception will be
1105 * @param savedInstanceState If the activity is being re-initialized after
1106 * previously being shut down then this Bundle contains the data it most
1107 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
1111 protected void onPostCreate(@Nullable Bundle savedInstanceState) {
1114 onTitleChanged(getTitle(), getTitleColor());
1120 * This is the same as {@link #onPostCreate(Bundle)} but is called for activities
1121 * created with the attribute {@link android.R.attr#persistableMode} set to
1122 * <code>persistAcrossReboots</code>.
1124 * @param savedInstanceState The data most recently supplied in {@link #onSaveInstanceState}
1125 * @param persistentState The data caming from the PersistableBundle first
1126 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1130 public void onPostCreate(@Nullable Bundle savedInstanceState,
1131 @Nullable PersistableBundle persistentState) {
1132 onPostCreate(savedInstanceState);
1136 * Called after {@link #onCreate} — or after {@link #onRestart} when
1137 * the activity had been stopped, but is now again being displayed to the
1138 * user. It will be followed by {@link #onResume}.
1140 * <p><em>Derived classes must call through to the super class's
1141 * implementation of this method. If they do not, an exception will be
1149 protected void onStart() {
1150 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
1153 mFragments.doLoaderStart();
1155 // region @android-x86-analytics
1157 if (mAppsStatistics) {
1158 AnalyticsHelper.hitScreen(this);
1161 getApplication().dispatchActivityStarted(this);
1165 * Called after {@link #onStop} when the current activity is being
1166 * re-displayed to the user (the user has navigated back to it). It will
1167 * be followed by {@link #onStart} and then {@link #onResume}.
1169 * <p>For activities that are using raw {@link Cursor} objects (instead of
1170 * creating them through
1171 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1172 * this is usually the place
1173 * where the cursor should be requeried (because you had deactivated it in
1176 * <p><em>Derived classes must call through to the super class's
1177 * implementation of this method. If they do not, an exception will be
1185 protected void onRestart() {
1190 * Called when an {@link #onResume} is coming up, prior to other pre-resume callbacks
1191 * such as {@link #onNewIntent} and {@link #onActivityResult}. This is primarily intended
1192 * to give the activity a hint that its state is no longer saved -- it will generally
1193 * be called after {@link #onSaveInstanceState} and prior to the activity being
1194 * resumed/started again.
1196 public void onStateNotSaved() {
1200 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1201 * {@link #onPause}, for your activity to start interacting with the user.
1202 * This is a good place to begin animations, open exclusive-access devices
1203 * (such as the camera), etc.
1205 * <p>Keep in mind that onResume is not the best indicator that your activity
1206 * is visible to the user; a system window such as the keyguard may be in
1207 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1208 * activity is visible to the user (for example, to resume a game).
1210 * <p><em>Derived classes must call through to the super class's
1211 * implementation of this method. If they do not, an exception will be
1214 * @see #onRestoreInstanceState
1216 * @see #onPostResume
1220 protected void onResume() {
1221 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this);
1222 getApplication().dispatchActivityResumed(this);
1223 mActivityTransitionState.onResume();
1228 * Called when activity resume is complete (after {@link #onResume} has
1229 * been called). Applications will generally not implement this method;
1230 * it is intended for system classes to do final setup after application
1231 * resume code has run.
1233 * <p><em>Derived classes must call through to the super class's
1234 * implementation of this method. If they do not, an exception will be
1240 protected void onPostResume() {
1241 final Window win = getWindow();
1242 if (win != null) win.makeActive();
1243 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
1248 * Check whether this activity is running as part of a voice interaction with the user.
1249 * If true, it should perform its interaction with the user through the
1250 * {@link VoiceInteractor} returned by {@link #getVoiceInteractor}.
1252 public boolean isVoiceInteraction() {
1253 return mVoiceInteractor != null;
1257 * Like {@link #isVoiceInteraction}, but only returns true if this is also the root
1258 * of a voice interaction. That is, returns true if this activity was directly
1259 * started by the voice interaction service as the initiation of a voice interaction.
1260 * Otherwise, for example if it was started by another activity while under voice
1261 * interaction, returns false.
1263 public boolean isVoiceInteractionRoot() {
1265 return mVoiceInteractor != null
1266 && ActivityManagerNative.getDefault().isRootVoiceInteraction(mToken);
1267 } catch (RemoteException e) {
1273 * Retrieve the active {@link VoiceInteractor} that the user is going through to
1274 * interact with this activity.
1276 public VoiceInteractor getVoiceInteractor() {
1277 return mVoiceInteractor;
1281 * This is called for activities that set launchMode to "singleTop" in
1282 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1283 * flag when calling {@link #startActivity}. In either case, when the
1284 * activity is re-launched while at the top of the activity stack instead
1285 * of a new instance of the activity being started, onNewIntent() will be
1286 * called on the existing instance with the Intent that was used to
1289 * <p>An activity will always be paused before receiving a new intent, so
1290 * you can count on {@link #onResume} being called after this method.
1292 * <p>Note that {@link #getIntent} still returns the original Intent. You
1293 * can use {@link #setIntent} to update it to this new Intent.
1295 * @param intent The new intent that was started for the activity.
1301 protected void onNewIntent(Intent intent) {
1305 * The hook for {@link ActivityThread} to save the state of this activity.
1307 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1308 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1310 * @param outState The bundle to save the state to.
1312 final void performSaveInstanceState(Bundle outState) {
1313 onSaveInstanceState(outState);
1314 saveManagedDialogs(outState);
1315 mActivityTransitionState.saveState(outState);
1316 storeHasCurrentPermissionRequest(outState);
1317 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState);
1321 * The hook for {@link ActivityThread} to save the state of this activity.
1323 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1324 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1326 * @param outState The bundle to save the state to.
1327 * @param outPersistentState The bundle to save persistent state to.
1329 final void performSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1330 onSaveInstanceState(outState, outPersistentState);
1331 saveManagedDialogs(outState);
1332 storeHasCurrentPermissionRequest(outState);
1333 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState +
1334 ", " + outPersistentState);
1338 * Called to retrieve per-instance state from an activity before being killed
1339 * so that the state can be restored in {@link #onCreate} or
1340 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1341 * will be passed to both).
1343 * <p>This method is called before an activity may be killed so that when it
1344 * comes back some time in the future it can restore its state. For example,
1345 * if activity B is launched in front of activity A, and at some point activity
1346 * A is killed to reclaim resources, activity A will have a chance to save the
1347 * current state of its user interface via this method so that when the user
1348 * returns to activity A, the state of the user interface can be restored
1349 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1351 * <p>Do not confuse this method with activity lifecycle callbacks such as
1352 * {@link #onPause}, which is always called when an activity is being placed
1353 * in the background or on its way to destruction, or {@link #onStop} which
1354 * is called before destruction. One example of when {@link #onPause} and
1355 * {@link #onStop} is called and not this method is when a user navigates back
1356 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1357 * on B because that particular instance will never be restored, so the
1358 * system avoids calling it. An example when {@link #onPause} is called and
1359 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1360 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1361 * killed during the lifetime of B since the state of the user interface of
1362 * A will stay intact.
1364 * <p>The default implementation takes care of most of the UI per-instance
1365 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1366 * view in the hierarchy that has an id, and by saving the id of the currently
1367 * focused view (all of which is restored by the default implementation of
1368 * {@link #onRestoreInstanceState}). If you override this method to save additional
1369 * information not captured by each individual view, you will likely want to
1370 * call through to the default implementation, otherwise be prepared to save
1371 * all of the state of each view yourself.
1373 * <p>If called, this method will occur before {@link #onStop}. There are
1374 * no guarantees about whether it will occur before or after {@link #onPause}.
1376 * @param outState Bundle in which to place your saved state.
1379 * @see #onRestoreInstanceState
1382 protected void onSaveInstanceState(Bundle outState) {
1383 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
1384 Parcelable p = mFragments.saveAllState();
1386 outState.putParcelable(FRAGMENTS_TAG, p);
1388 getApplication().dispatchActivitySaveInstanceState(this, outState);
1392 * This is the same as {@link #onSaveInstanceState} but is called for activities
1393 * created with the attribute {@link android.R.attr#persistableMode} set to
1394 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1395 * in will be saved and presented in {@link #onCreate(Bundle, PersistableBundle)}
1396 * the first time that this activity is restarted following the next device reboot.
1398 * @param outState Bundle in which to place your saved state.
1399 * @param outPersistentState State which will be saved across reboots.
1401 * @see #onSaveInstanceState(Bundle)
1403 * @see #onRestoreInstanceState(Bundle, PersistableBundle)
1406 public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1407 onSaveInstanceState(outState);
1411 * Save the state of any managed dialogs.
1413 * @param outState place to store the saved state.
1415 private void saveManagedDialogs(Bundle outState) {
1416 if (mManagedDialogs == null) {
1420 final int numDialogs = mManagedDialogs.size();
1421 if (numDialogs == 0) {
1425 Bundle dialogState = new Bundle();
1427 int[] ids = new int[mManagedDialogs.size()];
1429 // save each dialog's bundle, gather the ids
1430 for (int i = 0; i < numDialogs; i++) {
1431 final int key = mManagedDialogs.keyAt(i);
1433 final ManagedDialog md = mManagedDialogs.valueAt(i);
1434 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1435 if (md.mArgs != null) {
1436 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1440 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1441 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1446 * Called as part of the activity lifecycle when an activity is going into
1447 * the background, but has not (yet) been killed. The counterpart to
1448 * {@link #onResume}.
1450 * <p>When activity B is launched in front of activity A, this callback will
1451 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1452 * so be sure to not do anything lengthy here.
1454 * <p>This callback is mostly used for saving any persistent state the
1455 * activity is editing, to present a "edit in place" model to the user and
1456 * making sure nothing is lost if there are not enough resources to start
1457 * the new activity without first killing this one. This is also a good
1458 * place to do things like stop animations and other things that consume a
1459 * noticeable amount of CPU in order to make the switch to the next activity
1460 * as fast as possible, or to close resources that are exclusive access
1461 * such as the camera.
1463 * <p>In situations where the system needs more memory it may kill paused
1464 * processes to reclaim resources. Because of this, you should be sure
1465 * that all of your state is saved by the time you return from
1466 * this function. In general {@link #onSaveInstanceState} is used to save
1467 * per-instance state in the activity and this method is used to store
1468 * global persistent data (in content providers, files, etc.)
1470 * <p>After receiving this call you will usually receive a following call
1471 * to {@link #onStop} (after the next activity has been resumed and
1472 * displayed), however in some cases there will be a direct call back to
1473 * {@link #onResume} without going through the stopped state.
1475 * <p><em>Derived classes must call through to the super class's
1476 * implementation of this method. If they do not, an exception will be
1480 * @see #onSaveInstanceState
1484 protected void onPause() {
1485 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this);
1486 getApplication().dispatchActivityPaused(this);
1491 * Called as part of the activity lifecycle when an activity is about to go
1492 * into the background as the result of user choice. For example, when the
1493 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1494 * when an incoming phone call causes the in-call Activity to be automatically
1495 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1496 * the activity being interrupted. In cases when it is invoked, this method
1497 * is called right before the activity's {@link #onPause} callback.
1499 * <p>This callback and {@link #onUserInteraction} are intended to help
1500 * activities manage status bar notifications intelligently; specifically,
1501 * for helping activities determine the proper time to cancel a notfication.
1503 * @see #onUserInteraction()
1505 protected void onUserLeaveHint() {
1509 * Generate a new thumbnail for this activity. This method is called before
1510 * pausing the activity, and should draw into <var>outBitmap</var> the
1511 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1512 * can use the given <var>canvas</var>, which is configured to draw into the
1513 * bitmap, for rendering if desired.
1515 * <p>The default implementation returns fails and does not draw a thumbnail;
1516 * this will result in the platform creating its own thumbnail if needed.
1518 * @param outBitmap The bitmap to contain the thumbnail.
1519 * @param canvas Can be used to render into the bitmap.
1521 * @return Return true if you have drawn into the bitmap; otherwise after
1522 * you return it will be filled with a default thumbnail.
1524 * @see #onCreateDescription
1525 * @see #onSaveInstanceState
1528 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
1533 * Generate a new description for this activity. This method is called
1534 * before pausing the activity and can, if desired, return some textual
1535 * description of its current state to be displayed to the user.
1537 * <p>The default implementation returns null, which will cause you to
1538 * inherit the description from the previous activity. If all activities
1539 * return null, generally the label of the top activity will be used as the
1542 * @return A description of what the user is doing. It should be short and
1543 * sweet (only a few words).
1545 * @see #onCreateThumbnail
1546 * @see #onSaveInstanceState
1550 public CharSequence onCreateDescription() {
1555 * This is called when the user is requesting an assist, to build a full
1556 * {@link Intent#ACTION_ASSIST} Intent with all of the context of the current
1557 * application. You can override this method to place into the bundle anything
1558 * you would like to appear in the {@link Intent#EXTRA_ASSIST_CONTEXT} part
1559 * of the assist Intent.
1561 * <p>This function will be called after any global assist callbacks that had
1562 * been registered with {@link Application#registerOnProvideAssistDataListener
1563 * Application.registerOnProvideAssistDataListener}.
1565 public void onProvideAssistData(Bundle data) {
1569 * This is called when the user is requesting an assist, to provide references
1570 * to content related to the current activity. Before being called, the
1571 * {@code outContent} Intent is filled with the base Intent of the activity (the Intent
1572 * returned by {@link #getIntent()}). The Intent's extras are stripped of any types
1573 * that are not valid for {@link PersistableBundle} or non-framework Parcelables, and
1574 * the flags {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} and
1575 * {@link Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION} are cleared from the Intent.
1577 * <p>Custom implementation may adjust the content intent to better reflect the top-level
1578 * context of the activity, and fill in its ClipData with additional content of
1579 * interest that the user is currently viewing. For example, an image gallery application
1580 * that has launched in to an activity allowing the user to swipe through pictures should
1581 * modify the intent to reference the current image they are looking it; such an
1582 * application when showing a list of pictures should add a ClipData that has
1583 * references to all of the pictures currently visible on screen.</p>
1585 * @param outContent The assist content to return.
1587 public void onProvideAssistContent(AssistContent outContent) {
1591 * Ask to have the current assistant shown to the user. This only works if the calling
1592 * activity is the current foreground activity. It is the same as calling
1593 * {@link android.service.voice.VoiceInteractionService#showSession
1594 * VoiceInteractionService.showSession} and requesting all of the possible context.
1595 * The receiver will always see
1596 * {@link android.service.voice.VoiceInteractionSession#SHOW_SOURCE_APPLICATION} set.
1597 * @return Returns true if the assistant was successfully invoked, else false. For example
1598 * false will be returned if the caller is not the current top activity.
1600 public boolean showAssist(Bundle args) {
1602 return ActivityManagerNative.getDefault().showAssistFromActivity(mToken, args);
1603 } catch (RemoteException e) {
1609 * Called when you are no longer visible to the user. You will next
1610 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1611 * depending on later user activity.
1613 * <p>Note that this method may never be called, in low memory situations
1614 * where the system does not have enough memory to keep your activity's
1615 * process running after its {@link #onPause} method is called.
1617 * <p><em>Derived classes must call through to the super class's
1618 * implementation of this method. If they do not, an exception will be
1623 * @see #onSaveInstanceState
1627 protected void onStop() {
1628 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
1629 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
1630 mActivityTransitionState.onStop();
1631 getApplication().dispatchActivityStopped(this);
1632 mTranslucentCallback = null;
1637 * Perform any final cleanup before an activity is destroyed. This can
1638 * happen either because the activity is finishing (someone called
1639 * {@link #finish} on it, or because the system is temporarily destroying
1640 * this instance of the activity to save space. You can distinguish
1641 * between these two scenarios with the {@link #isFinishing} method.
1643 * <p><em>Note: do not count on this method being called as a place for
1644 * saving data! For example, if an activity is editing data in a content
1645 * provider, those edits should be committed in either {@link #onPause} or
1646 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1647 * free resources like threads that are associated with an activity, so
1648 * that a destroyed activity does not leave such things around while the
1649 * rest of its application is still running. There are situations where
1650 * the system will simply kill the activity's hosting process without
1651 * calling this method (or any others) in it, so it should not be used to
1652 * do things that are intended to remain around after the process goes
1655 * <p><em>Derived classes must call through to the super class's
1656 * implementation of this method. If they do not, an exception will be
1665 protected void onDestroy() {
1666 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
1669 // dismiss any dialogs we are managing.
1670 if (mManagedDialogs != null) {
1671 final int numDialogs = mManagedDialogs.size();
1672 for (int i = 0; i < numDialogs; i++) {
1673 final ManagedDialog md = mManagedDialogs.valueAt(i);
1674 if (md.mDialog.isShowing()) {
1675 md.mDialog.dismiss();
1678 mManagedDialogs = null;
1681 // close any cursors we are managing.
1682 synchronized (mManagedCursors) {
1683 int numCursors = mManagedCursors.size();
1684 for (int i = 0; i < numCursors; i++) {
1685 ManagedCursor c = mManagedCursors.get(i);
1690 mManagedCursors.clear();
1693 // Close any open search dialog
1694 if (mSearchManager != null) {
1695 mSearchManager.stopSearch();
1698 getApplication().dispatchActivityDestroyed(this);
1702 * Report to the system that your app is now fully drawn, purely for diagnostic
1703 * purposes (calling it does not impact the visible behavior of the activity).
1704 * This is only used to help instrument application launch times, so that the
1705 * app can report when it is fully in a usable state; without this, the only thing
1706 * the system itself can determine is the point at which the activity's window
1707 * is <em>first</em> drawn and displayed. To participate in app launch time
1708 * measurement, you should always call this method after first launch (when
1709 * {@link #onCreate(android.os.Bundle)} is called), at the point where you have
1710 * entirely drawn your UI and populated with all of the significant data. You
1711 * can safely call this method any time after first launch as well, in which case
1712 * it will simply be ignored.
1714 public void reportFullyDrawn() {
1715 if (mDoReportFullyDrawn) {
1716 mDoReportFullyDrawn = false;
1718 ActivityManagerNative.getDefault().reportActivityFullyDrawn(mToken);
1719 } catch (RemoteException e) {
1725 * Called by the system when the device configuration changes while your
1726 * activity is running. Note that this will <em>only</em> be called if
1727 * you have selected configurations you would like to handle with the
1728 * {@link android.R.attr#configChanges} attribute in your manifest. If
1729 * any configuration change occurs that is not selected to be reported
1730 * by that attribute, then instead of reporting it the system will stop
1731 * and restart the activity (to have it launched with the new
1734 * <p>At the time that this function has been called, your Resources
1735 * object will have been updated to return resource values matching the
1736 * new configuration.
1738 * @param newConfig The new device configuration.
1740 public void onConfigurationChanged(Configuration newConfig) {
1741 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onConfigurationChanged " + this + ": " + newConfig);
1744 mFragments.dispatchConfigurationChanged(newConfig);
1746 if (mWindow != null) {
1747 // Pass the configuration changed event to the window
1748 mWindow.onConfigurationChanged(newConfig);
1751 if (mActionBar != null) {
1752 // Do this last; the action bar will need to access
1753 // view changes from above.
1754 mActionBar.onConfigurationChanged(newConfig);
1759 * If this activity is being destroyed because it can not handle a
1760 * configuration parameter being changed (and thus its
1761 * {@link #onConfigurationChanged(Configuration)} method is
1762 * <em>not</em> being called), then you can use this method to discover
1763 * the set of changes that have occurred while in the process of being
1764 * destroyed. Note that there is no guarantee that these will be
1765 * accurate (other changes could have happened at any time), so you should
1766 * only use this as an optimization hint.
1768 * @return Returns a bit field of the configuration parameters that are
1769 * changing, as defined by the {@link android.content.res.Configuration}
1772 public int getChangingConfigurations() {
1773 return mConfigChangeFlags;
1777 * Retrieve the non-configuration instance data that was previously
1778 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1779 * be available from the initial {@link #onCreate} and
1780 * {@link #onStart} calls to the new instance, allowing you to extract
1781 * any useful dynamic state from the previous instance.
1783 * <p>Note that the data you retrieve here should <em>only</em> be used
1784 * as an optimization for handling configuration changes. You should always
1785 * be able to handle getting a null pointer back, and an activity must
1786 * still be able to restore itself to its previous state (through the
1787 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1788 * function returns null.
1790 * @return Returns the object previously returned by
1791 * {@link #onRetainNonConfigurationInstance()}.
1793 * @deprecated Use the new {@link Fragment} API
1794 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
1795 * available on older platforms through the Android compatibility package.
1799 public Object getLastNonConfigurationInstance() {
1800 return mLastNonConfigurationInstances != null
1801 ? mLastNonConfigurationInstances.activity : null;
1805 * Called by the system, as part of destroying an
1806 * activity due to a configuration change, when it is known that a new
1807 * instance will immediately be created for the new configuration. You
1808 * can return any object you like here, including the activity instance
1809 * itself, which can later be retrieved by calling
1810 * {@link #getLastNonConfigurationInstance()} in the new activity
1813 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1814 * or later, consider instead using a {@link Fragment} with
1815 * {@link Fragment#setRetainInstance(boolean)
1816 * Fragment.setRetainInstance(boolean}.</em>
1818 * <p>This function is called purely as an optimization, and you must
1819 * not rely on it being called. When it is called, a number of guarantees
1820 * will be made to help optimize configuration switching:
1822 * <li> The function will be called between {@link #onStop} and
1823 * {@link #onDestroy}.
1824 * <li> A new instance of the activity will <em>always</em> be immediately
1825 * created after this one's {@link #onDestroy()} is called. In particular,
1826 * <em>no</em> messages will be dispatched during this time (when the returned
1827 * object does not have an activity to be associated with).
1828 * <li> The object you return here will <em>always</em> be available from
1829 * the {@link #getLastNonConfigurationInstance()} method of the following
1830 * activity instance as described there.
1833 * <p>These guarantees are designed so that an activity can use this API
1834 * to propagate extensive state from the old to new activity instance, from
1835 * loaded bitmaps, to network connections, to evenly actively running
1836 * threads. Note that you should <em>not</em> propagate any data that
1837 * may change based on the configuration, including any data loaded from
1838 * resources such as strings, layouts, or drawables.
1840 * <p>The guarantee of no message handling during the switch to the next
1841 * activity simplifies use with active objects. For example if your retained
1842 * state is an {@link android.os.AsyncTask} you are guaranteed that its
1843 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
1844 * not be called from the call here until you execute the next instance's
1845 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
1846 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
1847 * running in a separate thread.)
1849 * @return Return any Object holding the desired state to propagate to the
1850 * next activity instance.
1852 * @deprecated Use the new {@link Fragment} API
1853 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
1854 * available on older platforms through the Android compatibility package.
1856 public Object onRetainNonConfigurationInstance() {
1861 * Retrieve the non-configuration instance data that was previously
1862 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1863 * be available from the initial {@link #onCreate} and
1864 * {@link #onStart} calls to the new instance, allowing you to extract
1865 * any useful dynamic state from the previous instance.
1867 * <p>Note that the data you retrieve here should <em>only</em> be used
1868 * as an optimization for handling configuration changes. You should always
1869 * be able to handle getting a null pointer back, and an activity must
1870 * still be able to restore itself to its previous state (through the
1871 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1872 * function returns null.
1874 * @return Returns the object previously returned by
1875 * {@link #onRetainNonConfigurationChildInstances()}
1878 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1879 return mLastNonConfigurationInstances != null
1880 ? mLastNonConfigurationInstances.children : null;
1884 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1885 * it should return either a mapping from child activity id strings to arbitrary objects,
1886 * or null. This method is intended to be used by Activity framework subclasses that control a
1887 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1888 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1891 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1895 NonConfigurationInstances retainNonConfigurationInstances() {
1896 Object activity = onRetainNonConfigurationInstance();
1897 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1898 List<Fragment> fragments = mFragments.retainNonConfig();
1899 ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
1900 if (activity == null && children == null && fragments == null && loaders == null
1901 && mVoiceInteractor == null) {
1905 NonConfigurationInstances nci = new NonConfigurationInstances();
1906 nci.activity = activity;
1907 nci.children = children;
1908 nci.fragments = fragments;
1909 nci.loaders = loaders;
1910 if (mVoiceInteractor != null) {
1911 mVoiceInteractor.retainInstance();
1912 nci.voiceInteractor = mVoiceInteractor;
1917 public void onLowMemory() {
1918 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onLowMemory " + this);
1920 mFragments.dispatchLowMemory();
1923 public void onTrimMemory(int level) {
1924 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onTrimMemory " + this + ": " + level);
1926 mFragments.dispatchTrimMemory(level);
1930 * Return the FragmentManager for interacting with fragments associated
1931 * with this activity.
1933 public FragmentManager getFragmentManager() {
1934 return mFragments.getFragmentManager();
1938 * Called when a Fragment is being attached to this activity, immediately
1939 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1940 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1942 public void onAttachFragment(Fragment fragment) {
1947 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1948 * that gives the resulting {@link Cursor} to call
1949 * {@link #startManagingCursor} so that the activity will manage its
1950 * lifecycle for you.
1952 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1953 * or later, consider instead using {@link LoaderManager} instead, available
1954 * via {@link #getLoaderManager()}.</em>
1956 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
1957 * this method, because the activity will do that for you at the appropriate time. However, if
1958 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
1959 * not</em> automatically close the cursor and, in that case, you must call
1960 * {@link Cursor#close()}.</p>
1962 * @param uri The URI of the content provider to query.
1963 * @param projection List of columns to return.
1964 * @param selection SQL WHERE clause.
1965 * @param sortOrder SQL ORDER BY clause.
1967 * @return The Cursor that was returned by query().
1969 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1970 * @see #startManagingCursor
1973 * @deprecated Use {@link CursorLoader} instead.
1976 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1978 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1980 startManagingCursor(c);
1987 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1988 * that gives the resulting {@link Cursor} to call
1989 * {@link #startManagingCursor} so that the activity will manage its
1990 * lifecycle for you.
1992 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1993 * or later, consider instead using {@link LoaderManager} instead, available
1994 * via {@link #getLoaderManager()}.</em>
1996 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
1997 * this method, because the activity will do that for you at the appropriate time. However, if
1998 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
1999 * not</em> automatically close the cursor and, in that case, you must call
2000 * {@link Cursor#close()}.</p>
2002 * @param uri The URI of the content provider to query.
2003 * @param projection List of columns to return.
2004 * @param selection SQL WHERE clause.
2005 * @param selectionArgs The arguments to selection, if any ?s are pesent
2006 * @param sortOrder SQL ORDER BY clause.
2008 * @return The Cursor that was returned by query().
2010 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
2011 * @see #startManagingCursor
2013 * @deprecated Use {@link CursorLoader} instead.
2016 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
2017 String[] selectionArgs, String sortOrder) {
2018 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
2020 startManagingCursor(c);
2026 * This method allows the activity to take care of managing the given
2027 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
2028 * That is, when the activity is stopped it will automatically call
2029 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
2030 * it will call {@link Cursor#requery} for you. When the activity is
2031 * destroyed, all managed Cursors will be closed automatically.
2033 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2034 * or later, consider instead using {@link LoaderManager} instead, available
2035 * via {@link #getLoaderManager()}.</em>
2037 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on cursor obtained from
2038 * {@link #managedQuery}, because the activity will do that for you at the appropriate time.
2039 * However, if you call {@link #stopManagingCursor} on a cursor from a managed query, the system
2040 * <em>will not</em> automatically close the cursor and, in that case, you must call
2041 * {@link Cursor#close()}.</p>
2043 * @param c The Cursor to be managed.
2045 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
2046 * @see #stopManagingCursor
2048 * @deprecated Use the new {@link android.content.CursorLoader} class with
2049 * {@link LoaderManager} instead; this is also
2050 * available on older platforms through the Android compatibility package.
2053 public void startManagingCursor(Cursor c) {
2054 synchronized (mManagedCursors) {
2055 mManagedCursors.add(new ManagedCursor(c));
2060 * Given a Cursor that was previously given to
2061 * {@link #startManagingCursor}, stop the activity's management of that
2064 * <p><strong>Warning:</strong> After calling this method on a cursor from a managed query,
2065 * the system <em>will not</em> automatically close the cursor and you must call
2066 * {@link Cursor#close()}.</p>
2068 * @param c The Cursor that was being managed.
2070 * @see #startManagingCursor
2072 * @deprecated Use the new {@link android.content.CursorLoader} class with
2073 * {@link LoaderManager} instead; this is also
2074 * available on older platforms through the Android compatibility package.
2077 public void stopManagingCursor(Cursor c) {
2078 synchronized (mManagedCursors) {
2079 final int N = mManagedCursors.size();
2080 for (int i=0; i<N; i++) {
2081 ManagedCursor mc = mManagedCursors.get(i);
2082 if (mc.mCursor == c) {
2083 mManagedCursors.remove(i);
2091 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
2096 public void setPersistent(boolean isPersistent) {
2100 * Finds a view that was identified by the id attribute from the XML that
2101 * was processed in {@link #onCreate}.
2103 * @return The view if found or null otherwise.
2106 public View findViewById(@IdRes int id) {
2107 return getWindow().findViewById(id);
2111 * Retrieve a reference to this activity's ActionBar.
2113 * @return The Activity's ActionBar, or null if it does not have one.
2116 public ActionBar getActionBar() {
2117 initWindowDecorActionBar();
2122 * Set a {@link android.widget.Toolbar Toolbar} to act as the {@link ActionBar} for this
2125 * <p>When set to a non-null value the {@link #getActionBar()} method will return
2126 * an {@link ActionBar} object that can be used to control the given toolbar as if it were
2127 * a traditional window decor action bar. The toolbar's menu will be populated with the
2128 * Activity's options menu and the navigation button will be wired through the standard
2129 * {@link android.R.id#home home} menu select action.</p>
2131 * <p>In order to use a Toolbar within the Activity's window content the application
2132 * must not request the window feature {@link Window#FEATURE_ACTION_BAR FEATURE_ACTION_BAR}.</p>
2134 * @param toolbar Toolbar to set as the Activity's action bar
2136 public void setActionBar(@Nullable Toolbar toolbar) {
2137 if (getActionBar() instanceof WindowDecorActionBar) {
2138 throw new IllegalStateException("This Activity already has an action bar supplied " +
2139 "by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " +
2140 "android:windowActionBar to false in your theme to use a Toolbar instead.");
2142 // Clear out the MenuInflater to make sure that it is valid for the new Action Bar
2143 mMenuInflater = null;
2145 ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this);
2147 mWindow.setCallback(tbab.getWrappedWindowCallback());
2148 mActionBar.invalidateOptionsMenu();
2152 * Creates a new ActionBar, locates the inflated ActionBarView,
2153 * initializes the ActionBar with the view, and sets mActionBar.
2155 private void initWindowDecorActionBar() {
2156 Window window = getWindow();
2158 // Initializing the window decor can change window feature flags.
2159 // Make sure that we have the correct set before performing the test below.
2160 window.getDecorView();
2162 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
2166 mActionBar = new WindowDecorActionBar(this);
2167 mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
2169 mWindow.setDefaultIcon(mActivityInfo.getIconResource());
2170 mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
2174 * Set the activity content from a layout resource. The resource will be
2175 * inflated, adding all top-level views to the activity.
2177 * @param layoutResID Resource ID to be inflated.
2179 * @see #setContentView(android.view.View)
2180 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2182 public void setContentView(@LayoutRes int layoutResID) {
2183 getWindow().setContentView(layoutResID);
2184 initWindowDecorActionBar();
2188 * Set the activity content to an explicit view. This view is placed
2189 * directly into the activity's view hierarchy. It can itself be a complex
2190 * view hierarchy. When calling this method, the layout parameters of the
2191 * specified view are ignored. Both the width and the height of the view are
2192 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
2193 * your own layout parameters, invoke
2194 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
2197 * @param view The desired content to display.
2199 * @see #setContentView(int)
2200 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2202 public void setContentView(View view) {
2203 getWindow().setContentView(view);
2204 initWindowDecorActionBar();
2208 * Set the activity content to an explicit view. This view is placed
2209 * directly into the activity's view hierarchy. It can itself be a complex
2212 * @param view The desired content to display.
2213 * @param params Layout parameters for the view.
2215 * @see #setContentView(android.view.View)
2216 * @see #setContentView(int)
2218 public void setContentView(View view, ViewGroup.LayoutParams params) {
2219 getWindow().setContentView(view, params);
2220 initWindowDecorActionBar();
2224 * Add an additional content view to the activity. Added after any existing
2225 * ones in the activity -- existing views are NOT removed.
2227 * @param view The desired content to display.
2228 * @param params Layout parameters for the view.
2230 public void addContentView(View view, ViewGroup.LayoutParams params) {
2231 getWindow().addContentView(view, params);
2232 initWindowDecorActionBar();
2236 * Retrieve the {@link TransitionManager} responsible for default transitions in this window.
2237 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2239 * <p>This method will return non-null after content has been initialized (e.g. by using
2240 * {@link #setContentView}) if {@link Window#FEATURE_CONTENT_TRANSITIONS} has been granted.</p>
2242 * @return This window's content TransitionManager or null if none is set.
2244 public TransitionManager getContentTransitionManager() {
2245 return getWindow().getTransitionManager();
2249 * Set the {@link TransitionManager} to use for default transitions in this window.
2250 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2252 * @param tm The TransitionManager to use for scene changes.
2254 public void setContentTransitionManager(TransitionManager tm) {
2255 getWindow().setTransitionManager(tm);
2259 * Retrieve the {@link Scene} representing this window's current content.
2260 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2262 * <p>This method will return null if the current content is not represented by a Scene.</p>
2264 * @return Current Scene being shown or null
2266 public Scene getContentScene() {
2267 return getWindow().getContentScene();
2271 * Sets whether this activity is finished when touched outside its window's
2274 public void setFinishOnTouchOutside(boolean finish) {
2275 mWindow.setCloseOnTouchOutside(finish);
2280 DEFAULT_KEYS_DISABLE,
2281 DEFAULT_KEYS_DIALER,
2282 DEFAULT_KEYS_SHORTCUT,
2283 DEFAULT_KEYS_SEARCH_LOCAL,
2284 DEFAULT_KEYS_SEARCH_GLOBAL})
2285 @Retention(RetentionPolicy.SOURCE)
2286 @interface DefaultKeyMode {}
2289 * Use with {@link #setDefaultKeyMode} to turn off default handling of
2292 * @see #setDefaultKeyMode
2294 static public final int DEFAULT_KEYS_DISABLE = 0;
2296 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
2299 * @see #setDefaultKeyMode
2301 static public final int DEFAULT_KEYS_DIALER = 1;
2303 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
2304 * default key handling.
2306 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
2308 * @see #setDefaultKeyMode
2310 static public final int DEFAULT_KEYS_SHORTCUT = 2;
2312 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2313 * will start an application-defined search. (If the application or activity does not
2314 * actually define a search, the the keys will be ignored.)
2316 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2318 * @see #setDefaultKeyMode
2320 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
2323 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2324 * will start a global search (typically web search, but some platforms may define alternate
2325 * methods for global search)
2327 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2329 * @see #setDefaultKeyMode
2331 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
2334 * Select the default key handling for this activity. This controls what
2335 * will happen to key events that are not otherwise handled. The default
2336 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
2337 * floor. Other modes allow you to launch the dialer
2338 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
2339 * menu without requiring the menu key be held down
2340 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
2341 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
2343 * <p>Note that the mode selected here does not impact the default
2344 * handling of system keys, such as the "back" and "menu" keys, and your
2345 * activity and its views always get a first chance to receive and handle
2346 * all application keys.
2348 * @param mode The desired default key mode constant.
2350 * @see #DEFAULT_KEYS_DISABLE
2351 * @see #DEFAULT_KEYS_DIALER
2352 * @see #DEFAULT_KEYS_SHORTCUT
2353 * @see #DEFAULT_KEYS_SEARCH_LOCAL
2354 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
2357 public final void setDefaultKeyMode(@DefaultKeyMode int mode) {
2358 mDefaultKeyMode = mode;
2360 // Some modes use a SpannableStringBuilder to track & dispatch input events
2361 // This list must remain in sync with the switch in onKeyDown()
2363 case DEFAULT_KEYS_DISABLE:
2364 case DEFAULT_KEYS_SHORTCUT:
2365 mDefaultKeySsb = null; // not used in these modes
2367 case DEFAULT_KEYS_DIALER:
2368 case DEFAULT_KEYS_SEARCH_LOCAL:
2369 case DEFAULT_KEYS_SEARCH_GLOBAL:
2370 mDefaultKeySsb = new SpannableStringBuilder();
2371 Selection.setSelection(mDefaultKeySsb,0);
2374 throw new IllegalArgumentException();
2379 * Called when a key was pressed down and not handled by any of the views
2380 * inside of the activity. So, for example, key presses while the cursor
2381 * is inside a TextView will not trigger the event (unless it is a navigation
2382 * to another object) because TextView handles its own key presses.
2384 * <p>If the focused view didn't want this event, this method is called.
2386 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
2387 * by calling {@link #onBackPressed()}, though the behavior varies based
2388 * on the application compatibility mode: for
2389 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
2390 * it will set up the dispatch to call {@link #onKeyUp} where the action
2391 * will be performed; for earlier applications, it will perform the
2392 * action immediately in on-down, as those versions of the platform
2395 * <p>Other additional default key handling may be performed
2396 * if configured with {@link #setDefaultKeyMode}.
2398 * @return Return <code>true</code> to prevent this event from being propagated
2399 * further, or <code>false</code> to indicate that you have not handled
2400 * this event and it should continue to be propagated.
2402 * @see android.view.KeyEvent
2404 public boolean onKeyDown(int keyCode, KeyEvent event) {
2405 if (keyCode == KeyEvent.KEYCODE_BACK) {
2406 if (getApplicationInfo().targetSdkVersion
2407 >= Build.VERSION_CODES.ECLAIR) {
2408 event.startTracking();
2415 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
2417 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
2418 Window w = getWindow();
2419 if (w.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
2420 w.performPanelShortcut(Window.FEATURE_OPTIONS_PANEL, keyCode, event,
2421 Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
2426 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
2427 boolean clearSpannable = false;
2429 if ((event.getRepeatCount() != 0) || event.isSystem()) {
2430 clearSpannable = true;
2433 handled = TextKeyListener.getInstance().onKeyDown(
2434 null, mDefaultKeySsb, keyCode, event);
2435 if (handled && mDefaultKeySsb.length() > 0) {
2436 // something useable has been typed - dispatch it now.
2438 final String str = mDefaultKeySsb.toString();
2439 clearSpannable = true;
2441 switch (mDefaultKeyMode) {
2442 case DEFAULT_KEYS_DIALER:
2443 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
2444 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2445 startActivity(intent);
2447 case DEFAULT_KEYS_SEARCH_LOCAL:
2448 startSearch(str, false, null, false);
2450 case DEFAULT_KEYS_SEARCH_GLOBAL:
2451 startSearch(str, false, null, true);
2456 if (clearSpannable) {
2457 mDefaultKeySsb.clear();
2458 mDefaultKeySsb.clearSpans();
2459 Selection.setSelection(mDefaultKeySsb,0);
2466 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2467 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2470 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2475 * Called when a key was released and not handled by any of the views
2476 * inside of the activity. So, for example, key presses while the cursor
2477 * is inside a TextView will not trigger the event (unless it is a navigation
2478 * to another object) because TextView handles its own key presses.
2480 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2483 * @return Return <code>true</code> to prevent this event from being propagated
2484 * further, or <code>false</code> to indicate that you have not handled
2485 * this event and it should continue to be propagated.
2489 public boolean onKeyUp(int keyCode, KeyEvent event) {
2490 if (getApplicationInfo().targetSdkVersion
2491 >= Build.VERSION_CODES.ECLAIR) {
2492 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2493 && !event.isCanceled()) {
2502 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2503 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2506 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2511 * Called when the activity has detected the user's press of the back
2512 * key. The default implementation simply finishes the current activity,
2513 * but you can override this to do whatever you want.
2515 public void onBackPressed() {
2516 if (mActionBar != null && mActionBar.collapseActionView()) {
2520 if (!mFragments.getFragmentManager().popBackStackImmediate()) {
2521 finishAfterTransition();
2526 * Called when a key shortcut event is not handled by any of the views in the Activity.
2527 * Override this method to implement global key shortcuts for the Activity.
2528 * Key shortcuts can also be implemented by setting the
2529 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
2531 * @param keyCode The value in event.getKeyCode().
2532 * @param event Description of the key event.
2533 * @return True if the key shortcut was handled.
2535 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2536 // Let the Action Bar have a chance at handling the shortcut.
2537 ActionBar actionBar = getActionBar();
2538 return (actionBar != null && actionBar.onKeyShortcut(keyCode, event));
2542 * Called when a touch screen event was not handled by any of the views
2543 * under it. This is most useful to process touch events that happen
2544 * outside of your window bounds, where there is no view to receive it.
2546 * @param event The touch screen event being processed.
2548 * @return Return true if you have consumed the event, false if you haven't.
2549 * The default implementation always returns false.
2551 public boolean onTouchEvent(MotionEvent event) {
2552 if (mWindow.shouldCloseOnTouch(this, event)) {
2561 * Called when the trackball was moved and not handled by any of the
2562 * views inside of the activity. So, for example, if the trackball moves
2563 * while focus is on a button, you will receive a call here because
2564 * buttons do not normally do anything with trackball events. The call
2565 * here happens <em>before</em> trackball movements are converted to
2566 * DPAD key events, which then get sent back to the view hierarchy, and
2567 * will be processed at the point for things like focus navigation.
2569 * @param event The trackball event being processed.
2571 * @return Return true if you have consumed the event, false if you haven't.
2572 * The default implementation always returns false.
2574 public boolean onTrackballEvent(MotionEvent event) {
2579 * Called when a generic motion event was not handled by any of the
2580 * views inside of the activity.
2582 * Generic motion events describe joystick movements, mouse hovers, track pad
2583 * touches, scroll wheel movements and other input events. The
2584 * {@link MotionEvent#getSource() source} of the motion event specifies
2585 * the class of input that was received. Implementations of this method
2586 * must examine the bits in the source before processing the event.
2587 * The following code example shows how this is done.
2589 * Generic motion events with source class
2590 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
2591 * are delivered to the view under the pointer. All other generic motion events are
2592 * delivered to the focused view.
2594 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
2595 * handle this event.
2598 * @param event The generic motion event being processed.
2600 * @return Return true if you have consumed the event, false if you haven't.
2601 * The default implementation always returns false.
2603 public boolean onGenericMotionEvent(MotionEvent event) {
2608 * Called whenever a key, touch, or trackball event is dispatched to the
2609 * activity. Implement this method if you wish to know that the user has
2610 * interacted with the device in some way while your activity is running.
2611 * This callback and {@link #onUserLeaveHint} are intended to help
2612 * activities manage status bar notifications intelligently; specifically,
2613 * for helping activities determine the proper time to cancel a notfication.
2615 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2616 * be accompanied by calls to {@link #onUserInteraction}. This
2617 * ensures that your activity will be told of relevant user activity such
2618 * as pulling down the notification pane and touching an item there.
2620 * <p>Note that this callback will be invoked for the touch down action
2621 * that begins a touch gesture, but may not be invoked for the touch-moved
2622 * and touch-up actions that follow.
2624 * @see #onUserLeaveHint()
2626 public void onUserInteraction() {
2629 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2630 // Update window manager if: we have a view, that view is
2631 // attached to its parent (which will be a RootView), and
2632 // this activity is not embedded.
2633 if (mParent == null) {
2634 View decor = mDecor;
2635 if (decor != null && decor.getParent() != null) {
2636 getWindowManager().updateViewLayout(decor, params);
2641 public void onContentChanged() {
2645 * Called when the current {@link Window} of the activity gains or loses
2646 * focus. This is the best indicator of whether this activity is visible
2647 * to the user. The default implementation clears the key tracking
2648 * state, so should always be called.
2650 * <p>Note that this provides information about global focus state, which
2651 * is managed independently of activity lifecycles. As such, while focus
2652 * changes will generally have some relation to lifecycle changes (an
2653 * activity that is stopped will not generally get window focus), you
2654 * should not rely on any particular order between the callbacks here and
2655 * those in the other lifecycle methods such as {@link #onResume}.
2657 * <p>As a general rule, however, a resumed activity will have window
2658 * focus... unless it has displayed other dialogs or popups that take
2659 * input focus, in which case the activity itself will not have focus
2660 * when the other windows have it. Likewise, the system may display
2661 * system-level windows (such as the status bar notification panel or
2662 * a system alert) which will temporarily take window input focus without
2663 * pausing the foreground activity.
2665 * @param hasFocus Whether the window of this activity has focus.
2667 * @see #hasWindowFocus()
2669 * @see View#onWindowFocusChanged(boolean)
2671 public void onWindowFocusChanged(boolean hasFocus) {
2675 * Called when the main window associated with the activity has been
2676 * attached to the window manager.
2677 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2678 * for more information.
2679 * @see View#onAttachedToWindow
2681 public void onAttachedToWindow() {
2685 * Called when the main window associated with the activity has been
2686 * detached from the window manager.
2687 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2688 * for more information.
2689 * @see View#onDetachedFromWindow
2691 public void onDetachedFromWindow() {
2695 * Returns true if this activity's <em>main</em> window currently has window focus.
2696 * Note that this is not the same as the view itself having focus.
2698 * @return True if this activity's main window currently has window focus.
2700 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2702 public boolean hasWindowFocus() {
2703 Window w = getWindow();
2705 View d = w.getDecorView();
2707 return d.hasWindowFocus();
2714 * Called when the main window associated with the activity has been dismissed.
2718 public void onWindowDismissed() {
2723 * Called to process key events. You can override this to intercept all
2724 * key events before they are dispatched to the window. Be sure to call
2725 * this implementation for key events that should be handled normally.
2727 * @param event The key event.
2729 * @return boolean Return true if this event was consumed.
2731 public boolean dispatchKeyEvent(KeyEvent event) {
2732 onUserInteraction();
2734 // Let action bars open menus in response to the menu key prioritized over
2735 // the window handling it
2736 if (event.getKeyCode() == KeyEvent.KEYCODE_MENU &&
2737 mActionBar != null && mActionBar.onMenuKeyEvent(event)) {
2741 Window win = getWindow();
2742 if (win.superDispatchKeyEvent(event)) {
2745 View decor = mDecor;
2746 if (decor == null) decor = win.getDecorView();
2747 return event.dispatch(this, decor != null
2748 ? decor.getKeyDispatcherState() : null, this);
2752 * Called to process a key shortcut event.
2753 * You can override this to intercept all key shortcut events before they are
2754 * dispatched to the window. Be sure to call this implementation for key shortcut
2755 * events that should be handled normally.
2757 * @param event The key shortcut event.
2758 * @return True if this event was consumed.
2760 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
2761 onUserInteraction();
2762 if (getWindow().superDispatchKeyShortcutEvent(event)) {
2765 return onKeyShortcut(event.getKeyCode(), event);
2769 * Called to process touch screen events. You can override this to
2770 * intercept all touch screen events before they are dispatched to the
2771 * window. Be sure to call this implementation for touch screen events
2772 * that should be handled normally.
2774 * @param ev The touch screen event.
2776 * @return boolean Return true if this event was consumed.
2778 public boolean dispatchTouchEvent(MotionEvent ev) {
2779 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2780 onUserInteraction();
2782 if (getWindow().superDispatchTouchEvent(ev)) {
2785 return onTouchEvent(ev);
2789 * Called to process trackball events. You can override this to
2790 * intercept all trackball events before they are dispatched to the
2791 * window. Be sure to call this implementation for trackball events
2792 * that should be handled normally.
2794 * @param ev The trackball event.
2796 * @return boolean Return true if this event was consumed.
2798 public boolean dispatchTrackballEvent(MotionEvent ev) {
2799 onUserInteraction();
2800 if (getWindow().superDispatchTrackballEvent(ev)) {
2803 return onTrackballEvent(ev);
2807 * Called to process generic motion events. You can override this to
2808 * intercept all generic motion events before they are dispatched to the
2809 * window. Be sure to call this implementation for generic motion events
2810 * that should be handled normally.
2812 * @param ev The generic motion event.
2814 * @return boolean Return true if this event was consumed.
2816 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
2817 onUserInteraction();
2818 if (getWindow().superDispatchGenericMotionEvent(ev)) {
2821 return onGenericMotionEvent(ev);
2824 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2825 event.setClassName(getClass().getName());
2826 event.setPackageName(getPackageName());
2828 LayoutParams params = getWindow().getAttributes();
2829 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2830 (params.height == LayoutParams.MATCH_PARENT);
2831 event.setFullScreen(isFullScreen);
2833 CharSequence title = getTitle();
2834 if (!TextUtils.isEmpty(title)) {
2835 event.getText().add(title);
2842 * Default implementation of
2843 * {@link android.view.Window.Callback#onCreatePanelView}
2844 * for activities. This
2845 * simply returns null so that all panel sub-windows will have the default
2849 public View onCreatePanelView(int featureId) {
2854 * Default implementation of
2855 * {@link android.view.Window.Callback#onCreatePanelMenu}
2856 * for activities. This calls through to the new
2857 * {@link #onCreateOptionsMenu} method for the
2858 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2859 * so that subclasses of Activity don't need to deal with feature codes.
2861 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2862 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
2863 boolean show = onCreateOptionsMenu(menu);
2864 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2871 * Default implementation of
2872 * {@link android.view.Window.Callback#onPreparePanel}
2873 * for activities. This
2874 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2875 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2876 * panel, so that subclasses of
2877 * Activity don't need to deal with feature codes.
2879 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2880 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2881 boolean goforit = onPrepareOptionsMenu(menu);
2882 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
2891 * @return The default implementation returns true.
2893 public boolean onMenuOpened(int featureId, Menu menu) {
2894 if (featureId == Window.FEATURE_ACTION_BAR) {
2895 initWindowDecorActionBar();
2896 if (mActionBar != null) {
2897 mActionBar.dispatchMenuVisibilityChanged(true);
2899 Log.e(TAG, "Tried to open action bar menu with no action bar");
2906 * Default implementation of
2907 * {@link android.view.Window.Callback#onMenuItemSelected}
2908 * for activities. This calls through to the new
2909 * {@link #onOptionsItemSelected} method for the
2910 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2911 * panel, so that subclasses of
2912 * Activity don't need to deal with feature codes.
2914 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2915 CharSequence titleCondensed = item.getTitleCondensed();
2917 switch (featureId) {
2918 case Window.FEATURE_OPTIONS_PANEL:
2919 // Put event logging here so it gets called even if subclass
2920 // doesn't call through to superclass's implmeentation of each
2921 // of these methods below
2922 if(titleCondensed != null) {
2923 EventLog.writeEvent(50000, 0, titleCondensed.toString());
2925 if (onOptionsItemSelected(item)) {
2928 if (mFragments.dispatchOptionsItemSelected(item)) {
2931 if (item.getItemId() == android.R.id.home && mActionBar != null &&
2932 (mActionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
2933 if (mParent == null) {
2934 return onNavigateUp();
2936 return mParent.onNavigateUpFromChild(this);
2941 case Window.FEATURE_CONTEXT_MENU:
2942 if(titleCondensed != null) {
2943 EventLog.writeEvent(50000, 1, titleCondensed.toString());
2945 if (onContextItemSelected(item)) {
2948 return mFragments.dispatchContextItemSelected(item);
2956 * Default implementation of
2957 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2958 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2959 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2960 * so that subclasses of Activity don't need to deal with feature codes.
2961 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2962 * {@link #onContextMenuClosed(Menu)} will be called.
2964 public void onPanelClosed(int featureId, Menu menu) {
2965 switch (featureId) {
2966 case Window.FEATURE_OPTIONS_PANEL:
2967 mFragments.dispatchOptionsMenuClosed(menu);
2968 onOptionsMenuClosed(menu);
2971 case Window.FEATURE_CONTEXT_MENU:
2972 onContextMenuClosed(menu);
2975 case Window.FEATURE_ACTION_BAR:
2976 initWindowDecorActionBar();
2977 mActionBar.dispatchMenuVisibilityChanged(false);
2983 * Declare that the options menu has changed, so should be recreated.
2984 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2985 * time it needs to be displayed.
2987 public void invalidateOptionsMenu() {
2988 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
2989 (mActionBar == null || !mActionBar.invalidateOptionsMenu())) {
2990 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2995 * Initialize the contents of the Activity's standard options menu. You
2996 * should place your menu items in to <var>menu</var>.
2998 * <p>This is only called once, the first time the options menu is
2999 * displayed. To update the menu every time it is displayed, see
3000 * {@link #onPrepareOptionsMenu}.
3002 * <p>The default implementation populates the menu with standard system
3003 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
3004 * they will be correctly ordered with application-defined menu items.
3005 * Deriving classes should always call through to the base implementation.
3007 * <p>You can safely hold on to <var>menu</var> (and any items created
3008 * from it), making modifications to it as desired, until the next
3009 * time onCreateOptionsMenu() is called.
3011 * <p>When you add items to the menu, you can implement the Activity's
3012 * {@link #onOptionsItemSelected} method to handle them there.
3014 * @param menu The options menu in which you place your items.
3016 * @return You must return true for the menu to be displayed;
3017 * if you return false it will not be shown.
3019 * @see #onPrepareOptionsMenu
3020 * @see #onOptionsItemSelected
3022 public boolean onCreateOptionsMenu(Menu menu) {
3023 if (mParent != null) {
3024 return mParent.onCreateOptionsMenu(menu);
3030 * Prepare the Screen's standard options menu to be displayed. This is
3031 * called right before the menu is shown, every time it is shown. You can
3032 * use this method to efficiently enable/disable items or otherwise
3033 * dynamically modify the contents.
3035 * <p>The default implementation updates the system menu items based on the
3036 * activity's state. Deriving classes should always call through to the
3037 * base class implementation.
3039 * @param menu The options menu as last shown or first initialized by
3040 * onCreateOptionsMenu().
3042 * @return You must return true for the menu to be displayed;
3043 * if you return false it will not be shown.
3045 * @see #onCreateOptionsMenu
3047 public boolean onPrepareOptionsMenu(Menu menu) {
3048 if (mParent != null) {
3049 return mParent.onPrepareOptionsMenu(menu);
3055 * This hook is called whenever an item in your options menu is selected.
3056 * The default implementation simply returns false to have the normal
3057 * processing happen (calling the item's Runnable or sending a message to
3058 * its Handler as appropriate). You can use this method for any items
3059 * for which you would like to do processing without those other
3062 * <p>Derived classes should call through to the base class for it to
3063 * perform the default menu handling.</p>
3065 * @param item The menu item that was selected.
3067 * @return boolean Return false to allow normal menu processing to
3068 * proceed, true to consume it here.
3070 * @see #onCreateOptionsMenu
3072 public boolean onOptionsItemSelected(MenuItem item) {
3073 if (mParent != null) {
3074 return mParent.onOptionsItemSelected(item);
3080 * This method is called whenever the user chooses to navigate Up within your application's
3081 * activity hierarchy from the action bar.
3083 * <p>If the attribute {@link android.R.attr#parentActivityName parentActivityName}
3084 * was specified in the manifest for this activity or an activity-alias to it,
3085 * default Up navigation will be handled automatically. If any activity
3086 * along the parent chain requires extra Intent arguments, the Activity subclass
3087 * should override the method {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}
3088 * to supply those arguments.</p>
3090 * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
3091 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
3092 * from the design guide for more information about navigating within your app.</p>
3094 * <p>See the {@link TaskStackBuilder} class and the Activity methods
3095 * {@link #getParentActivityIntent()}, {@link #shouldUpRecreateTask(Intent)}, and
3096 * {@link #navigateUpTo(Intent)} for help implementing custom Up navigation.
3097 * The AppNavigation sample application in the Android SDK is also available for reference.</p>
3099 * @return true if Up navigation completed successfully and this Activity was finished,
3102 public boolean onNavigateUp() {
3103 // Automatically handle hierarchical Up navigation if the proper
3104 // metadata is available.
3105 Intent upIntent = getParentActivityIntent();
3106 if (upIntent != null) {
3107 if (mActivityInfo.taskAffinity == null) {
3108 // Activities with a null affinity are special; they really shouldn't
3109 // specify a parent activity intent in the first place. Just finish
3110 // the current activity and call it a day.
3112 } else if (shouldUpRecreateTask(upIntent)) {
3113 TaskStackBuilder b = TaskStackBuilder.create(this);
3114 onCreateNavigateUpTaskStack(b);
3115 onPrepareNavigateUpTaskStack(b);
3116 b.startActivities();
3118 // We can't finishAffinity if we have a result.
3119 // Fall back and simply finish the current activity instead.
3120 if (mResultCode != RESULT_CANCELED || mResultData != null) {
3121 // Tell the developer what's going on to avoid hair-pulling.
3122 Log.i(TAG, "onNavigateUp only finishing topmost activity to return a result");
3128 navigateUpTo(upIntent);
3136 * This is called when a child activity of this one attempts to navigate up.
3137 * The default implementation simply calls onNavigateUp() on this activity (the parent).
3139 * @param child The activity making the call.
3141 public boolean onNavigateUpFromChild(Activity child) {
3142 return onNavigateUp();
3146 * Define the synthetic task stack that will be generated during Up navigation from
3149 * <p>The default implementation of this method adds the parent chain of this activity
3150 * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications
3151 * may choose to override this method to construct the desired task stack in a different
3154 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
3155 * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent
3156 * returned by {@link #getParentActivityIntent()}.</p>
3158 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
3159 * by the manifest should override {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}.</p>
3161 * @param builder An empty TaskStackBuilder - the application should add intents representing
3162 * the desired task stack
3164 public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) {
3165 builder.addParentStack(this);
3169 * Prepare the synthetic task stack that will be generated during Up navigation
3170 * from a different task.
3172 * <p>This method receives the {@link TaskStackBuilder} with the constructed series of
3173 * Intents as generated by {@link #onCreateNavigateUpTaskStack(TaskStackBuilder)}.
3174 * If any extra data should be added to these intents before launching the new task,
3175 * the application should override this method and add that data here.</p>
3177 * @param builder A TaskStackBuilder that has been populated with Intents by
3178 * onCreateNavigateUpTaskStack.
3180 public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) {
3184 * This hook is called whenever the options menu is being closed (either by the user canceling
3185 * the menu with the back/menu button, or when an item is selected).
3187 * @param menu The options menu as last shown or first initialized by
3188 * onCreateOptionsMenu().
3190 public void onOptionsMenuClosed(Menu menu) {
3191 if (mParent != null) {
3192 mParent.onOptionsMenuClosed(menu);
3197 * Programmatically opens the options menu. If the options menu is already
3198 * open, this method does nothing.
3200 public void openOptionsMenu() {
3201 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3202 (mActionBar == null || !mActionBar.openOptionsMenu())) {
3203 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
3208 * Progammatically closes the options menu. If the options menu is already
3209 * closed, this method does nothing.
3211 public void closeOptionsMenu() {
3212 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
3213 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
3218 * Called when a context menu for the {@code view} is about to be shown.
3219 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
3220 * time the context menu is about to be shown and should be populated for
3221 * the view (or item inside the view for {@link AdapterView} subclasses,
3222 * this can be found in the {@code menuInfo})).
3224 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
3225 * item has been selected.
3227 * It is not safe to hold onto the context menu after this method returns.
3230 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
3234 * Registers a context menu to be shown for the given view (multiple views
3235 * can show the context menu). This method will set the
3236 * {@link OnCreateContextMenuListener} on the view to this activity, so
3237 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
3238 * called when it is time to show the context menu.
3240 * @see #unregisterForContextMenu(View)
3241 * @param view The view that should show a context menu.
3243 public void registerForContextMenu(View view) {
3244 view.setOnCreateContextMenuListener(this);
3248 * Prevents a context menu to be shown for the given view. This method will remove the
3249 * {@link OnCreateContextMenuListener} on the view.
3251 * @see #registerForContextMenu(View)
3252 * @param view The view that should stop showing a context menu.
3254 public void unregisterForContextMenu(View view) {
3255 view.setOnCreateContextMenuListener(null);
3259 * Programmatically opens the context menu for a particular {@code view}.
3260 * The {@code view} should have been added via
3261 * {@link #registerForContextMenu(View)}.
3263 * @param view The view to show the context menu for.
3265 public void openContextMenu(View view) {
3266 view.showContextMenu();
3270 * Programmatically closes the most recently opened context menu, if showing.
3272 public void closeContextMenu() {
3273 if (mWindow.hasFeature(Window.FEATURE_CONTEXT_MENU)) {
3274 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
3279 * This hook is called whenever an item in a context menu is selected. The
3280 * default implementation simply returns false to have the normal processing
3281 * happen (calling the item's Runnable or sending a message to its Handler
3282 * as appropriate). You can use this method for any items for which you
3283 * would like to do processing without those other facilities.
3285 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
3286 * View that added this menu item.
3288 * Derived classes should call through to the base class for it to perform
3289 * the default menu handling.
3291 * @param item The context menu item that was selected.
3292 * @return boolean Return false to allow normal context menu processing to
3293 * proceed, true to consume it here.
3295 public boolean onContextItemSelected(MenuItem item) {
3296 if (mParent != null) {
3297 return mParent.onContextItemSelected(item);
3303 * This hook is called whenever the context menu is being closed (either by
3304 * the user canceling the menu with the back/menu button, or when an item is
3307 * @param menu The context menu that is being closed.
3309 public void onContextMenuClosed(Menu menu) {
3310 if (mParent != null) {
3311 mParent.onContextMenuClosed(menu);
3316 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
3319 protected Dialog onCreateDialog(int id) {
3324 * Callback for creating dialogs that are managed (saved and restored) for you
3325 * by the activity. The default implementation calls through to
3326 * {@link #onCreateDialog(int)} for compatibility.
3328 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3329 * or later, consider instead using a {@link DialogFragment} instead.</em>
3331 * <p>If you use {@link #showDialog(int)}, the activity will call through to
3332 * this method the first time, and hang onto it thereafter. Any dialog
3333 * that is created by this method will automatically be saved and restored
3334 * for you, including whether it is showing.
3336 * <p>If you would like the activity to manage saving and restoring dialogs
3337 * for you, you should override this method and handle any ids that are
3338 * passed to {@link #showDialog}.
3340 * <p>If you would like an opportunity to prepare your dialog before it is shown,
3341 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
3343 * @param id The id of the dialog.
3344 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3345 * @return The dialog. If you return null, the dialog will not be created.
3347 * @see #onPrepareDialog(int, Dialog, Bundle)
3348 * @see #showDialog(int, Bundle)
3349 * @see #dismissDialog(int)
3350 * @see #removeDialog(int)
3352 * @deprecated Use the new {@link DialogFragment} class with
3353 * {@link FragmentManager} instead; this is also
3354 * available on older platforms through the Android compatibility package.
3358 protected Dialog onCreateDialog(int id, Bundle args) {
3359 return onCreateDialog(id);
3363 * @deprecated Old no-arguments version of
3364 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
3367 protected void onPrepareDialog(int id, Dialog dialog) {
3368 dialog.setOwnerActivity(this);
3372 * Provides an opportunity to prepare a managed dialog before it is being
3373 * shown. The default implementation calls through to
3374 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
3377 * Override this if you need to update a managed dialog based on the state
3378 * of the application each time it is shown. For example, a time picker
3379 * dialog might want to be updated with the current time. You should call
3380 * through to the superclass's implementation. The default implementation
3381 * will set this Activity as the owner activity on the Dialog.
3383 * @param id The id of the managed dialog.
3384 * @param dialog The dialog.
3385 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3386 * @see #onCreateDialog(int, Bundle)
3387 * @see #showDialog(int)
3388 * @see #dismissDialog(int)
3389 * @see #removeDialog(int)
3391 * @deprecated Use the new {@link DialogFragment} class with
3392 * {@link FragmentManager} instead; this is also
3393 * available on older platforms through the Android compatibility package.
3396 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
3397 onPrepareDialog(id, dialog);
3401 * Simple version of {@link #showDialog(int, Bundle)} that does not
3402 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
3403 * with null arguments.
3405 * @deprecated Use the new {@link DialogFragment} class with
3406 * {@link FragmentManager} instead; this is also
3407 * available on older platforms through the Android compatibility package.
3410 public final void showDialog(int id) {
3411 showDialog(id, null);
3415 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
3416 * will be made with the same id the first time this is called for a given
3417 * id. From thereafter, the dialog will be automatically saved and restored.
3419 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3420 * or later, consider instead using a {@link DialogFragment} instead.</em>
3422 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
3423 * be made to provide an opportunity to do any timely preparation.
3425 * @param id The id of the managed dialog.
3426 * @param args Arguments to pass through to the dialog. These will be saved
3427 * and restored for you. Note that if the dialog is already created,
3428 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
3429 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
3430 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
3431 * @return Returns true if the Dialog was created; false is returned if
3432 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
3435 * @see #onCreateDialog(int, Bundle)
3436 * @see #onPrepareDialog(int, Dialog, Bundle)
3437 * @see #dismissDialog(int)
3438 * @see #removeDialog(int)
3440 * @deprecated Use the new {@link DialogFragment} class with
3441 * {@link FragmentManager} instead; this is also
3442 * available on older platforms through the Android compatibility package.
3446 public final boolean showDialog(int id, Bundle args) {
3447 if (mManagedDialogs == null) {
3448 mManagedDialogs = new SparseArray<ManagedDialog>();
3450 ManagedDialog md = mManagedDialogs.get(id);
3452 md = new ManagedDialog();
3453 md.mDialog = createDialog(id, null, args);
3454 if (md.mDialog == null) {
3457 mManagedDialogs.put(id, md);
3461 onPrepareDialog(id, md.mDialog, args);
3467 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
3469 * @param id The id of the managed dialog.
3471 * @throws IllegalArgumentException if the id was not previously shown via
3472 * {@link #showDialog(int)}.
3474 * @see #onCreateDialog(int, Bundle)
3475 * @see #onPrepareDialog(int, Dialog, Bundle)
3476 * @see #showDialog(int)
3477 * @see #removeDialog(int)
3479 * @deprecated Use the new {@link DialogFragment} class with
3480 * {@link FragmentManager} instead; this is also
3481 * available on older platforms through the Android compatibility package.
3484 public final void dismissDialog(int id) {
3485 if (mManagedDialogs == null) {
3486 throw missingDialog(id);
3489 final ManagedDialog md = mManagedDialogs.get(id);
3491 throw missingDialog(id);
3493 md.mDialog.dismiss();
3497 * Creates an exception to throw if a user passed in a dialog id that is
3500 private IllegalArgumentException missingDialog(int id) {
3501 return new IllegalArgumentException("no dialog with id " + id + " was ever "
3502 + "shown via Activity#showDialog");
3506 * Removes any internal references to a dialog managed by this Activity.
3507 * If the dialog is showing, it will dismiss it as part of the clean up.
3509 * <p>This can be useful if you know that you will never show a dialog again and
3510 * want to avoid the overhead of saving and restoring it in the future.
3512 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
3513 * will not throw an exception if you try to remove an ID that does not
3514 * currently have an associated dialog.</p>
3516 * @param id The id of the managed dialog.
3518 * @see #onCreateDialog(int, Bundle)
3519 * @see #onPrepareDialog(int, Dialog, Bundle)
3520 * @see #showDialog(int)
3521 * @see #dismissDialog(int)
3523 * @deprecated Use the new {@link DialogFragment} class with
3524 * {@link FragmentManager} instead; this is also
3525 * available on older platforms through the Android compatibility package.
3528 public final void removeDialog(int id) {
3529 if (mManagedDialogs != null) {
3530 final ManagedDialog md = mManagedDialogs.get(id);
3532 md.mDialog.dismiss();
3533 mManagedDialogs.remove(id);
3539 * This hook is called when the user signals the desire to start a search.
3541 * <p>You can use this function as a simple way to launch the search UI, in response to a
3542 * menu item, search button, or other widgets within your activity. Unless overidden,
3543 * calling this function is the same as calling
3544 * {@link #startSearch startSearch(null, false, null, false)}, which launches
3545 * search for the current activity as specified in its manifest, see {@link SearchManager}.
3547 * <p>You can override this function to force global search, e.g. in response to a dedicated
3548 * search key, or to block search entirely (by simply returning false).
3550 * <p>Note: when running in a {@link Configuration#UI_MODE_TYPE_TELEVISION}, the default
3551 * implementation changes to simply return false and you must supply your own custom
3552 * implementation if you want to support search.</p>
3554 * @param searchEvent The {@link SearchEvent} that signaled this search.
3555 * @return Returns {@code true} if search launched, and {@code false} if the activity does
3556 * not respond to search. The default implementation always returns {@code true}, except
3557 * when in {@link Configuration#UI_MODE_TYPE_TELEVISION} mode where it returns false.
3559 * @see android.app.SearchManager
3561 public boolean onSearchRequested(@Nullable SearchEvent searchEvent) {
3562 mSearchEvent = searchEvent;
3563 boolean result = onSearchRequested();
3564 mSearchEvent = null;
3569 * @see #onSearchRequested(SearchEvent)
3571 public boolean onSearchRequested() {
3572 if ((getResources().getConfiguration().uiMode&Configuration.UI_MODE_TYPE_MASK)
3573 != Configuration.UI_MODE_TYPE_TELEVISION) {
3574 startSearch(null, false, null, false);
3582 * During the onSearchRequested() callbacks, this function will return the
3583 * {@link SearchEvent} that triggered the callback, if it exists.
3585 * @return SearchEvent The SearchEvent that triggered the {@link
3586 * #onSearchRequested} callback.
3588 public final SearchEvent getSearchEvent() {
3589 return mSearchEvent;
3593 * This hook is called to launch the search UI.
3595 * <p>It is typically called from onSearchRequested(), either directly from
3596 * Activity.onSearchRequested() or from an overridden version in any given
3597 * Activity. If your goal is simply to activate search, it is preferred to call
3598 * onSearchRequested(), which may have been overridden elsewhere in your Activity. If your goal
3599 * is to inject specific data such as context data, it is preferred to <i>override</i>
3600 * onSearchRequested(), so that any callers to it will benefit from the override.
3602 * @param initialQuery Any non-null non-empty string will be inserted as
3603 * pre-entered text in the search query box.
3604 * @param selectInitialQuery If true, the initial query will be preselected, which means that
3605 * any further typing will replace it. This is useful for cases where an entire pre-formed
3606 * query is being inserted. If false, the selection point will be placed at the end of the
3607 * inserted query. This is useful when the inserted query is text that the user entered,
3608 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
3609 * if initialQuery is a non-empty string.</i>
3610 * @param appSearchData An application can insert application-specific
3611 * context here, in order to improve quality or specificity of its own
3612 * searches. This data will be returned with SEARCH intent(s). Null if
3613 * no extra data is required.
3614 * @param globalSearch If false, this will only launch the search that has been specifically
3615 * defined by the application (which is usually defined as a local search). If no default
3616 * search is defined in the current application or activity, global search will be launched.
3617 * If true, this will always launch a platform-global (e.g. web-based) search instead.
3619 * @see android.app.SearchManager
3620 * @see #onSearchRequested
3622 public void startSearch(@Nullable String initialQuery, boolean selectInitialQuery,
3623 @Nullable Bundle appSearchData, boolean globalSearch) {
3624 ensureSearchManager();
3625 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
3626 appSearchData, globalSearch);
3630 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
3631 * the search dialog. Made available for testing purposes.
3633 * @param query The query to trigger. If empty, the request will be ignored.
3634 * @param appSearchData An application can insert application-specific
3635 * context here, in order to improve quality or specificity of its own
3636 * searches. This data will be returned with SEARCH intent(s). Null if
3637 * no extra data is required.
3639 public void triggerSearch(String query, @Nullable Bundle appSearchData) {
3640 ensureSearchManager();
3641 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
3645 * Request that key events come to this activity. Use this if your
3646 * activity has no views with focus, but the activity still wants
3647 * a chance to process key events.
3649 * @see android.view.Window#takeKeyEvents
3651 public void takeKeyEvents(boolean get) {
3652 getWindow().takeKeyEvents(get);
3656 * Enable extended window features. This is a convenience for calling
3657 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
3659 * @param featureId The desired feature as defined in
3660 * {@link android.view.Window}.
3661 * @return Returns true if the requested feature is supported and now
3664 * @see android.view.Window#requestFeature
3666 public final boolean requestWindowFeature(int featureId) {
3667 return getWindow().requestFeature(featureId);
3671 * Convenience for calling
3672 * {@link android.view.Window#setFeatureDrawableResource}.
3674 public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) {
3675 getWindow().setFeatureDrawableResource(featureId, resId);
3679 * Convenience for calling
3680 * {@link android.view.Window#setFeatureDrawableUri}.
3682 public final void setFeatureDrawableUri(int featureId, Uri uri) {
3683 getWindow().setFeatureDrawableUri(featureId, uri);
3687 * Convenience for calling
3688 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
3690 public final void setFeatureDrawable(int featureId, Drawable drawable) {
3691 getWindow().setFeatureDrawable(featureId, drawable);
3695 * Convenience for calling
3696 * {@link android.view.Window#setFeatureDrawableAlpha}.
3698 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
3699 getWindow().setFeatureDrawableAlpha(featureId, alpha);
3703 * Convenience for calling
3704 * {@link android.view.Window#getLayoutInflater}.
3707 public LayoutInflater getLayoutInflater() {
3708 return getWindow().getLayoutInflater();
3712 * Returns a {@link MenuInflater} with this context.
3715 public MenuInflater getMenuInflater() {
3716 // Make sure that action views can get an appropriate theme.
3717 if (mMenuInflater == null) {
3718 initWindowDecorActionBar();
3719 if (mActionBar != null) {
3720 mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this);
3722 mMenuInflater = new MenuInflater(this);
3725 return mMenuInflater;
3729 protected void onApplyThemeResource(Resources.Theme theme, @StyleRes int resid,
3731 if (mParent == null) {
3732 super.onApplyThemeResource(theme, resid, first);
3735 theme.setTo(mParent.getTheme());
3736 } catch (Exception e) {
3739 theme.applyStyle(resid, false);
3742 // Get the primary color and update the TaskDescription for this activity
3743 if (theme != null) {
3744 TypedArray a = theme.obtainStyledAttributes(com.android.internal.R.styleable.Theme);
3745 int colorPrimary = a.getColor(com.android.internal.R.styleable.Theme_colorPrimary, 0);
3747 if (colorPrimary != 0) {
3748 ActivityManager.TaskDescription v = new ActivityManager.TaskDescription(null, null,
3750 setTaskDescription(v);
3756 * Requests permissions to be granted to this application. These permissions
3757 * must be requested in your manifest, they should not be granted to your app,
3758 * and they should have protection level {@link android.content.pm.PermissionInfo
3759 * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by
3760 * the platform or a third-party app.
3762 * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
3763 * are granted at install time if requested in the manifest. Signature permissions
3764 * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
3765 * install time if requested in the manifest and the signature of your app matches
3766 * the signature of the app declaring the permissions.
3769 * If your app does not have the requested permissions the user will be presented
3770 * with UI for accepting them. After the user has accepted or rejected the
3771 * requested permissions you will receive a callback on {@link
3772 * #onRequestPermissionsResult(int, String[], int[])} reporting whether the
3773 * permissions were granted or not.
3776 * Note that requesting a permission does not guarantee it will be granted and
3777 * your app should be able to run without having this permission.
3780 * This method may start an activity allowing the user to choose which permissions
3781 * to grant and which to reject. Hence, you should be prepared that your activity
3782 * may be paused and resumed. Further, granting some permissions may require
3783 * a restart of you application. In such a case, the system will recreate the
3784 * activity stack before delivering the result to {@link
3785 * #onRequestPermissionsResult(int, String[], int[])}.
3788 * When checking whether you have a permission you should use {@link
3789 * #checkSelfPermission(String)}.
3792 * You cannot request a permission if your activity sets {@link
3793 * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
3794 * <code>true</code> because in this case the activity would not receive
3795 * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}.
3798 * A sample permissions request looks like this:
3801 * private void showContacts() {
3802 * if (checkSelfPermission(Manifest.permission.READ_CONTACTS)
3803 * != PackageManager.PERMISSION_GRANTED) {
3804 * requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
3805 * PERMISSIONS_REQUEST_READ_CONTACTS);
3811 * {@literal @}Override
3812 * public void onRequestPermissionsResult(int requestCode, String[] permissions,
3813 * int[] grantResults) {
3814 * if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS
3815 * && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
3821 * @param permissions The requested permissions.
3822 * @param requestCode Application specific request code to match with a result
3823 * reported to {@link #onRequestPermissionsResult(int, String[], int[])}.
3826 * @see #onRequestPermissionsResult(int, String[], int[])
3827 * @see #checkSelfPermission(String)
3828 * @see #shouldShowRequestPermissionRationale(String)
3830 public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
3831 if (mHasCurrentPermissionsRequest) {
3832 Log.w(TAG, "Can reqeust only one set of permissions at a time");
3833 // Dispatch the callback with empty arrays which means a cancellation.
3834 onRequestPermissionsResult(requestCode, new String[0], new int[0]);
3837 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
3838 startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
3839 mHasCurrentPermissionsRequest = true;
3843 * Callback for the result from requesting permissions. This method
3844 * is invoked for every call on {@link #requestPermissions(String[], int)}.
3846 * <strong>Note:</strong> It is possible that the permissions request interaction
3847 * with the user is interrupted. In this case you will receive empty permissions
3848 * and results arrays which should be treated as a cancellation.
3851 * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
3852 * @param permissions The requested permissions. Never null.
3853 * @param grantResults The grant results for the corresponding permissions
3854 * which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
3855 * or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
3857 * @see #requestPermissions(String[], int)
3859 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
3860 @NonNull int[] grantResults) {
3861 /* callback - no nothing */
3865 * Gets whether you should show UI with rationale for requesting a permission.
3866 * You should do this only if you do not have the permission and the context in
3867 * which the permission is requested does not clearly communicate to the user
3868 * what would be the benefit from granting this permission.
3870 * For example, if you write a camera app, requesting the camera permission
3871 * would be expected by the user and no rationale for why it is requested is
3872 * needed. If however, the app needs location for tagging photos then a non-tech
3873 * savvy user may wonder how location is related to taking photos. In this case
3874 * you may choose to show UI with rationale of requesting this permission.
3877 * @param permission A permission your app wants to request.
3878 * @return Whether you can show permission rationale UI.
3880 * @see #checkSelfPermission(String)
3881 * @see #requestPermissions(String[], int)
3882 * @see #onRequestPermissionsResult(int, String[], int[])
3884 public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
3885 return getPackageManager().shouldShowRequestPermissionRationale(permission);
3889 * Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
3892 * @param intent The intent to start.
3893 * @param requestCode If >= 0, this code will be returned in
3894 * onActivityResult() when the activity exits.
3896 * @throws android.content.ActivityNotFoundException
3898 * @see #startActivity
3900 public void startActivityForResult(Intent intent, int requestCode) {
3901 startActivityForResult(intent, requestCode, null);
3905 * Launch an activity for which you would like a result when it finished.
3906 * When this activity exits, your
3907 * onActivityResult() method will be called with the given requestCode.
3908 * Using a negative requestCode is the same as calling
3909 * {@link #startActivity} (the activity is not launched as a sub-activity).
3911 * <p>Note that this method should only be used with Intent protocols
3912 * that are defined to return a result. In other protocols (such as
3913 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3914 * not get the result when you expect. For example, if the activity you
3915 * are launching uses the singleTask launch mode, it will not run in your
3916 * task and thus you will immediately receive a cancel result.
3918 * <p>As a special case, if you call startActivityForResult() with a requestCode
3919 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3920 * activity, then your window will not be displayed until a result is
3921 * returned back from the started activity. This is to avoid visible
3922 * flickering when redirecting to another activity.
3924 * <p>This method throws {@link android.content.ActivityNotFoundException}
3925 * if there was no Activity found to run the given Intent.
3927 * @param intent The intent to start.
3928 * @param requestCode If >= 0, this code will be returned in
3929 * onActivityResult() when the activity exits.
3930 * @param options Additional options for how the Activity should be started.
3931 * See {@link android.content.Context#startActivity(Intent, Bundle)
3932 * Context.startActivity(Intent, Bundle)} for more details.
3934 * @throws android.content.ActivityNotFoundException
3936 * @see #startActivity
3938 public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
3939 if (mParent == null) {
3940 Instrumentation.ActivityResult ar =
3941 mInstrumentation.execStartActivity(
3942 this, mMainThread.getApplicationThread(), mToken, this,
3943 intent, requestCode, options);
3945 mMainThread.sendActivityResult(
3946 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3947 ar.getResultData());
3949 if (requestCode >= 0) {
3950 // If this start is requesting a result, we can avoid making
3951 // the activity visible until the result is received. Setting
3952 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3953 // activity hidden during this time, to avoid flickering.
3954 // This can only be done when a result is requested because
3955 // that guarantees we will get information back when the
3956 // activity is finished, no matter what happens to it.
3957 mStartedActivity = true;
3960 cancelInputsAndStartExitTransition(options);
3961 // TODO Consider clearing/flushing other event sources and events for child windows.
3963 if (options != null) {
3964 mParent.startActivityFromChild(this, intent, requestCode, options);
3966 // Note we want to go through this method for compatibility with
3967 // existing applications that may have overridden it.
3968 mParent.startActivityFromChild(this, intent, requestCode);
3974 * Cancels pending inputs and if an Activity Transition is to be run, starts the transition.
3976 * @param options The ActivityOptions bundle used to start an Activity.
3978 private void cancelInputsAndStartExitTransition(Bundle options) {
3979 final View decor = mWindow != null ? mWindow.peekDecorView() : null;
3980 if (decor != null) {
3981 decor.cancelPendingInputEvents();
3983 if (options != null && !isTopOfTask()) {
3984 mActivityTransitionState.startExitOutTransition(this, options);
3989 * @hide Implement to provide correct calling token.
3991 public void startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user) {
3992 startActivityForResultAsUser(intent, requestCode, null, user);
3996 * @hide Implement to provide correct calling token.
3998 public void startActivityForResultAsUser(Intent intent, int requestCode,
3999 @Nullable Bundle options, UserHandle user) {
4000 if (mParent != null) {
4001 throw new RuntimeException("Can't be called from a child");
4003 Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
4004 this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode,
4007 mMainThread.sendActivityResult(
4008 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
4010 if (requestCode >= 0) {
4011 // If this start is requesting a result, we can avoid making
4012 // the activity visible until the result is received. Setting
4013 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4014 // activity hidden during this time, to avoid flickering.
4015 // This can only be done when a result is requested because
4016 // that guarantees we will get information back when the
4017 // activity is finished, no matter what happens to it.
4018 mStartedActivity = true;
4021 cancelInputsAndStartExitTransition(options);
4025 * @hide Implement to provide correct calling token.
4027 public void startActivityAsUser(Intent intent, UserHandle user) {
4028 startActivityAsUser(intent, null, user);
4032 * @hide Implement to provide correct calling token.
4034 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
4035 if (mParent != null) {
4036 throw new RuntimeException("Can't be called from a child");
4038 Instrumentation.ActivityResult ar =
4039 mInstrumentation.execStartActivity(
4040 this, mMainThread.getApplicationThread(), mToken, this,
4041 intent, -1, options, user);
4043 mMainThread.sendActivityResult(
4044 mToken, mEmbeddedID, -1, ar.getResultCode(),
4045 ar.getResultData());
4047 cancelInputsAndStartExitTransition(options);
4051 * Start a new activity as if it was started by the activity that started our
4052 * current activity. This is for the resolver and chooser activities, which operate
4053 * as intermediaries that dispatch their intent to the target the user selects -- to
4054 * do this, they must perform all security checks including permission grants as if
4055 * their launch had come from the original activity.
4056 * @param intent The Intent to start.
4057 * @param options ActivityOptions or null.
4058 * @param ignoreTargetSecurity If true, the activity manager will not check whether the
4059 * caller it is doing the start is, is actually allowed to start the target activity.
4060 * If you set this to true, you must set an explicit component in the Intent and do any
4061 * appropriate security checks yourself.
4062 * @param userId The user the new activity should run as.
4065 public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
4066 boolean ignoreTargetSecurity, int userId) {
4067 if (mParent != null) {
4068 throw new RuntimeException("Can't be called from a child");
4070 Instrumentation.ActivityResult ar =
4071 mInstrumentation.execStartActivityAsCaller(
4072 this, mMainThread.getApplicationThread(), mToken, this,
4073 intent, -1, options, ignoreTargetSecurity, userId);
4075 mMainThread.sendActivityResult(
4076 mToken, mEmbeddedID, -1, ar.getResultCode(),
4077 ar.getResultData());
4079 cancelInputsAndStartExitTransition(options);
4083 * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
4084 * Intent, int, int, int, Bundle)} with no options.
4086 * @param intent The IntentSender to launch.
4087 * @param requestCode If >= 0, this code will be returned in
4088 * onActivityResult() when the activity exits.
4089 * @param fillInIntent If non-null, this will be provided as the
4090 * intent parameter to {@link IntentSender#sendIntent}.
4091 * @param flagsMask Intent flags in the original IntentSender that you
4092 * would like to change.
4093 * @param flagsValues Desired values for any bits set in
4094 * <var>flagsMask</var>
4095 * @param extraFlags Always set to 0.
4097 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4098 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4099 throws IntentSender.SendIntentException {
4100 startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
4101 flagsValues, extraFlags, null);
4105 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
4106 * to use a IntentSender to describe the activity to be started. If
4107 * the IntentSender is for an activity, that activity will be started
4108 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
4109 * here; otherwise, its associated action will be executed (such as
4110 * sending a broadcast) as if you had called
4111 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
4113 * @param intent The IntentSender to launch.
4114 * @param requestCode If >= 0, this code will be returned in
4115 * onActivityResult() when the activity exits.
4116 * @param fillInIntent If non-null, this will be provided as the
4117 * intent parameter to {@link IntentSender#sendIntent}.
4118 * @param flagsMask Intent flags in the original IntentSender that you
4119 * would like to change.
4120 * @param flagsValues Desired values for any bits set in
4121 * <var>flagsMask</var>
4122 * @param extraFlags Always set to 0.
4123 * @param options Additional options for how the Activity should be started.
4124 * See {@link android.content.Context#startActivity(Intent, Bundle)
4125 * Context.startActivity(Intent, Bundle)} for more details. If options
4126 * have also been supplied by the IntentSender, options given here will
4127 * override any that conflict with those given by the IntentSender.
4129 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4130 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4131 Bundle options) throws IntentSender.SendIntentException {
4132 if (mParent == null) {
4133 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
4134 flagsMask, flagsValues, this, options);
4135 } else if (options != null) {
4136 mParent.startIntentSenderFromChild(this, intent, requestCode,
4137 fillInIntent, flagsMask, flagsValues, extraFlags, options);
4139 // Note we want to go through this call for compatibility with
4140 // existing applications that may have overridden the method.
4141 mParent.startIntentSenderFromChild(this, intent, requestCode,
4142 fillInIntent, flagsMask, flagsValues, extraFlags);
4146 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
4147 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity,
4149 throws IntentSender.SendIntentException {
4151 String resolvedType = null;
4152 if (fillInIntent != null) {
4153 fillInIntent.migrateExtraStreamToClipData();
4154 fillInIntent.prepareToLeaveProcess();
4155 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
4157 int result = ActivityManagerNative.getDefault()
4158 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
4159 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
4160 requestCode, flagsMask, flagsValues, options);
4161 if (result == ActivityManager.START_CANCELED) {
4162 throw new IntentSender.SendIntentException();
4164 Instrumentation.checkStartActivityResult(result, null);
4165 } catch (RemoteException e) {
4167 if (requestCode >= 0) {
4168 // If this start is requesting a result, we can avoid making
4169 // the activity visible until the result is received. Setting
4170 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4171 // activity hidden during this time, to avoid flickering.
4172 // This can only be done when a result is requested because
4173 // that guarantees we will get information back when the
4174 // activity is finished, no matter what happens to it.
4175 mStartedActivity = true;
4180 * Same as {@link #startActivity(Intent, Bundle)} with no options
4183 * @param intent The intent to start.
4185 * @throws android.content.ActivityNotFoundException
4187 * @see {@link #startActivity(Intent, Bundle)}
4188 * @see #startActivityForResult
4191 public void startActivity(Intent intent) {
4192 this.startActivity(intent, null);
4196 * Launch a new activity. You will not receive any information about when
4197 * the activity exits. This implementation overrides the base version,
4198 * providing information about
4199 * the activity performing the launch. Because of this additional
4200 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4201 * required; if not specified, the new activity will be added to the
4202 * task of the caller.
4204 * <p>This method throws {@link android.content.ActivityNotFoundException}
4205 * if there was no Activity found to run the given Intent.
4207 * @param intent The intent to start.
4208 * @param options Additional options for how the Activity should be started.
4209 * See {@link android.content.Context#startActivity(Intent, Bundle)
4210 * Context.startActivity(Intent, Bundle)} for more details.
4212 * @throws android.content.ActivityNotFoundException
4214 * @see {@link #startActivity(Intent)}
4215 * @see #startActivityForResult
4218 public void startActivity(Intent intent, @Nullable Bundle options) {
4219 if (options != null) {
4220 startActivityForResult(intent, -1, options);
4222 // Note we want to go through this call for compatibility with
4223 // applications that may have overridden the method.
4224 startActivityForResult(intent, -1);
4229 * Same as {@link #startActivities(Intent[], Bundle)} with no options
4232 * @param intents The intents to start.
4234 * @throws android.content.ActivityNotFoundException
4236 * @see {@link #startActivities(Intent[], Bundle)}
4237 * @see #startActivityForResult
4240 public void startActivities(Intent[] intents) {
4241 startActivities(intents, null);
4245 * Launch a new activity. You will not receive any information about when
4246 * the activity exits. This implementation overrides the base version,
4247 * providing information about
4248 * the activity performing the launch. Because of this additional
4249 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4250 * required; if not specified, the new activity will be added to the
4251 * task of the caller.
4253 * <p>This method throws {@link android.content.ActivityNotFoundException}
4254 * if there was no Activity found to run the given Intent.
4256 * @param intents The intents to start.
4257 * @param options Additional options for how the Activity should be started.
4258 * See {@link android.content.Context#startActivity(Intent, Bundle)
4259 * Context.startActivity(Intent, Bundle)} for more details.
4261 * @throws android.content.ActivityNotFoundException
4263 * @see {@link #startActivities(Intent[])}
4264 * @see #startActivityForResult
4267 public void startActivities(Intent[] intents, @Nullable Bundle options) {
4268 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
4269 mToken, this, intents, options);
4273 * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
4276 * @param intent The IntentSender to launch.
4277 * @param fillInIntent If non-null, this will be provided as the
4278 * intent parameter to {@link IntentSender#sendIntent}.
4279 * @param flagsMask Intent flags in the original IntentSender that you
4280 * would like to change.
4281 * @param flagsValues Desired values for any bits set in
4282 * <var>flagsMask</var>
4283 * @param extraFlags Always set to 0.
4285 public void startIntentSender(IntentSender intent,
4286 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4287 throws IntentSender.SendIntentException {
4288 startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
4293 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
4295 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
4296 * for more information.
4298 * @param intent The IntentSender to launch.
4299 * @param fillInIntent If non-null, this will be provided as the
4300 * intent parameter to {@link IntentSender#sendIntent}.
4301 * @param flagsMask Intent flags in the original IntentSender that you
4302 * would like to change.
4303 * @param flagsValues Desired values for any bits set in
4304 * <var>flagsMask</var>
4305 * @param extraFlags Always set to 0.
4306 * @param options Additional options for how the Activity should be started.
4307 * See {@link android.content.Context#startActivity(Intent, Bundle)
4308 * Context.startActivity(Intent, Bundle)} for more details. If options
4309 * have also been supplied by the IntentSender, options given here will
4310 * override any that conflict with those given by the IntentSender.
4312 public void startIntentSender(IntentSender intent,
4313 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4314 Bundle options) throws IntentSender.SendIntentException {
4315 if (options != null) {
4316 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4317 flagsValues, extraFlags, options);
4319 // Note we want to go through this call for compatibility with
4320 // applications that may have overridden the method.
4321 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4322 flagsValues, extraFlags);
4327 * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
4330 * @param intent The intent to start.
4331 * @param requestCode If >= 0, this code will be returned in
4332 * onActivityResult() when the activity exits, as described in
4333 * {@link #startActivityForResult}.
4335 * @return If a new activity was launched then true is returned; otherwise
4336 * false is returned and you must handle the Intent yourself.
4338 * @see #startActivity
4339 * @see #startActivityForResult
4341 public boolean startActivityIfNeeded(@NonNull Intent intent, int requestCode) {
4342 return startActivityIfNeeded(intent, requestCode, null);
4346 * A special variation to launch an activity only if a new activity
4347 * instance is needed to handle the given Intent. In other words, this is
4348 * just like {@link #startActivityForResult(Intent, int)} except: if you are
4349 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
4350 * singleTask or singleTop
4351 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
4353 * that handles <var>intent</var> is the same as your currently running
4354 * activity, then a new instance is not needed. In this case, instead of
4355 * the normal behavior of calling {@link #onNewIntent} this function will
4356 * return and you can handle the Intent yourself.
4358 * <p>This function can only be called from a top-level activity; if it is
4359 * called from a child activity, a runtime exception will be thrown.
4361 * @param intent The intent to start.
4362 * @param requestCode If >= 0, this code will be returned in
4363 * onActivityResult() when the activity exits, as described in
4364 * {@link #startActivityForResult}.
4365 * @param options Additional options for how the Activity should be started.
4366 * See {@link android.content.Context#startActivity(Intent, Bundle)
4367 * Context.startActivity(Intent, Bundle)} for more details.
4369 * @return If a new activity was launched then true is returned; otherwise
4370 * false is returned and you must handle the Intent yourself.
4372 * @see #startActivity
4373 * @see #startActivityForResult
4375 public boolean startActivityIfNeeded(@NonNull Intent intent, int requestCode,
4376 @Nullable Bundle options) {
4377 if (mParent == null) {
4378 int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
4380 Uri referrer = onProvideReferrer();
4381 if (referrer != null) {
4382 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4384 intent.migrateExtraStreamToClipData();
4385 intent.prepareToLeaveProcess();
4386 result = ActivityManagerNative.getDefault()
4387 .startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
4388 intent, intent.resolveTypeIfNeeded(getContentResolver()), mToken,
4389 mEmbeddedID, requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4391 } catch (RemoteException e) {
4395 Instrumentation.checkStartActivityResult(result, intent);
4397 if (requestCode >= 0) {
4398 // If this start is requesting a result, we can avoid making
4399 // the activity visible until the result is received. Setting
4400 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4401 // activity hidden during this time, to avoid flickering.
4402 // This can only be done when a result is requested because
4403 // that guarantees we will get information back when the
4404 // activity is finished, no matter what happens to it.
4405 mStartedActivity = true;
4407 return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
4410 throw new UnsupportedOperationException(
4411 "startActivityIfNeeded can only be called from a top-level activity");
4415 * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
4418 * @param intent The intent to dispatch to the next activity. For
4419 * correct behavior, this must be the same as the Intent that started
4420 * your own activity; the only changes you can make are to the extras
4423 * @return Returns a boolean indicating whether there was another Activity
4424 * to start: true if there was a next activity to start, false if there
4425 * wasn't. In general, if true is returned you will then want to call
4426 * finish() on yourself.
4428 public boolean startNextMatchingActivity(@NonNull Intent intent) {
4429 return startNextMatchingActivity(intent, null);
4433 * Special version of starting an activity, for use when you are replacing
4434 * other activity components. You can use this to hand the Intent off
4435 * to the next Activity that can handle it. You typically call this in
4436 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
4438 * @param intent The intent to dispatch to the next activity. For
4439 * correct behavior, this must be the same as the Intent that started
4440 * your own activity; the only changes you can make are to the extras
4442 * @param options Additional options for how the Activity should be started.
4443 * See {@link android.content.Context#startActivity(Intent, Bundle)
4444 * Context.startActivity(Intent, Bundle)} for more details.
4446 * @return Returns a boolean indicating whether there was another Activity
4447 * to start: true if there was a next activity to start, false if there
4448 * wasn't. In general, if true is returned you will then want to call
4449 * finish() on yourself.
4451 public boolean startNextMatchingActivity(@NonNull Intent intent, @Nullable Bundle options) {
4452 if (mParent == null) {
4454 intent.migrateExtraStreamToClipData();
4455 intent.prepareToLeaveProcess();
4456 return ActivityManagerNative.getDefault()
4457 .startNextMatchingActivity(mToken, intent, options);
4458 } catch (RemoteException e) {
4464 throw new UnsupportedOperationException(
4465 "startNextMatchingActivity can only be called from a top-level activity");
4469 * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
4472 * @param child The activity making the call.
4473 * @param intent The intent to start.
4474 * @param requestCode Reply request code. < 0 if reply is not requested.
4476 * @throws android.content.ActivityNotFoundException
4478 * @see #startActivity
4479 * @see #startActivityForResult
4481 public void startActivityFromChild(@NonNull Activity child, Intent intent,
4483 startActivityFromChild(child, intent, requestCode, null);
4487 * This is called when a child activity of this one calls its
4488 * {@link #startActivity} or {@link #startActivityForResult} method.
4490 * <p>This method throws {@link android.content.ActivityNotFoundException}
4491 * if there was no Activity found to run the given Intent.
4493 * @param child The activity making the call.
4494 * @param intent The intent to start.
4495 * @param requestCode Reply request code. < 0 if reply is not requested.
4496 * @param options Additional options for how the Activity should be started.
4497 * See {@link android.content.Context#startActivity(Intent, Bundle)
4498 * Context.startActivity(Intent, Bundle)} for more details.
4500 * @throws android.content.ActivityNotFoundException
4502 * @see #startActivity
4503 * @see #startActivityForResult
4505 public void startActivityFromChild(@NonNull Activity child, Intent intent,
4506 int requestCode, @Nullable Bundle options) {
4507 Instrumentation.ActivityResult ar =
4508 mInstrumentation.execStartActivity(
4509 this, mMainThread.getApplicationThread(), mToken, child,
4510 intent, requestCode, options);
4512 mMainThread.sendActivityResult(
4513 mToken, child.mEmbeddedID, requestCode,
4514 ar.getResultCode(), ar.getResultData());
4516 cancelInputsAndStartExitTransition(options);
4520 * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
4523 * @param fragment The fragment making the call.
4524 * @param intent The intent to start.
4525 * @param requestCode Reply request code. < 0 if reply is not requested.
4527 * @throws android.content.ActivityNotFoundException
4529 * @see Fragment#startActivity
4530 * @see Fragment#startActivityForResult
4532 public void startActivityFromFragment(@NonNull Fragment fragment, Intent intent,
4534 startActivityFromFragment(fragment, intent, requestCode, null);
4538 * This is called when a Fragment in this activity calls its
4539 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
4542 * <p>This method throws {@link android.content.ActivityNotFoundException}
4543 * if there was no Activity found to run the given Intent.
4545 * @param fragment The fragment making the call.
4546 * @param intent The intent to start.
4547 * @param requestCode Reply request code. < 0 if reply is not requested.
4548 * @param options Additional options for how the Activity should be started.
4549 * See {@link android.content.Context#startActivity(Intent, Bundle)
4550 * Context.startActivity(Intent, Bundle)} for more details.
4552 * @throws android.content.ActivityNotFoundException
4554 * @see Fragment#startActivity
4555 * @see Fragment#startActivityForResult
4557 public void startActivityFromFragment(@NonNull Fragment fragment, Intent intent,
4558 int requestCode, @Nullable Bundle options) {
4559 startActivityForResult(fragment.mWho, intent, requestCode, options);
4566 public void startActivityForResult(
4567 String who, Intent intent, int requestCode, @Nullable Bundle options) {
4568 Uri referrer = onProvideReferrer();
4569 if (referrer != null) {
4570 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4572 Instrumentation.ActivityResult ar =
4573 mInstrumentation.execStartActivity(
4574 this, mMainThread.getApplicationThread(), mToken, who,
4575 intent, requestCode, options);
4577 mMainThread.sendActivityResult(
4578 mToken, who, requestCode,
4579 ar.getResultCode(), ar.getResultData());
4581 cancelInputsAndStartExitTransition(options);
4588 public boolean canStartActivityForResult() {
4593 * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
4594 * int, Intent, int, int, int, Bundle)} with no options.
4596 public void startIntentSenderFromChild(Activity child, IntentSender intent,
4597 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
4599 throws IntentSender.SendIntentException {
4600 startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
4601 flagsMask, flagsValues, extraFlags, null);
4605 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
4606 * taking a IntentSender; see
4607 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
4608 * for more information.
4610 public void startIntentSenderFromChild(Activity child, IntentSender intent,
4611 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
4612 int extraFlags, @Nullable Bundle options)
4613 throws IntentSender.SendIntentException {
4614 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
4615 flagsMask, flagsValues, child, options);
4619 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
4620 * or {@link #finish} to specify an explicit transition animation to
4623 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
4624 * to using this with starting activities is to supply the desired animation
4625 * information through a {@link ActivityOptions} bundle to
4626 * {@link #startActivity(Intent, Bundle) or a related function. This allows
4627 * you to specify a custom animation even when starting an activity from
4628 * outside the context of the current top activity.
4630 * @param enterAnim A resource ID of the animation resource to use for
4631 * the incoming activity. Use 0 for no animation.
4632 * @param exitAnim A resource ID of the animation resource to use for
4633 * the outgoing activity. Use 0 for no animation.
4635 public void overridePendingTransition(int enterAnim, int exitAnim) {
4637 ActivityManagerNative.getDefault().overridePendingTransition(
4638 mToken, getPackageName(), enterAnim, exitAnim);
4639 } catch (RemoteException e) {
4644 * Call this to set the result that your activity will return to its
4647 * @param resultCode The result code to propagate back to the originating
4648 * activity, often RESULT_CANCELED or RESULT_OK
4650 * @see #RESULT_CANCELED
4652 * @see #RESULT_FIRST_USER
4653 * @see #setResult(int, Intent)
4655 public final void setResult(int resultCode) {
4656 synchronized (this) {
4657 mResultCode = resultCode;
4663 * Call this to set the result that your activity will return to its
4666 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
4667 * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
4668 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4669 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the
4670 * Activity receiving the result access to the specific URIs in the Intent.
4671 * Access will remain until the Activity has finished (it will remain across the hosting
4672 * process being killed and other temporary destruction) and will be added
4673 * to any existing set of URI permissions it already holds.
4675 * @param resultCode The result code to propagate back to the originating
4676 * activity, often RESULT_CANCELED or RESULT_OK
4677 * @param data The data to propagate back to the originating activity.
4679 * @see #RESULT_CANCELED
4681 * @see #RESULT_FIRST_USER
4682 * @see #setResult(int)
4684 public final void setResult(int resultCode, Intent data) {
4685 synchronized (this) {
4686 mResultCode = resultCode;
4692 * Return information about who launched this activity. If the launching Intent
4693 * contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
4694 * that will be returned as-is; otherwise, if known, an
4695 * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
4696 * package name that started the Intent will be returned. This may return null if no
4697 * referrer can be identified -- it is neither explicitly specified, nor is it known which
4698 * application package was involved.
4700 * <p>If called while inside the handling of {@link #onNewIntent}, this function will
4701 * return the referrer that submitted that new intent to the activity. Otherwise, it
4702 * always returns the referrer of the original Intent.</p>
4704 * <p>Note that this is <em>not</em> a security feature -- you can not trust the
4705 * referrer information, applications can spoof it.</p>
4708 public Uri getReferrer() {
4709 Intent intent = getIntent();
4710 Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
4711 if (referrer != null) {
4714 String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
4715 if (referrerName != null) {
4716 return Uri.parse(referrerName);
4718 if (mReferrer != null) {
4719 return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
4725 * Override to generate the desired referrer for the content currently being shown
4726 * by the app. The default implementation returns null, meaning the referrer will simply
4727 * be the android-app: of the package name of this activity. Return a non-null Uri to
4728 * have that supplied as the {@link Intent#EXTRA_REFERRER} of any activities started from it.
4730 public Uri onProvideReferrer() {
4735 * Return the name of the package that invoked this activity. This is who
4736 * the data in {@link #setResult setResult()} will be sent to. You can
4737 * use this information to validate that the recipient is allowed to
4740 * <p class="note">Note: if the calling activity is not expecting a result (that is it
4741 * did not use the {@link #startActivityForResult}
4742 * form that includes a request code), then the calling package will be
4745 * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
4746 * the result from this method was unstable. If the process hosting the calling
4747 * package was no longer running, it would return null instead of the proper package
4748 * name. You can use {@link #getCallingActivity()} and retrieve the package name
4749 * from that instead.</p>
4751 * @return The package of the activity that will receive your
4752 * reply, or null if none.
4755 public String getCallingPackage() {
4757 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
4758 } catch (RemoteException e) {
4764 * Return the name of the activity that invoked this activity. This is
4765 * who the data in {@link #setResult setResult()} will be sent to. You
4766 * can use this information to validate that the recipient is allowed to
4769 * <p class="note">Note: if the calling activity is not expecting a result (that is it
4770 * did not use the {@link #startActivityForResult}
4771 * form that includes a request code), then the calling package will be
4774 * @return The ComponentName of the activity that will receive your
4775 * reply, or null if none.
4778 public ComponentName getCallingActivity() {
4780 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
4781 } catch (RemoteException e) {
4787 * Control whether this activity's main window is visible. This is intended
4788 * only for the special case of an activity that is not going to show a
4789 * UI itself, but can't just finish prior to onResume() because it needs
4790 * to wait for a service binding or such. Setting this to false allows
4791 * you to prevent your UI from being shown during that time.
4793 * <p>The default value for this is taken from the
4794 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
4796 public void setVisible(boolean visible) {
4797 if (mVisibleFromClient != visible) {
4798 mVisibleFromClient = visible;
4799 if (mVisibleFromServer) {
4800 if (visible) makeVisible();
4801 else mDecor.setVisibility(View.INVISIBLE);
4806 void makeVisible() {
4807 if (!mWindowAdded) {
4808 ViewManager wm = getWindowManager();
4809 wm.addView(mDecor, getWindow().getAttributes());
4810 mWindowAdded = true;
4812 mDecor.setVisibility(View.VISIBLE);
4816 * Check to see whether this activity is in the process of finishing,
4817 * either because you called {@link #finish} on it or someone else
4818 * has requested that it finished. This is often used in
4819 * {@link #onPause} to determine whether the activity is simply pausing or
4820 * completely finishing.
4822 * @return If the activity is finishing, returns true; else returns false.
4826 public boolean isFinishing() {
4831 * Returns true if the final {@link #onDestroy()} call has been made
4832 * on the Activity, so this instance is now dead.
4834 public boolean isDestroyed() {
4839 * Check to see whether this activity is in the process of being destroyed in order to be
4840 * recreated with a new configuration. This is often used in
4841 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
4842 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
4844 * @return If the activity is being torn down in order to be recreated with a new configuration,
4845 * returns true; else returns false.
4847 public boolean isChangingConfigurations() {
4848 return mChangingConfigurations;
4852 * Cause this Activity to be recreated with a new instance. This results
4853 * in essentially the same flow as when the Activity is created due to
4854 * a configuration change -- the current instance will go through its
4855 * lifecycle to {@link #onDestroy} and a new instance then created after it.
4857 public void recreate() {
4858 if (mParent != null) {
4859 throw new IllegalStateException("Can only be called on top-level activity");
4861 if (Looper.myLooper() != mMainThread.getLooper()) {
4862 throw new IllegalStateException("Must be called from main thread");
4864 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, null, false);
4868 * Finishes the current activity and specifies whether to remove the task associated with this
4871 private void finish(boolean finishTask) {
4872 if (mParent == null) {
4875 synchronized (this) {
4876 resultCode = mResultCode;
4877 resultData = mResultData;
4879 if (false) Log.v(TAG, "Finishing self: token=" + mToken);
4881 if (resultData != null) {
4882 resultData.prepareToLeaveProcess();
4884 if (ActivityManagerNative.getDefault()
4885 .finishActivity(mToken, resultCode, resultData, finishTask)) {
4888 } catch (RemoteException e) {
4892 mParent.finishFromChild(this);
4897 * Call this when your activity is done and should be closed. The
4898 * ActivityResult is propagated back to whoever launched you via
4899 * onActivityResult().
4901 public void finish() {
4906 * Finish this activity as well as all activities immediately below it
4907 * in the current task that have the same affinity. This is typically
4908 * used when an application can be launched on to another task (such as
4909 * from an ACTION_VIEW of a content type it understands) and the user
4910 * has used the up navigation to switch out of the current task and in
4911 * to its own task. In this case, if the user has navigated down into
4912 * any other activities of the second application, all of those should
4913 * be removed from the original task as part of the task switch.
4915 * <p>Note that this finish does <em>not</em> allow you to deliver results
4916 * to the previous activity, and an exception will be thrown if you are trying
4919 public void finishAffinity() {
4920 if (mParent != null) {
4921 throw new IllegalStateException("Can not be called from an embedded activity");
4923 if (mResultCode != RESULT_CANCELED || mResultData != null) {
4924 throw new IllegalStateException("Can not be called to deliver a result");
4927 if (ActivityManagerNative.getDefault().finishActivityAffinity(mToken)) {
4930 } catch (RemoteException e) {
4936 * This is called when a child activity of this one calls its
4937 * {@link #finish} method. The default implementation simply calls
4938 * finish() on this activity (the parent), finishing the entire group.
4940 * @param child The activity making the call.
4944 public void finishFromChild(Activity child) {
4949 * Reverses the Activity Scene entry Transition and triggers the calling Activity
4950 * to reverse its exit Transition. When the exit Transition completes,
4951 * {@link #finish()} is called. If no entry Transition was used, finish() is called
4952 * immediately and the Activity exit Transition is run.
4953 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, android.util.Pair[])
4955 public void finishAfterTransition() {
4956 if (!mActivityTransitionState.startExitBackTransition(this)) {
4962 * Force finish another activity that you had previously started with
4963 * {@link #startActivityForResult}.
4965 * @param requestCode The request code of the activity that you had
4966 * given to startActivityForResult(). If there are multiple
4967 * activities started with this request code, they
4968 * will all be finished.
4970 public void finishActivity(int requestCode) {
4971 if (mParent == null) {
4973 ActivityManagerNative.getDefault()
4974 .finishSubActivity(mToken, mEmbeddedID, requestCode);
4975 } catch (RemoteException e) {
4979 mParent.finishActivityFromChild(this, requestCode);
4984 * This is called when a child activity of this one calls its
4987 * @param child The activity making the call.
4988 * @param requestCode Request code that had been used to start the
4991 public void finishActivityFromChild(@NonNull Activity child, int requestCode) {
4993 ActivityManagerNative.getDefault()
4994 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
4995 } catch (RemoteException e) {
5001 * Call this when your activity is done and should be closed and the task should be completely
5002 * removed as a part of finishing the Activity.
5004 public void finishAndRemoveTask() {
5009 * Ask that the local app instance of this activity be released to free up its memory.
5010 * This is asking for the activity to be destroyed, but does <b>not</b> finish the activity --
5011 * a new instance of the activity will later be re-created if needed due to the user
5012 * navigating back to it.
5014 * @return Returns true if the activity was in a state that it has started the process
5015 * of destroying its current instance; returns false if for any reason this could not
5016 * be done: it is currently visible to the user, it is already being destroyed, it is
5017 * being finished, it hasn't yet saved its state, etc.
5019 public boolean releaseInstance() {
5021 return ActivityManagerNative.getDefault().releaseActivityInstance(mToken);
5022 } catch (RemoteException e) {
5029 * Called when an activity you launched exits, giving you the requestCode
5030 * you started it with, the resultCode it returned, and any additional
5031 * data from it. The <var>resultCode</var> will be
5032 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
5033 * didn't return any result, or crashed during its operation.
5035 * <p>You will receive this call immediately before onResume() when your
5036 * activity is re-starting.
5038 * <p>This method is never invoked if your activity sets
5039 * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
5040 * <code>true</code>.
5042 * @param requestCode The integer request code originally supplied to
5043 * startActivityForResult(), allowing you to identify who this
5045 * @param resultCode The integer result code returned by the child activity
5046 * through its setResult().
5047 * @param data An Intent, which can return result data to the caller
5048 * (various data can be attached to Intent "extras").
5050 * @see #startActivityForResult
5051 * @see #createPendingResult
5052 * @see #setResult(int)
5054 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
5058 * Called when an activity you launched with an activity transition exposes this
5059 * Activity through a returning activity transition, giving you the resultCode
5060 * and any additional data from it. This method will only be called if the activity
5061 * set a result code other than {@link #RESULT_CANCELED} and it supports activity
5062 * transitions with {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
5064 * <p>The purpose of this function is to let the called Activity send a hint about
5065 * its state so that this underlying Activity can prepare to be exposed. A call to
5066 * this method does not guarantee that the called Activity has or will be exiting soon.
5067 * It only indicates that it will expose this Activity's Window and it has
5068 * some data to pass to prepare it.</p>
5070 * @param resultCode The integer result code returned by the child activity
5071 * through its setResult().
5072 * @param data An Intent, which can return result data to the caller
5073 * (various data can be attached to Intent "extras").
5075 public void onActivityReenter(int resultCode, Intent data) {
5079 * Create a new PendingIntent object which you can hand to others
5080 * for them to use to send result data back to your
5081 * {@link #onActivityResult} callback. The created object will be either
5082 * one-shot (becoming invalid after a result is sent back) or multiple
5083 * (allowing any number of results to be sent through it).
5085 * @param requestCode Private request code for the sender that will be
5086 * associated with the result data when it is returned. The sender can not
5087 * modify this value, allowing you to identify incoming results.
5088 * @param data Default data to supply in the result, which may be modified
5090 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
5091 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
5092 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
5093 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
5094 * or any of the flags as supported by
5095 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
5096 * of the intent that can be supplied when the actual send happens.
5098 * @return Returns an existing or new PendingIntent matching the given
5099 * parameters. May return null only if
5100 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
5103 * @see PendingIntent
5105 public PendingIntent createPendingResult(int requestCode, @NonNull Intent data,
5106 @PendingIntent.Flags int flags) {
5107 String packageName = getPackageName();
5109 data.prepareToLeaveProcess();
5110 IIntentSender target =
5111 ActivityManagerNative.getDefault().getIntentSender(
5112 ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
5113 mParent == null ? mToken : mParent.mToken,
5114 mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null,
5115 UserHandle.myUserId());
5116 return target != null ? new PendingIntent(target) : null;
5117 } catch (RemoteException e) {
5124 * Change the desired orientation of this activity. If the activity
5125 * is currently in the foreground or otherwise impacting the screen
5126 * orientation, the screen will immediately be changed (possibly causing
5127 * the activity to be restarted). Otherwise, this will be used the next
5128 * time the activity is visible.
5130 * @param requestedOrientation An orientation constant as used in
5131 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5133 public void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) {
5134 if (mParent == null) {
5136 ActivityManagerNative.getDefault().setRequestedOrientation(
5137 mToken, requestedOrientation);
5138 } catch (RemoteException e) {
5142 mParent.setRequestedOrientation(requestedOrientation);
5147 * Return the current requested orientation of the activity. This will
5148 * either be the orientation requested in its component's manifest, or
5149 * the last requested orientation given to
5150 * {@link #setRequestedOrientation(int)}.
5152 * @return Returns an orientation constant as used in
5153 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5155 @ActivityInfo.ScreenOrientation
5156 public int getRequestedOrientation() {
5157 if (mParent == null) {
5159 return ActivityManagerNative.getDefault()
5160 .getRequestedOrientation(mToken);
5161 } catch (RemoteException e) {
5165 return mParent.getRequestedOrientation();
5167 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
5171 * Return the identifier of the task this activity is in. This identifier
5172 * will remain the same for the lifetime of the activity.
5174 * @return Task identifier, an opaque integer.
5176 public int getTaskId() {
5178 return ActivityManagerNative.getDefault()
5179 .getTaskForActivity(mToken, false);
5180 } catch (RemoteException e) {
5186 * Return whether this activity is the root of a task. The root is the
5187 * first activity in a task.
5189 * @return True if this is the root activity, else false.
5191 public boolean isTaskRoot() {
5193 return ActivityManagerNative.getDefault()
5194 .getTaskForActivity(mToken, true) >= 0;
5195 } catch (RemoteException e) {
5201 * Move the task containing this activity to the back of the activity
5202 * stack. The activity's order within the task is unchanged.
5204 * @param nonRoot If false then this only works if the activity is the root
5205 * of a task; if true it will work for any activity in
5208 * @return If the task was moved (or it was already at the
5209 * back) true is returned, else false.
5211 public boolean moveTaskToBack(boolean nonRoot) {
5213 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
5215 } catch (RemoteException e) {
5222 * Returns class name for this activity with the package prefix removed.
5223 * This is the default name used to read and write settings.
5225 * @return The local class name.
5228 public String getLocalClassName() {
5229 final String pkg = getPackageName();
5230 final String cls = mComponent.getClassName();
5231 int packageLen = pkg.length();
5232 if (!cls.startsWith(pkg) || cls.length() <= packageLen
5233 || cls.charAt(packageLen) != '.') {
5236 return cls.substring(packageLen+1);
5240 * Returns complete component name of this activity.
5242 * @return Returns the complete component name for this activity
5244 public ComponentName getComponentName()
5250 * Retrieve a {@link SharedPreferences} object for accessing preferences
5251 * that are private to this activity. This simply calls the underlying
5252 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
5253 * class name as the preferences name.
5255 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
5256 * operation, {@link #MODE_WORLD_READABLE} and
5257 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
5259 * @return Returns the single SharedPreferences instance that can be used
5260 * to retrieve and modify the preference values.
5262 public SharedPreferences getPreferences(int mode) {
5263 return getSharedPreferences(getLocalClassName(), mode);
5266 private void ensureSearchManager() {
5267 if (mSearchManager != null) {
5271 mSearchManager = new SearchManager(this, null);
5275 public Object getSystemService(@ServiceName @NonNull String name) {
5276 if (getBaseContext() == null) {
5277 throw new IllegalStateException(
5278 "System services not available to Activities before onCreate()");
5281 if (WINDOW_SERVICE.equals(name)) {
5282 return mWindowManager;
5283 } else if (SEARCH_SERVICE.equals(name)) {
5284 ensureSearchManager();
5285 return mSearchManager;
5287 return super.getSystemService(name);
5291 * Change the title associated with this activity. If this is a
5292 * top-level activity, the title for its window will change. If it
5293 * is an embedded activity, the parent can do whatever it wants
5296 public void setTitle(CharSequence title) {
5298 onTitleChanged(title, mTitleColor);
5300 if (mParent != null) {
5301 mParent.onChildTitleChanged(this, title);
5306 * Change the title associated with this activity. If this is a
5307 * top-level activity, the title for its window will change. If it
5308 * is an embedded activity, the parent can do whatever it wants
5311 public void setTitle(int titleId) {
5312 setTitle(getText(titleId));
5316 * Change the color of the title associated with this activity.
5318 * This method is deprecated starting in API Level 11 and replaced by action
5319 * bar styles. For information on styling the Action Bar, read the <a
5320 * href="{@docRoot} guide/topics/ui/actionbar.html">Action Bar</a> developer
5323 * @deprecated Use action bar styles instead.
5326 public void setTitleColor(int textColor) {
5327 mTitleColor = textColor;
5328 onTitleChanged(mTitle, textColor);
5331 public final CharSequence getTitle() {
5335 public final int getTitleColor() {
5339 protected void onTitleChanged(CharSequence title, int color) {
5341 final Window win = getWindow();
5343 win.setTitle(title);
5345 win.setTitleColor(color);
5348 if (mActionBar != null) {
5349 mActionBar.setWindowTitle(title);
5354 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
5358 * Sets information describing the task with this activity for presentation inside the Recents
5359 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
5360 * are traversed in order from the topmost activity to the bottommost. The traversal continues
5361 * for each property until a suitable value is found. For each task the taskDescription will be
5362 * returned in {@link android.app.ActivityManager.TaskDescription}.
5364 * @see ActivityManager#getRecentTasks
5365 * @see android.app.ActivityManager.TaskDescription
5367 * @param taskDescription The TaskDescription properties that describe the task with this activity
5369 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
5370 ActivityManager.TaskDescription td;
5371 // Scale the icon down to something reasonable if it is provided
5372 if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
5373 final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
5374 final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size, true);
5375 td = new ActivityManager.TaskDescription(taskDescription.getLabel(), icon,
5376 taskDescription.getPrimaryColor());
5378 td = taskDescription;
5381 ActivityManagerNative.getDefault().setTaskDescription(mToken, td);
5382 } catch (RemoteException e) {
5387 * Sets the visibility of the progress bar in the title.
5389 * In order for the progress bar to be shown, the feature must be requested
5390 * via {@link #requestWindowFeature(int)}.
5392 * @param visible Whether to show the progress bars in the title.
5394 public final void setProgressBarVisibility(boolean visible) {
5395 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
5396 Window.PROGRESS_VISIBILITY_OFF);
5400 * Sets the visibility of the indeterminate progress bar in the title.
5402 * In order for the progress bar to be shown, the feature must be requested
5403 * via {@link #requestWindowFeature(int)}.
5405 * @param visible Whether to show the progress bars in the title.
5407 public final void setProgressBarIndeterminateVisibility(boolean visible) {
5408 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
5409 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
5413 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
5414 * is always indeterminate).
5416 * In order for the progress bar to be shown, the feature must be requested
5417 * via {@link #requestWindowFeature(int)}.
5419 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
5421 public final void setProgressBarIndeterminate(boolean indeterminate) {
5422 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
5423 indeterminate ? Window.PROGRESS_INDETERMINATE_ON
5424 : Window.PROGRESS_INDETERMINATE_OFF);
5428 * Sets the progress for the progress bars in the title.
5430 * In order for the progress bar to be shown, the feature must be requested
5431 * via {@link #requestWindowFeature(int)}.
5433 * @param progress The progress for the progress bar. Valid ranges are from
5434 * 0 to 10000 (both inclusive). If 10000 is given, the progress
5435 * bar will be completely filled and will fade out.
5437 public final void setProgress(int progress) {
5438 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
5442 * Sets the secondary progress for the progress bar in the title. This
5443 * progress is drawn between the primary progress (set via
5444 * {@link #setProgress(int)} and the background. It can be ideal for media
5445 * scenarios such as showing the buffering progress while the default
5446 * progress shows the play progress.
5448 * In order for the progress bar to be shown, the feature must be requested
5449 * via {@link #requestWindowFeature(int)}.
5451 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
5452 * 0 to 10000 (both inclusive).
5454 public final void setSecondaryProgress(int secondaryProgress) {
5455 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
5456 secondaryProgress + Window.PROGRESS_SECONDARY_START);
5460 * Suggests an audio stream whose volume should be changed by the hardware
5463 * The suggested audio stream will be tied to the window of this Activity.
5464 * Volume requests which are received while the Activity is in the
5465 * foreground will affect this stream.
5467 * It is not guaranteed that the hardware volume controls will always change
5468 * this stream's volume (for example, if a call is in progress, its stream's
5469 * volume may be changed instead). To reset back to the default, use
5470 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
5472 * @param streamType The type of the audio stream whose volume should be
5473 * changed by the hardware volume controls.
5475 public final void setVolumeControlStream(int streamType) {
5476 getWindow().setVolumeControlStream(streamType);
5480 * Gets the suggested audio stream whose volume should be changed by the
5481 * hardware volume controls.
5483 * @return The suggested audio stream type whose volume should be changed by
5484 * the hardware volume controls.
5485 * @see #setVolumeControlStream(int)
5487 public final int getVolumeControlStream() {
5488 return getWindow().getVolumeControlStream();
5492 * Sets a {@link MediaController} to send media keys and volume changes to.
5494 * The controller will be tied to the window of this Activity. Media key and
5495 * volume events which are received while the Activity is in the foreground
5496 * will be forwarded to the controller and used to invoke transport controls
5497 * or adjust the volume. This may be used instead of or in addition to
5498 * {@link #setVolumeControlStream} to affect a specific session instead of a
5501 * It is not guaranteed that the hardware volume controls will always change
5502 * this session's volume (for example, if a call is in progress, its
5503 * stream's volume may be changed instead). To reset back to the default use
5504 * null as the controller.
5506 * @param controller The controller for the session which should receive
5507 * media keys and volume changes.
5509 public final void setMediaController(MediaController controller) {
5510 getWindow().setMediaController(controller);
5514 * Gets the controller which should be receiving media key and volume events
5515 * while this activity is in the foreground.
5517 * @return The controller which should receive events.
5518 * @see #setMediaController(android.media.session.MediaController)
5520 public final MediaController getMediaController() {
5521 return getWindow().getMediaController();
5525 * Runs the specified action on the UI thread. If the current thread is the UI
5526 * thread, then the action is executed immediately. If the current thread is
5527 * not the UI thread, the action is posted to the event queue of the UI thread.
5529 * @param action the action to run on the UI thread
5531 public final void runOnUiThread(Runnable action) {
5532 if (Thread.currentThread() != mUiThread) {
5533 mHandler.post(action);
5540 * Standard implementation of
5541 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
5542 * inflating with the LayoutInflater returned by {@link #getSystemService}.
5543 * This implementation does nothing and is for
5544 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
5545 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
5547 * @see android.view.LayoutInflater#createView
5548 * @see android.view.Window#getLayoutInflater
5551 public View onCreateView(String name, Context context, AttributeSet attrs) {
5556 * Standard implementation of
5557 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
5558 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
5559 * This implementation handles <fragment> tags to embed fragments inside
5562 * @see android.view.LayoutInflater#createView
5563 * @see android.view.Window#getLayoutInflater
5565 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
5566 if (!"fragment".equals(name)) {
5567 return onCreateView(name, context, attrs);
5570 return mFragments.onCreateView(parent, name, context, attrs);
5574 * Print the Activity's state into the given stream. This gets invoked if
5575 * you run "adb shell dumpsys activity <activity_component_name>".
5577 * @param prefix Desired prefix to prepend at each line of output.
5578 * @param fd The raw file descriptor that the dump is being sent to.
5579 * @param writer The PrintWriter to which you should dump your state. This will be
5580 * closed for you after you return.
5581 * @param args additional arguments to the dump request.
5583 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5584 dumpInner(prefix, fd, writer, args);
5587 void dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5588 writer.print(prefix); writer.print("Local Activity ");
5589 writer.print(Integer.toHexString(System.identityHashCode(this)));
5590 writer.println(" State:");
5591 String innerPrefix = prefix + " ";
5592 writer.print(innerPrefix); writer.print("mResumed=");
5593 writer.print(mResumed); writer.print(" mStopped=");
5594 writer.print(mStopped); writer.print(" mFinished=");
5595 writer.println(mFinished);
5596 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
5597 writer.println(mChangingConfigurations);
5598 writer.print(innerPrefix); writer.print("mCurrentConfig=");
5599 writer.println(mCurrentConfig);
5601 mFragments.dumpLoaders(innerPrefix, fd, writer, args);
5602 mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args);
5603 if (mVoiceInteractor != null) {
5604 mVoiceInteractor.dump(innerPrefix, fd, writer, args);
5607 if (getWindow() != null &&
5608 getWindow().peekDecorView() != null &&
5609 getWindow().peekDecorView().getViewRootImpl() != null) {
5610 getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args);
5613 mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix);
5617 * Bit indicating that this activity is "immersive" and should not be
5618 * interrupted by notifications if possible.
5620 * This value is initially set by the manifest property
5621 * <code>android:immersive</code> but may be changed at runtime by
5622 * {@link #setImmersive}.
5624 * @see #setImmersive(boolean)
5625 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
5627 public boolean isImmersive() {
5629 return ActivityManagerNative.getDefault().isImmersive(mToken);
5630 } catch (RemoteException e) {
5636 * Indication of whether this is the highest level activity in this task. Can be used to
5637 * determine whether an activity launched by this activity was placed in the same task or
5640 * @return true if this is the topmost, non-finishing activity in its task.
5642 private boolean isTopOfTask() {
5644 return ActivityManagerNative.getDefault().isTopOfTask(mToken);
5645 } catch (RemoteException e) {
5651 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} to a
5652 * fullscreen opaque Activity.
5654 * Call this whenever the background of a translucent Activity has changed to become opaque.
5655 * Doing so will allow the {@link android.view.Surface} of the Activity behind to be released.
5657 * This call has no effect on non-translucent activities or on activities with the
5658 * {@link android.R.attr#windowIsFloating} attribute.
5660 * @see #convertToTranslucent(android.app.Activity.TranslucentConversionListener,
5662 * @see TranslucentConversionListener
5667 public void convertFromTranslucent() {
5669 mTranslucentCallback = null;
5670 if (ActivityManagerNative.getDefault().convertFromTranslucent(mToken)) {
5671 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true);
5673 } catch (RemoteException e) {
5679 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} back from
5680 * opaque to translucent following a call to {@link #convertFromTranslucent()}.
5682 * Calling this allows the Activity behind this one to be seen again. Once all such Activities
5683 * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
5684 * be called indicating that it is safe to make this activity translucent again. Until
5685 * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
5686 * behind the frontmost Activity will be indeterminate.
5688 * This call has no effect on non-translucent activities or on activities with the
5689 * {@link android.R.attr#windowIsFloating} attribute.
5691 * @param callback the method to call when all visible Activities behind this one have been
5692 * drawn and it is safe to make this Activity translucent again.
5693 * @param options activity options delivered to the activity below this one. The options
5694 * are retrieved using {@link #getActivityOptions}.
5695 * @return <code>true</code> if Window was opaque and will become translucent or
5696 * <code>false</code> if window was translucent and no change needed to be made.
5698 * @see #convertFromTranslucent()
5699 * @see TranslucentConversionListener
5704 public boolean convertToTranslucent(TranslucentConversionListener callback,
5705 ActivityOptions options) {
5706 boolean drawComplete;
5708 mTranslucentCallback = callback;
5709 mChangeCanvasToTranslucent =
5710 ActivityManagerNative.getDefault().convertToTranslucent(mToken, options);
5711 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
5712 drawComplete = true;
5713 } catch (RemoteException e) {
5714 // Make callback return as though it timed out.
5715 mChangeCanvasToTranslucent = false;
5716 drawComplete = false;
5718 if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) {
5719 // Window is already translucent.
5720 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
5722 return mChangeCanvasToTranslucent;
5726 void onTranslucentConversionComplete(boolean drawComplete) {
5727 if (mTranslucentCallback != null) {
5728 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
5729 mTranslucentCallback = null;
5731 if (mChangeCanvasToTranslucent) {
5732 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
5737 public void onNewActivityOptions(ActivityOptions options) {
5738 mActivityTransitionState.setEnterActivityOptions(this, options);
5740 mActivityTransitionState.enterReady(this);
5745 * Retrieve the ActivityOptions passed in from the launching activity or passed back
5746 * from an activity launched by this activity in its call to {@link
5747 * #convertToTranslucent(TranslucentConversionListener, ActivityOptions)}
5749 * @return The ActivityOptions passed to {@link #convertToTranslucent}.
5752 ActivityOptions getActivityOptions() {
5754 return ActivityManagerNative.getDefault().getActivityOptions(mToken);
5755 } catch (RemoteException e) {
5761 * Activities that want to remain visible behind a translucent activity above them must call
5762 * this method anytime between the start of {@link #onResume()} and the return from
5763 * {@link #onPause()}. If this call is successful then the activity will remain visible after
5764 * {@link #onPause()} is called, and is allowed to continue playing media in the background.
5766 * <p>The actions of this call are reset each time that this activity is brought to the
5767 * front. That is, every time {@link #onResume()} is called the activity will be assumed
5768 * to not have requested visible behind. Therefore, if you want this activity to continue to
5769 * be visible in the background you must call this method again.
5771 * <p>Only fullscreen opaque activities may make this call. I.e. this call is a nop
5772 * for dialog and translucent activities.
5774 * <p>Under all circumstances, the activity must stop playing and release resources prior to or
5775 * within a call to {@link #onVisibleBehindCanceled()} or if this call returns false.
5777 * <p>False will be returned any time this method is called between the return of onPause and
5778 * the next call to onResume.
5780 * @param visible true to notify the system that the activity wishes to be visible behind other
5781 * translucent activities, false to indicate otherwise. Resources must be
5782 * released when passing false to this method.
5783 * @return the resulting visibiity state. If true the activity will remain visible beyond
5784 * {@link #onPause()} if the next activity is translucent or not fullscreen. If false
5785 * then the activity may not count on being visible behind other translucent activities,
5786 * and must stop any media playback and release resources.
5787 * Returning false may occur in lieu of a call to {@link #onVisibleBehindCanceled()} so
5788 * the return value must be checked.
5790 * @see #onVisibleBehindCanceled()
5791 * @see #onBackgroundVisibleBehindChanged(boolean)
5793 public boolean requestVisibleBehind(boolean visible) {
5795 // Do not permit paused or stopped activities to do this.
5799 mVisibleBehind = ActivityManagerNative.getDefault()
5800 .requestVisibleBehind(mToken, visible) && visible;
5801 } catch (RemoteException e) {
5802 mVisibleBehind = false;
5804 return mVisibleBehind;
5808 * Called when a translucent activity over this activity is becoming opaque or another
5809 * activity is being launched. Activities that override this method must call
5810 * <code>super.onVisibleBehindCanceled()</code> or a SuperNotCalledException will be thrown.
5812 * <p>When this method is called the activity has 500 msec to release any resources it may be
5813 * using while visible in the background.
5814 * If the activity has not returned from this method in 500 msec the system will destroy
5815 * the activity and kill the process in order to recover the resources for another
5816 * process. Otherwise {@link #onStop()} will be called following return.
5818 * @see #requestVisibleBehind(boolean)
5819 * @see #onBackgroundVisibleBehindChanged(boolean)
5822 public void onVisibleBehindCanceled() {
5827 * Translucent activities may call this to determine if there is an activity below them that
5828 * is currently set to be visible in the background.
5830 * @return true if an activity below is set to visible according to the most recent call to
5831 * {@link #requestVisibleBehind(boolean)}, false otherwise.
5833 * @see #requestVisibleBehind(boolean)
5834 * @see #onVisibleBehindCanceled()
5835 * @see #onBackgroundVisibleBehindChanged(boolean)
5839 public boolean isBackgroundVisibleBehind() {
5841 return ActivityManagerNative.getDefault().isBackgroundVisibleBehind(mToken);
5842 } catch (RemoteException e) {
5848 * The topmost foreground activity will receive this call when the background visibility state
5849 * of the activity below it changes.
5851 * This call may be a consequence of {@link #requestVisibleBehind(boolean)} or might be
5852 * due to a background activity finishing itself.
5854 * @param visible true if a background activity is visible, false otherwise.
5856 * @see #requestVisibleBehind(boolean)
5857 * @see #onVisibleBehindCanceled()
5861 public void onBackgroundVisibleBehindChanged(boolean visible) {
5865 * Activities cannot draw during the period that their windows are animating in. In order
5866 * to know when it is safe to begin drawing they can override this method which will be
5867 * called when the entering animation has completed.
5869 public void onEnterAnimationComplete() {
5875 public void dispatchEnterAnimationComplete() {
5876 onEnterAnimationComplete();
5877 if (getWindow() != null && getWindow().getDecorView() != null) {
5878 getWindow().getDecorView().getViewTreeObserver().dispatchOnEnterAnimationComplete();
5883 * Adjust the current immersive mode setting.
5885 * Note that changing this value will have no effect on the activity's
5886 * {@link android.content.pm.ActivityInfo} structure; that is, if
5887 * <code>android:immersive</code> is set to <code>true</code>
5888 * in the application's manifest entry for this activity, the {@link
5889 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
5890 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
5891 * FLAG_IMMERSIVE} bit set.
5893 * @see #isImmersive()
5894 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
5896 public void setImmersive(boolean i) {
5898 ActivityManagerNative.getDefault().setImmersive(mToken, i);
5899 } catch (RemoteException e) {
5905 * Start an action mode of the default type {@link ActionMode#TYPE_PRIMARY}.
5907 * @param callback Callback that will manage lifecycle events for this action mode
5908 * @return The ActionMode that was started, or null if it was canceled
5913 public ActionMode startActionMode(ActionMode.Callback callback) {
5914 return mWindow.getDecorView().startActionMode(callback);
5918 * Start an action mode of the given type.
5920 * @param callback Callback that will manage lifecycle events for this action mode
5921 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5922 * @return The ActionMode that was started, or null if it was canceled
5927 public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5928 return mWindow.getDecorView().startActionMode(callback, type);
5932 * Give the Activity a chance to control the UI for an action mode requested
5935 * <p>Note: If you are looking for a notification callback that an action mode
5936 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
5938 * @param callback The callback that should control the new action mode
5939 * @return The new action mode, or <code>null</code> if the activity does not want to
5940 * provide special handling for this action mode. (It will be handled by the system.)
5944 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
5945 // Only Primary ActionModes are represented in the ActionBar.
5946 if (mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
5947 initWindowDecorActionBar();
5948 if (mActionBar != null) {
5949 return mActionBar.startActionMode(callback);
5960 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
5962 mActionModeTypeStarting = type;
5963 return onWindowStartingActionMode(callback);
5965 mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
5970 * Notifies the Activity that an action mode has been started.
5971 * Activity subclasses overriding this method should call the superclass implementation.
5973 * @param mode The new action mode.
5977 public void onActionModeStarted(ActionMode mode) {
5981 * Notifies the activity that an action mode has finished.
5982 * Activity subclasses overriding this method should call the superclass implementation.
5984 * @param mode The action mode that just finished.
5988 public void onActionModeFinished(ActionMode mode) {
5992 * Returns true if the app should recreate the task when navigating 'up' from this activity
5993 * by using targetIntent.
5995 * <p>If this method returns false the app can trivially call
5996 * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
5997 * up navigation. If this method returns false, the app should synthesize a new task stack
5998 * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
6000 * @param targetIntent An intent representing the target destination for up navigation
6001 * @return true if navigating up should recreate a new task stack, false if the same task
6002 * should be used for the destination
6004 public boolean shouldUpRecreateTask(Intent targetIntent) {
6006 PackageManager pm = getPackageManager();
6007 ComponentName cn = targetIntent.getComponent();
6009 cn = targetIntent.resolveActivity(pm);
6011 ActivityInfo info = pm.getActivityInfo(cn, 0);
6012 if (info.taskAffinity == null) {
6015 return ActivityManagerNative.getDefault()
6016 .shouldUpRecreateTask(mToken, info.taskAffinity);
6017 } catch (RemoteException e) {
6019 } catch (NameNotFoundException e) {
6025 * Navigate from this activity to the activity specified by upIntent, finishing this activity
6026 * in the process. If the activity indicated by upIntent already exists in the task's history,
6027 * this activity and all others before the indicated activity in the history stack will be
6030 * <p>If the indicated activity does not appear in the history stack, this will finish
6031 * each activity in this task until the root activity of the task is reached, resulting in
6032 * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
6033 * when an activity may be reached by a path not passing through a canonical parent
6036 * <p>This method should be used when performing up navigation from within the same task
6037 * as the destination. If up navigation should cross tasks in some cases, see
6038 * {@link #shouldUpRecreateTask(Intent)}.</p>
6040 * @param upIntent An intent representing the target destination for up navigation
6042 * @return true if up navigation successfully reached the activity indicated by upIntent and
6043 * upIntent was delivered to it. false if an instance of the indicated activity could
6044 * not be found and this activity was simply finished normally.
6046 public boolean navigateUpTo(Intent upIntent) {
6047 if (mParent == null) {
6048 ComponentName destInfo = upIntent.getComponent();
6049 if (destInfo == null) {
6050 destInfo = upIntent.resolveActivity(getPackageManager());
6051 if (destInfo == null) {
6054 upIntent = new Intent(upIntent);
6055 upIntent.setComponent(destInfo);
6059 synchronized (this) {
6060 resultCode = mResultCode;
6061 resultData = mResultData;
6063 if (resultData != null) {
6064 resultData.prepareToLeaveProcess();
6067 upIntent.prepareToLeaveProcess();
6068 return ActivityManagerNative.getDefault().navigateUpTo(mToken, upIntent,
6069 resultCode, resultData);
6070 } catch (RemoteException e) {
6074 return mParent.navigateUpToFromChild(this, upIntent);
6079 * This is called when a child activity of this one calls its
6080 * {@link #navigateUpTo} method. The default implementation simply calls
6081 * navigateUpTo(upIntent) on this activity (the parent).
6083 * @param child The activity making the call.
6084 * @param upIntent An intent representing the target destination for up navigation
6086 * @return true if up navigation successfully reached the activity indicated by upIntent and
6087 * upIntent was delivered to it. false if an instance of the indicated activity could
6088 * not be found and this activity was simply finished normally.
6090 public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
6091 return navigateUpTo(upIntent);
6095 * Obtain an {@link Intent} that will launch an explicit target activity specified by
6096 * this activity's logical parent. The logical parent is named in the application's manifest
6097 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
6098 * Activity subclasses may override this method to modify the Intent returned by
6099 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
6100 * the parent intent entirely.
6102 * @return a new Intent targeting the defined parent of this activity or null if
6103 * there is no valid parent.
6106 public Intent getParentActivityIntent() {
6107 final String parentName = mActivityInfo.parentActivityName;
6108 if (TextUtils.isEmpty(parentName)) {
6112 // If the parent itself has no parent, generate a main activity intent.
6113 final ComponentName target = new ComponentName(this, parentName);
6115 final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
6116 final String parentActivity = parentInfo.parentActivityName;
6117 final Intent parentIntent = parentActivity == null
6118 ? Intent.makeMainActivity(target)
6119 : new Intent().setComponent(target);
6120 return parentIntent;
6121 } catch (NameNotFoundException e) {
6122 Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
6129 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6130 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6131 * will be called to handle shared elements on the <i>launched</i> Activity. This requires
6132 * {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6134 * @param callback Used to manipulate shared element transitions on the launched Activity.
6136 public void setEnterSharedElementCallback(SharedElementCallback callback) {
6137 if (callback == null) {
6138 callback = SharedElementCallback.NULL_CALLBACK;
6140 mEnterTransitionListener = callback;
6144 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6145 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6146 * will be called to handle shared elements on the <i>launching</i> Activity. Most
6147 * calls will only come when returning from the started Activity.
6148 * This requires {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6150 * @param callback Used to manipulate shared element transitions on the launching Activity.
6152 public void setExitSharedElementCallback(SharedElementCallback callback) {
6153 if (callback == null) {
6154 callback = SharedElementCallback.NULL_CALLBACK;
6156 mExitTransitionListener = callback;
6160 * Postpone the entering activity transition when Activity was started with
6161 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6162 * android.util.Pair[])}.
6163 * <p>This method gives the Activity the ability to delay starting the entering and
6164 * shared element transitions until all data is loaded. Until then, the Activity won't
6165 * draw into its window, leaving the window transparent. This may also cause the
6166 * returning animation to be delayed until data is ready. This method should be
6167 * called in {@link #onCreate(android.os.Bundle)} or in
6168 * {@link #onActivityReenter(int, android.content.Intent)}.
6169 * {@link #startPostponedEnterTransition()} must be called to allow the Activity to
6170 * start the transitions. If the Activity did not use
6171 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6172 * android.util.Pair[])}, then this method does nothing.</p>
6174 public void postponeEnterTransition() {
6175 mActivityTransitionState.postponeEnterTransition();
6179 * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
6180 * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
6181 * to have your Activity start drawing.
6183 public void startPostponedEnterTransition() {
6184 mActivityTransitionState.startPostponedEnterTransition();
6187 // ------------------ Internal API ------------------
6189 final void setParent(Activity parent) {
6193 final void attach(Context context, ActivityThread aThread,
6194 Instrumentation instr, IBinder token, int ident,
6195 Application application, Intent intent, ActivityInfo info,
6196 CharSequence title, Activity parent, String id,
6197 NonConfigurationInstances lastNonConfigurationInstances,
6198 Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
6199 attachBaseContext(context);
6201 mFragments.attachHost(null /*parent*/);
6203 mWindow = new PhoneWindow(this);
6204 mWindow.setCallback(this);
6205 mWindow.setOnWindowDismissedCallback(this);
6206 mWindow.getLayoutInflater().setPrivateFactory(this);
6207 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
6208 mWindow.setSoftInputMode(info.softInputMode);
6210 if (info.uiOptions != 0) {
6211 mWindow.setUiOptions(info.uiOptions);
6213 mUiThread = Thread.currentThread();
6215 mMainThread = aThread;
6216 mInstrumentation = instr;
6219 mApplication = application;
6221 mReferrer = referrer;
6222 mComponent = intent.getComponent();
6223 mActivityInfo = info;
6227 mLastNonConfigurationInstances = lastNonConfigurationInstances;
6228 if (voiceInteractor != null) {
6229 if (lastNonConfigurationInstances != null) {
6230 mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
6232 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
6237 mWindow.setWindowManager(
6238 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
6239 mToken, mComponent.flattenToString(),
6240 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
6241 if (mParent != null) {
6242 mWindow.setContainer(mParent.getWindow());
6244 mWindowManager = mWindow.getWindowManager();
6245 mCurrentConfig = config;
6249 public final IBinder getActivityToken() {
6250 return mParent != null ? mParent.getActivityToken() : mToken;
6253 final void performCreateCommon() {
6254 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
6255 com.android.internal.R.styleable.Window_windowNoDisplay, false);
6256 mFragments.dispatchActivityCreated();
6257 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
6260 final void performCreate(Bundle icicle) {
6261 restoreHasCurrentPermissionRequest(icicle);
6263 mActivityTransitionState.readState(icicle);
6264 performCreateCommon();
6267 final void performCreate(Bundle icicle, PersistableBundle persistentState) {
6268 restoreHasCurrentPermissionRequest(icicle);
6269 onCreate(icicle, persistentState);
6270 mActivityTransitionState.readState(icicle);
6271 performCreateCommon();
6274 final void performStart() {
6275 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
6276 mFragments.noteStateNotSaved();
6278 mFragments.execPendingActions();
6279 mInstrumentation.callActivityOnStart(this);
6281 throw new SuperNotCalledException(
6282 "Activity " + mComponent.toShortString() +
6283 " did not call through to super.onStart()");
6285 mFragments.dispatchStart();
6286 mFragments.reportLoaderStart();
6287 mActivityTransitionState.enterReady(this);
6290 final void performRestart() {
6291 mFragments.noteStateNotSaved();
6295 if (mToken != null && mParent == null) {
6296 WindowManagerGlobal.getInstance().setStoppedState(mToken, false);
6299 synchronized (mManagedCursors) {
6300 final int N = mManagedCursors.size();
6301 for (int i=0; i<N; i++) {
6302 ManagedCursor mc = mManagedCursors.get(i);
6303 if (mc.mReleased || mc.mUpdated) {
6304 if (!mc.mCursor.requery()) {
6305 if (getApplicationInfo().targetSdkVersion
6306 >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
6307 throw new IllegalStateException(
6308 "trying to requery an already closed cursor "
6312 mc.mReleased = false;
6313 mc.mUpdated = false;
6319 mInstrumentation.callActivityOnRestart(this);
6321 throw new SuperNotCalledException(
6322 "Activity " + mComponent.toShortString() +
6323 " did not call through to super.onRestart()");
6329 final void performResume() {
6332 mFragments.execPendingActions();
6334 mLastNonConfigurationInstances = null;
6337 // mResumed is set by the instrumentation
6338 mInstrumentation.callActivityOnResume(this);
6340 throw new SuperNotCalledException(
6341 "Activity " + mComponent.toShortString() +
6342 " did not call through to super.onResume()");
6345 // invisible activities must be finished before onResume() completes
6346 if (!mVisibleFromClient && !mFinished) {
6347 Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
6348 if (getApplicationInfo().targetSdkVersion
6349 > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
6350 throw new IllegalStateException(
6351 "Activity " + mComponent.toShortString() +
6352 " did not call finish() prior to onResume() completing");
6356 // Now really resume, and install the current status bar and menu.
6359 mFragments.dispatchResume();
6360 mFragments.execPendingActions();
6364 throw new SuperNotCalledException(
6365 "Activity " + mComponent.toShortString() +
6366 " did not call through to super.onPostResume()");
6370 final void performPause() {
6371 mDoReportFullyDrawn = false;
6372 mFragments.dispatchPause();
6376 if (!mCalled && getApplicationInfo().targetSdkVersion
6377 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
6378 throw new SuperNotCalledException(
6379 "Activity " + mComponent.toShortString() +
6380 " did not call through to super.onPause()");
6385 final void performUserLeaving() {
6386 onUserInteraction();
6390 final void performStop() {
6391 mDoReportFullyDrawn = false;
6392 mFragments.doLoaderStop(mChangingConfigurations /*retain*/);
6395 if (mWindow != null) {
6396 mWindow.closeAllPanels();
6399 if (mToken != null && mParent == null) {
6400 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
6403 mFragments.dispatchStop();
6406 mInstrumentation.callActivityOnStop(this);
6408 throw new SuperNotCalledException(
6409 "Activity " + mComponent.toShortString() +
6410 " did not call through to super.onStop()");
6413 synchronized (mManagedCursors) {
6414 final int N = mManagedCursors.size();
6415 for (int i=0; i<N; i++) {
6416 ManagedCursor mc = mManagedCursors.get(i);
6417 if (!mc.mReleased) {
6418 mc.mCursor.deactivate();
6419 mc.mReleased = true;
6429 final void performDestroy() {
6432 mFragments.dispatchDestroy();
6434 mFragments.doLoaderDestroy();
6435 if (mVoiceInteractor != null) {
6436 mVoiceInteractor.detachActivity();
6443 public final boolean isResumed() {
6447 private void storeHasCurrentPermissionRequest(Bundle bundle) {
6448 if (bundle != null && mHasCurrentPermissionsRequest) {
6449 bundle.putBoolean(HAS_CURENT_PERMISSIONS_REQUEST_KEY, true);
6453 private void restoreHasCurrentPermissionRequest(Bundle bundle) {
6454 if (bundle != null) {
6455 mHasCurrentPermissionsRequest = bundle.getBoolean(
6456 HAS_CURENT_PERMISSIONS_REQUEST_KEY, false);
6460 void dispatchActivityResult(String who, int requestCode,
6461 int resultCode, Intent data) {
6463 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
6464 + ", resCode=" + resultCode + ", data=" + data);
6465 mFragments.noteStateNotSaved();
6467 onActivityResult(requestCode, resultCode, data);
6468 } else if (who.startsWith(REQUEST_PERMISSIONS_WHO_PREFIX)) {
6469 who = who.substring(REQUEST_PERMISSIONS_WHO_PREFIX.length());
6470 if (TextUtils.isEmpty(who)) {
6471 dispatchRequestPermissionsResult(requestCode, data);
6473 Fragment frag = mFragments.findFragmentByWho(who);
6475 dispatchRequestPermissionsResultToFragment(requestCode, data, frag);
6478 } else if (who.startsWith("@android:view:")) {
6479 ArrayList<ViewRootImpl> views = WindowManagerGlobal.getInstance().getRootViews(
6480 getActivityToken());
6481 for (ViewRootImpl viewRoot : views) {
6482 if (viewRoot.getView() != null
6483 && viewRoot.getView().dispatchActivityResult(
6484 who, requestCode, resultCode, data)) {
6489 Fragment frag = mFragments.findFragmentByWho(who);
6491 frag.onActivityResult(requestCode, resultCode, data);
6497 * Request to put this Activity in a mode where the user is locked to the
6500 * This will prevent the user from launching other apps, going to settings, or reaching the
6501 * home screen. This does not include those apps whose {@link android.R.attr#lockTaskMode}
6502 * values permit launching while locked.
6504 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns true or
6505 * lockTaskMode=lockTaskModeAlways for this component then the app will go directly into
6506 * Lock Task mode. The user will not be able to exit this mode until
6507 * {@link Activity#stopLockTask()} is called.
6509 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns false
6510 * then the system will prompt the user with a dialog requesting permission to enter
6511 * this mode. When entered through this method the user can exit at any time through
6512 * an action described by the request dialog. Calling stopLockTask will also exit the
6515 * @see android.R.attr#lockTaskMode
6517 public void startLockTask() {
6519 ActivityManagerNative.getDefault().startLockTaskMode(mToken);
6520 } catch (RemoteException e) {
6525 * Allow the user to switch away from the current task.
6527 * Called to end the mode started by {@link Activity#startLockTask}. This
6528 * can only be called by activities that have successfully called
6529 * startLockTask previously.
6531 * This will allow the user to exit this app and move onto other activities.
6532 * <p>Note: This method should only be called when the activity is user-facing. That is,
6533 * between onResume() and onPause().
6534 * <p>Note: If there are other tasks below this one that are also locked then calling this
6535 * method will immediately finish this task and resume the previous locked one, remaining in
6538 * @see android.R.attr#lockTaskMode
6539 * @see ActivityManager#getLockTaskModeState()
6541 public void stopLockTask() {
6543 ActivityManagerNative.getDefault().stopLockTaskMode();
6544 } catch (RemoteException e) {
6549 * Shows the user the system defined message for telling the user how to exit
6550 * lock task mode. The task containing this activity must be in lock task mode at the time
6551 * of this call for the message to be displayed.
6553 public void showLockTaskEscapeMessage() {
6555 ActivityManagerNative.getDefault().showLockTaskEscapeMessage(mToken);
6556 } catch (RemoteException e) {
6561 * Interface for informing a translucent {@link Activity} once all visible activities below it
6562 * have completed drawing. This is necessary only after an {@link Activity} has been made
6563 * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
6564 * translucent again following a call to {@link
6565 * Activity#convertToTranslucent(android.app.Activity.TranslucentConversionListener,
6571 public interface TranslucentConversionListener {
6573 * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
6574 * below the top one have been redrawn. Following this callback it is safe to make the top
6575 * Activity translucent because the underlying Activity has been drawn.
6577 * @param drawComplete True if the background Activity has drawn itself. False if a timeout
6578 * occurred waiting for the Activity to complete drawing.
6580 * @see Activity#convertFromTranslucent()
6581 * @see Activity#convertToTranslucent(TranslucentConversionListener, ActivityOptions)
6583 public void onTranslucentConversionComplete(boolean drawComplete);
6586 private void dispatchRequestPermissionsResult(int requestCode, Intent data) {
6587 mHasCurrentPermissionsRequest = false;
6588 // If the package installer crashed we may have not data - best effort.
6589 String[] permissions = (data != null) ? data.getStringArrayExtra(
6590 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
6591 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
6592 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
6593 onRequestPermissionsResult(requestCode, permissions, grantResults);
6596 private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data,
6597 Fragment fragment) {
6598 // If the package installer crashed we may have not data - best effort.
6599 String[] permissions = (data != null) ? data.getStringArrayExtra(
6600 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
6601 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
6602 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
6603 fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
6606 class HostCallbacks extends FragmentHostCallback<Activity> {
6607 public HostCallbacks() {
6608 super(Activity.this /*activity*/);
6612 public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
6613 Activity.this.dump(prefix, fd, writer, args);
6617 public boolean onShouldSaveFragmentState(Fragment fragment) {
6618 return !isFinishing();
6622 public LayoutInflater onGetLayoutInflater() {
6623 final LayoutInflater result = Activity.this.getLayoutInflater();
6624 if (onUseFragmentManagerInflaterFactory()) {
6625 return result.cloneInContext(Activity.this);
6631 public boolean onUseFragmentManagerInflaterFactory() {
6632 // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
6633 return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
6637 public Activity onGetHost() {
6638 return Activity.this;
6642 public void onInvalidateOptionsMenu() {
6643 Activity.this.invalidateOptionsMenu();
6647 public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
6649 Activity.this.startActivityFromFragment(fragment, intent, requestCode, options);
6653 public void onRequestPermissionsFromFragment(Fragment fragment, String[] permissions,
6655 String who = REQUEST_PERMISSIONS_WHO_PREFIX + fragment.mWho;
6656 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
6657 startActivityForResult(who, intent, requestCode, null);
6661 public boolean onHasWindowAnimations() {
6662 return getWindow() != null;
6666 public int onGetWindowAnimations() {
6667 final Window w = getWindow();
6668 return (w == null) ? 0 : w.getAttributes().windowAnimations;
6672 public void onAttachFragment(Fragment fragment) {
6673 Activity.this.onAttachFragment(fragment);
6678 public View onFindViewById(int id) {
6679 return Activity.this.findViewById(id);
6683 public boolean onHasView() {
6684 final Window w = getWindow();
6685 return (w != null && w.peekDecorView() != null);