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.UserHandle;
73 import android.text.Selection;
74 import android.text.SpannableStringBuilder;
75 import android.text.TextUtils;
76 import android.text.method.TextKeyListener;
77 import android.util.AttributeSet;
78 import android.util.EventLog;
79 import android.util.Log;
80 import android.util.PrintWriterPrinter;
81 import android.util.Slog;
82 import android.util.SparseArray;
83 import android.view.ActionMode;
84 import android.view.ContextMenu;
85 import android.view.ContextMenu.ContextMenuInfo;
86 import android.view.ContextThemeWrapper;
87 import android.view.KeyEvent;
88 import android.view.LayoutInflater;
89 import android.view.Menu;
90 import android.view.MenuInflater;
91 import android.view.MenuItem;
92 import android.view.MotionEvent;
93 import com.android.internal.policy.PhoneWindow;
94 import android.view.SearchEvent;
95 import android.view.View;
96 import android.view.View.OnCreateContextMenuListener;
97 import android.view.ViewGroup;
98 import android.view.ViewGroup.LayoutParams;
99 import android.view.ViewManager;
100 import android.view.ViewRootImpl;
101 import android.view.Window;
102 import android.view.WindowManager;
103 import android.view.WindowManagerGlobal;
104 import android.view.accessibility.AccessibilityEvent;
105 import android.widget.AdapterView;
107 import java.io.FileDescriptor;
108 import java.io.PrintWriter;
109 import java.lang.annotation.Retention;
110 import java.lang.annotation.RetentionPolicy;
111 import java.util.ArrayList;
112 import java.util.HashMap;
113 import java.util.List;
116 * An activity is a single, focused thing that the user can do. Almost all
117 * activities interact with the user, so the Activity class takes care of
118 * creating a window for you in which you can place your UI with
119 * {@link #setContentView}. While activities are often presented to the user
120 * as full-screen windows, they can also be used in other ways: as floating
121 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
122 * or embedded inside of another activity (using {@link ActivityGroup}).
124 * There are two methods almost all subclasses of Activity will implement:
127 * <li> {@link #onCreate} is where you initialize your activity. Most
128 * importantly, here you will usually call {@link #setContentView(int)}
129 * with a layout resource defining your UI, and using {@link #findViewById}
130 * to retrieve the widgets in that UI that you need to interact with
133 * <li> {@link #onPause} is where you deal with the user leaving your
134 * activity. Most importantly, any changes made by the user should at this
135 * point be committed (usually to the
136 * {@link android.content.ContentProvider} holding the data).
139 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
140 * activity classes must have a corresponding
141 * {@link android.R.styleable#AndroidManifestActivity <activity>}
142 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
144 * <p>Topics covered here:
146 * <li><a href="#Fragments">Fragments</a>
147 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
148 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
149 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
150 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
151 * <li><a href="#Permissions">Permissions</a>
152 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
155 * <div class="special reference">
156 * <h3>Developer Guides</h3>
157 * <p>The Activity class is an important part of an application's overall lifecycle,
158 * and the way activities are launched and put together is a fundamental
159 * part of the platform's application model. For a detailed perspective on the structure of an
160 * Android application and how activities behave, please read the
161 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and
162 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
163 * developer guides.</p>
165 * <p>You can also find a detailed discussion about how to create activities in the
166 * <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a>
167 * developer guide.</p>
170 * <a name="Fragments"></a>
173 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
174 * implementations can make use of the {@link Fragment} class to better
175 * modularize their code, build more sophisticated user interfaces for larger
176 * screens, and help scale their application between small and large screens.
178 * <a name="ActivityLifecycle"></a>
179 * <h3>Activity Lifecycle</h3>
181 * <p>Activities in the system are managed as an <em>activity stack</em>.
182 * When a new activity is started, it is placed on the top of the stack
183 * and becomes the running activity -- the previous activity always remains
184 * below it in the stack, and will not come to the foreground again until
185 * the new activity exits.</p>
187 * <p>An activity has essentially four states:</p>
189 * <li> If an activity in the foreground of the screen (at the top of
191 * it is <em>active</em> or <em>running</em>. </li>
192 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
193 * or transparent activity has focus on top of your activity), it
194 * is <em>paused</em>. A paused activity is completely alive (it
195 * maintains all state and member information and remains attached to
196 * the window manager), but can be killed by the system in extreme
197 * low memory situations.
198 * <li>If an activity is completely obscured by another activity,
199 * it is <em>stopped</em>. It still retains all state and member information,
200 * however, it is no longer visible to the user so its window is hidden
201 * and it will often be killed by the system when memory is needed
203 * <li>If an activity is paused or stopped, the system can drop the activity
204 * from memory by either asking it to finish, or simply killing its
205 * process. When it is displayed again to the user, it must be
206 * completely restarted and restored to its previous state.</li>
209 * <p>The following diagram shows the important state paths of an Activity.
210 * The square rectangles represent callback methods you can implement to
211 * perform operations when the Activity moves between states. The colored
212 * ovals are major states the Activity can be in.</p>
214 * <p><img src="../../../images/activity_lifecycle.png"
215 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
217 * <p>There are three key loops you may be interested in monitoring within your
221 * <li>The <b>entire lifetime</b> of an activity happens between the first call
222 * to {@link android.app.Activity#onCreate} through to a single final call
223 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
224 * of "global" state in onCreate(), and release all remaining resources in
225 * onDestroy(). For example, if it has a thread running in the background
226 * to download data from the network, it may create that thread in onCreate()
227 * and then stop the thread in onDestroy().
229 * <li>The <b>visible lifetime</b> of an activity happens between a call to
230 * {@link android.app.Activity#onStart} until a corresponding call to
231 * {@link android.app.Activity#onStop}. During this time the user can see the
232 * activity on-screen, though it may not be in the foreground and interacting
233 * with the user. Between these two methods you can maintain resources that
234 * are needed to show the activity to the user. For example, you can register
235 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
236 * that impact your UI, and unregister it in onStop() when the user no
237 * longer sees what you are displaying. The onStart() and onStop() methods
238 * can be called multiple times, as the activity becomes visible and hidden
241 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
242 * {@link android.app.Activity#onResume} until a corresponding call to
243 * {@link android.app.Activity#onPause}. During this time the activity is
244 * in front of all other activities and interacting with the user. An activity
245 * can frequently go between the resumed and paused states -- for example when
246 * the device goes to sleep, when an activity result is delivered, when a new
247 * intent is delivered -- so the code in these methods should be fairly
251 * <p>The entire lifecycle of an activity is defined by the following
252 * Activity methods. All of these are hooks that you can override
253 * to do appropriate work when the activity changes state. All
254 * activities will implement {@link android.app.Activity#onCreate}
255 * to do their initial setup; many will also implement
256 * {@link android.app.Activity#onPause} to commit changes to data and
257 * otherwise prepare to stop interacting with the user. You should always
258 * call up to your superclass when implementing these methods.</p>
261 * <pre class="prettyprint">
262 * public class Activity extends ApplicationContext {
263 * protected void onCreate(Bundle savedInstanceState);
265 * protected void onStart();
267 * protected void onRestart();
269 * protected void onResume();
271 * protected void onPause();
273 * protected void onStop();
275 * protected void onDestroy();
279 * <p>In general the movement through an activity's lifecycle looks like
282 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
283 * <colgroup align="left" span="3" />
284 * <colgroup align="left" />
285 * <colgroup align="center" />
286 * <colgroup align="center" />
289 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
293 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
294 * <td>Called when the activity is first created.
295 * This is where you should do all of your normal static set up:
296 * create views, bind data to lists, etc. This method also
297 * provides you with a Bundle containing the activity's previously
298 * frozen state, if there was one.
299 * <p>Always followed by <code>onStart()</code>.</td>
300 * <td align="center">No</td>
301 * <td align="center"><code>onStart()</code></td>
304 * <tr><td rowspan="5" style="border-left: none; border-right: none;"> </td>
305 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
306 * <td>Called after your activity has been stopped, prior to it being
308 * <p>Always followed by <code>onStart()</code></td>
309 * <td align="center">No</td>
310 * <td align="center"><code>onStart()</code></td>
313 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
314 * <td>Called when the activity is becoming visible to the user.
315 * <p>Followed by <code>onResume()</code> if the activity comes
316 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
317 * <td align="center">No</td>
318 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
321 * <tr><td rowspan="2" style="border-left: none;"> </td>
322 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
323 * <td>Called when the activity will start
324 * interacting with the user. At this point your activity is at
325 * the top of the activity stack, with user input going to it.
326 * <p>Always followed by <code>onPause()</code>.</td>
327 * <td align="center">No</td>
328 * <td align="center"><code>onPause()</code></td>
331 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
332 * <td>Called when the system is about to start resuming a previous
333 * activity. This is typically used to commit unsaved changes to
334 * persistent data, stop animations and other things that may be consuming
335 * CPU, etc. Implementations of this method must be very quick because
336 * the next activity will not be resumed until this method returns.
337 * <p>Followed by either <code>onResume()</code> if the activity
338 * returns back to the front, or <code>onStop()</code> if it becomes
339 * invisible to the user.</td>
340 * <td align="center"><font color="#800000"><strong>Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB}</strong></font></td>
341 * <td align="center"><code>onResume()</code> or<br>
342 * <code>onStop()</code></td>
345 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
346 * <td>Called when the activity is no longer visible to the user, because
347 * another activity has been resumed and is covering this one. This
348 * may happen either because a new activity is being started, an existing
349 * one is being brought in front of this one, or this one is being
351 * <p>Followed by either <code>onRestart()</code> if
352 * this activity is coming back to interact with the user, or
353 * <code>onDestroy()</code> if this activity is going away.</td>
354 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
355 * <td align="center"><code>onRestart()</code> or<br>
356 * <code>onDestroy()</code></td>
359 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
360 * <td>The final call you receive before your
361 * activity is destroyed. This can happen either because the
362 * activity is finishing (someone called {@link Activity#finish} on
363 * it, or because the system is temporarily destroying this
364 * instance of the activity to save space. You can distinguish
365 * between these two scenarios with the {@link
366 * Activity#isFinishing} method.</td>
367 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
368 * <td align="center"><em>nothing</em></td>
373 * <p>Note the "Killable" column in the above table -- for those methods that
374 * are marked as being killable, after that method returns the process hosting the
375 * activity may be killed by the system <em>at any time</em> without another line
376 * of its code being executed. Because of this, you should use the
377 * {@link #onPause} method to write any persistent data (such as user edits)
378 * to storage. In addition, the method
379 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
380 * in such a background state, allowing you to save away any dynamic instance
381 * state in your activity into the given Bundle, to be later received in
382 * {@link #onCreate} if the activity needs to be re-created.
383 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
384 * section for more information on how the lifecycle of a process is tied
385 * to the activities it is hosting. Note that it is important to save
386 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
387 * because the latter is not part of the lifecycle callbacks, so will not
388 * be called in every situation as described in its documentation.</p>
390 * <p class="note">Be aware that these semantics will change slightly between
391 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
392 * vs. those targeting prior platforms. Starting with Honeycomb, an application
393 * is not in the killable state until its {@link #onStop} has returned. This
394 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
395 * safely called after {@link #onPause()} and allows and application to safely
396 * wait until {@link #onStop()} to save persistent state.</p>
398 * <p>For those methods that are not marked as being killable, the activity's
399 * process will not be killed by the system starting from the time the method
400 * is called and continuing after it returns. Thus an activity is in the killable
401 * state, for example, between after <code>onPause()</code> to the start of
402 * <code>onResume()</code>.</p>
404 * <a name="ConfigurationChanges"></a>
405 * <h3>Configuration Changes</h3>
407 * <p>If the configuration of the device (as defined by the
408 * {@link Configuration Resources.Configuration} class) changes,
409 * then anything displaying a user interface will need to update to match that
410 * configuration. Because Activity is the primary mechanism for interacting
411 * with the user, it includes special support for handling configuration
414 * <p>Unless you specify otherwise, a configuration change (such as a change
415 * in screen orientation, language, input devices, etc) will cause your
416 * current activity to be <em>destroyed</em>, going through the normal activity
417 * lifecycle process of {@link #onPause},
418 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
419 * had been in the foreground or visible to the user, once {@link #onDestroy} is
420 * called in that instance then a new instance of the activity will be
421 * created, with whatever savedInstanceState the previous instance had generated
422 * from {@link #onSaveInstanceState}.</p>
424 * <p>This is done because any application resource,
425 * including layout files, can change based on any configuration value. Thus
426 * the only safe way to handle a configuration change is to re-retrieve all
427 * resources, including layouts, drawables, and strings. Because activities
428 * must already know how to save their state and re-create themselves from
429 * that state, this is a convenient way to have an activity restart itself
430 * with a new configuration.</p>
432 * <p>In some special cases, you may want to bypass restarting of your
433 * activity based on one or more types of configuration changes. This is
434 * done with the {@link android.R.attr#configChanges android:configChanges}
435 * attribute in its manifest. For any types of configuration changes you say
436 * that you handle there, you will receive a call to your current activity's
437 * {@link #onConfigurationChanged} method instead of being restarted. If
438 * a configuration change involves any that you do not handle, however, the
439 * activity will still be restarted and {@link #onConfigurationChanged}
440 * will not be called.</p>
442 * <a name="StartingActivities"></a>
443 * <h3>Starting Activities and Getting Results</h3>
445 * <p>The {@link android.app.Activity#startActivity}
446 * method is used to start a
447 * new activity, which will be placed at the top of the activity stack. It
448 * takes a single argument, an {@link android.content.Intent Intent},
449 * which describes the activity
450 * to be executed.</p>
452 * <p>Sometimes you want to get a result back from an activity when it
453 * ends. For example, you may start an activity that lets the user pick
454 * a person in a list of contacts; when it ends, it returns the person
455 * that was selected. To do this, you call the
456 * {@link android.app.Activity#startActivityForResult(Intent, int)}
457 * version with a second integer parameter identifying the call. The result
458 * will come back through your {@link android.app.Activity#onActivityResult}
461 * <p>When an activity exits, it can call
462 * {@link android.app.Activity#setResult(int)}
463 * to return data back to its parent. It must always supply a result code,
464 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
465 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
466 * return back an Intent containing any additional data it wants. All of this
467 * information appears back on the
468 * parent's <code>Activity.onActivityResult()</code>, along with the integer
469 * identifier it originally supplied.</p>
471 * <p>If a child activity fails for any reason (such as crashing), the parent
472 * activity will receive a result with the code RESULT_CANCELED.</p>
474 * <pre class="prettyprint">
475 * public class MyActivity extends Activity {
478 * static final int PICK_CONTACT_REQUEST = 0;
480 * public boolean onKeyDown(int keyCode, KeyEvent event) {
481 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
482 * // When the user center presses, let them pick a contact.
483 * startActivityForResult(
484 * new Intent(Intent.ACTION_PICK,
485 * new Uri("content://contacts")),
486 * PICK_CONTACT_REQUEST);
492 * protected void onActivityResult(int requestCode, int resultCode,
494 * if (requestCode == PICK_CONTACT_REQUEST) {
495 * if (resultCode == RESULT_OK) {
496 * // A contact was picked. Here we will just display it
498 * startActivity(new Intent(Intent.ACTION_VIEW, data));
505 * <a name="SavingPersistentState"></a>
506 * <h3>Saving Persistent State</h3>
508 * <p>There are generally two kinds of persistent state than an activity
509 * will deal with: shared document-like data (typically stored in a SQLite
510 * database using a {@linkplain android.content.ContentProvider content provider})
511 * and internal state such as user preferences.</p>
513 * <p>For content provider data, we suggest that activities use a
514 * "edit in place" user model. That is, any edits a user makes are effectively
515 * made immediately without requiring an additional confirmation step.
516 * Supporting this model is generally a simple matter of following two rules:</p>
519 * <li> <p>When creating a new document, the backing database entry or file for
520 * it is created immediately. For example, if the user chooses to write
521 * a new e-mail, a new entry for that e-mail is created as soon as they
522 * start entering data, so that if they go to any other activity after
523 * that point this e-mail will now appear in the list of drafts.</p>
524 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
525 * commit to the backing content provider or file any changes the user
526 * has made. This ensures that those changes will be seen by any other
527 * activity that is about to run. You will probably want to commit
528 * your data even more aggressively at key times during your
529 * activity's lifecycle: for example before starting a new
530 * activity, before finishing your own activity, when the user
531 * switches between input fields, etc.</p>
534 * <p>This model is designed to prevent data loss when a user is navigating
535 * between activities, and allows the system to safely kill an activity (because
536 * system resources are needed somewhere else) at any time after it has been
537 * paused. Note this implies
538 * that the user pressing BACK from your activity does <em>not</em>
539 * mean "cancel" -- it means to leave the activity with its current contents
540 * saved away. Canceling edits in an activity must be provided through
541 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
543 * <p>See the {@linkplain android.content.ContentProvider content package} for
544 * more information about content providers. These are a key aspect of how
545 * different activities invoke and propagate data between themselves.</p>
547 * <p>The Activity class also provides an API for managing internal persistent state
548 * associated with an activity. This can be used, for example, to remember
549 * the user's preferred initial display in a calendar (day view or week view)
550 * or the user's default home page in a web browser.</p>
552 * <p>Activity persistent state is managed
553 * with the method {@link #getPreferences},
554 * allowing you to retrieve and
555 * modify a set of name/value pairs associated with the activity. To use
556 * preferences that are shared across multiple application components
557 * (activities, receivers, services, providers), you can use the underlying
558 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
559 * to retrieve a preferences
560 * object stored under a specific name.
561 * (Note that it is not possible to share settings data across application
562 * packages -- for that you will need a content provider.)</p>
564 * <p>Here is an excerpt from a calendar activity that stores the user's
565 * preferred view mode in its persistent settings:</p>
567 * <pre class="prettyprint">
568 * public class CalendarActivity extends Activity {
571 * static final int DAY_VIEW_MODE = 0;
572 * static final int WEEK_VIEW_MODE = 1;
574 * private SharedPreferences mPrefs;
575 * private int mCurViewMode;
577 * protected void onCreate(Bundle savedInstanceState) {
578 * super.onCreate(savedInstanceState);
580 * SharedPreferences mPrefs = getSharedPreferences();
581 * mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
584 * protected void onPause() {
587 * SharedPreferences.Editor ed = mPrefs.edit();
588 * ed.putInt("view_mode", mCurViewMode);
594 * <a name="Permissions"></a>
595 * <h3>Permissions</h3>
597 * <p>The ability to start a particular Activity can be enforced when it is
599 * manifest's {@link android.R.styleable#AndroidManifestActivity <activity>}
600 * tag. By doing so, other applications will need to declare a corresponding
601 * {@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>}
602 * element in their own manifest to be able to start that activity.
604 * <p>When starting an Activity you can set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
605 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
606 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the
607 * Activity access to the specific URIs in the Intent. Access will remain
608 * until the Activity has finished (it will remain across the hosting
609 * process being killed and other temporary destruction). As of
610 * {@link android.os.Build.VERSION_CODES#GINGERBREAD}, if the Activity
611 * was already created and a new Intent is being delivered to
612 * {@link #onNewIntent(Intent)}, any newly granted URI permissions will be added
613 * to the existing ones it holds.
615 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
616 * document for more information on permissions and security in general.
618 * <a name="ProcessLifecycle"></a>
619 * <h3>Process Lifecycle</h3>
621 * <p>The Android system attempts to keep application process around for as
622 * long as possible, but eventually will need to remove old processes when
623 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
624 * Lifecycle</a>, the decision about which process to remove is intimately
625 * tied to the state of the user's interaction with it. In general, there
626 * are four states a process can be in based on the activities running in it,
627 * listed here in order of importance. The system will kill less important
628 * processes (the last ones) before it resorts to killing more important
629 * processes (the first ones).
632 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
633 * that the user is currently interacting with) is considered the most important.
634 * Its process will only be killed as a last resort, if it uses more memory
635 * than is available on the device. Generally at this point the device has
636 * reached a memory paging state, so this is required in order to keep the user
637 * interface responsive.
638 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
639 * but not in the foreground, such as one sitting behind a foreground dialog)
640 * is considered extremely important and will not be killed unless that is
641 * required to keep the foreground activity running.
642 * <li> <p>A <b>background activity</b> (an activity that is not visible to
643 * the user and has been paused) is no longer critical, so the system may
644 * safely kill its process to reclaim memory for other foreground or
645 * visible processes. If its process needs to be killed, when the user navigates
646 * back to the activity (making it visible on the screen again), its
647 * {@link #onCreate} method will be called with the savedInstanceState it had previously
648 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
649 * state as the user last left it.
650 * <li> <p>An <b>empty process</b> is one hosting no activities or other
651 * application components (such as {@link Service} or
652 * {@link android.content.BroadcastReceiver} classes). These are killed very
653 * quickly by the system as memory becomes low. For this reason, any
654 * background operation you do outside of an activity must be executed in the
655 * context of an activity BroadcastReceiver or Service to ensure that the system
656 * knows it needs to keep your process around.
659 * <p>Sometimes an Activity may need to do a long-running operation that exists
660 * independently of the activity lifecycle itself. An example may be a camera
661 * application that allows you to upload a picture to a web site. The upload
662 * may take a long time, and the application should allow the user to leave
663 * the application will it is executing. To accomplish this, your Activity
664 * should start a {@link Service} in which the upload takes place. This allows
665 * the system to properly prioritize your process (considering it to be more
666 * important than other non-visible applications) for the duration of the
667 * upload, independent of whether the original activity is paused, stopped,
670 public class Activity extends ContextThemeWrapper
671 implements LayoutInflater.Factory2,
672 Window.Callback, KeyEvent.Callback,
673 OnCreateContextMenuListener, ComponentCallbacks2,
674 Window.OnWindowDismissedCallback {
675 private static final String TAG = "Activity";
676 private static final boolean DEBUG_LIFECYCLE = false;
678 /** Standard activity result: operation canceled. */
679 public static final int RESULT_CANCELED = 0;
680 /** Standard activity result: operation succeeded. */
681 public static final int RESULT_OK = -1;
682 /** Start of user-defined activity results. */
683 public static final int RESULT_FIRST_USER = 1;
685 static final String FRAGMENTS_TAG = "android:fragments";
687 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
688 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
689 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
690 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
691 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
692 private static final String HAS_CURENT_PERMISSIONS_REQUEST_KEY =
693 "android:hasCurrentPermissionsRequest";
695 private static final String REQUEST_PERMISSIONS_WHO_PREFIX = "@android:requestPermissions:";
697 private static class ManagedDialog {
701 private SparseArray<ManagedDialog> mManagedDialogs;
703 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
704 private Instrumentation mInstrumentation;
705 private IBinder mToken;
707 /*package*/ String mEmbeddedID;
708 private Application mApplication;
709 /*package*/ Intent mIntent;
710 /*package*/ String mReferrer;
711 private ComponentName mComponent;
712 /*package*/ ActivityInfo mActivityInfo;
713 /*package*/ ActivityThread mMainThread;
716 /*package*/ boolean mResumed;
717 private boolean mStopped;
719 boolean mStartedActivity;
720 private boolean mDestroyed;
721 private boolean mDoReportFullyDrawn = true;
722 /** true if the activity is going through a transient pause */
723 /*package*/ boolean mTemporaryPause = false;
724 /** true if the activity is being destroyed in order to recreate it with a new configuration */
725 /*package*/ boolean mChangingConfigurations = false;
726 /*package*/ int mConfigChangeFlags;
727 /*package*/ Configuration mCurrentConfig;
728 private SearchManager mSearchManager;
729 private MenuInflater mMenuInflater;
731 static final class NonConfigurationInstances {
733 HashMap<String, Object> children;
734 List<Fragment> fragments;
735 ArrayMap<String, LoaderManager> loaders;
736 VoiceInteractor voiceInteractor;
738 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
740 private Window mWindow;
742 private WindowManager mWindowManager;
743 /*package*/ View mDecor = null;
744 /*package*/ boolean mWindowAdded = false;
745 /*package*/ boolean mVisibleFromServer = false;
746 /*package*/ boolean mVisibleFromClient = true;
747 /*package*/ ActionBar mActionBar = null;
748 private boolean mEnableDefaultActionBarUp;
750 private VoiceInteractor mVoiceInteractor;
752 private CharSequence mTitle;
753 private int mTitleColor = 0;
755 // we must have a handler before the FragmentController is constructed
756 final Handler mHandler = new Handler();
757 final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
759 // Most recent call to requestVisibleBehind().
760 boolean mVisibleBehind;
762 private static final class ManagedCursor {
763 ManagedCursor(Cursor cursor) {
769 private final Cursor mCursor;
770 private boolean mReleased;
771 private boolean mUpdated;
773 private final ArrayList<ManagedCursor> mManagedCursors =
774 new ArrayList<ManagedCursor>();
776 // protected by synchronized (this)
777 int mResultCode = RESULT_CANCELED;
778 Intent mResultData = null;
780 private TranslucentConversionListener mTranslucentCallback;
781 private boolean mChangeCanvasToTranslucent;
783 private SearchEvent mSearchEvent;
785 private boolean mTitleReady = false;
786 private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
788 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
789 private SpannableStringBuilder mDefaultKeySsb = null;
791 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
793 @SuppressWarnings("unused")
794 private final Object mInstanceTracker = StrictMode.trackActivity(this);
796 private Thread mUiThread;
798 ActivityTransitionState mActivityTransitionState = new ActivityTransitionState();
799 SharedElementCallback mEnterTransitionListener = SharedElementCallback.NULL_CALLBACK;
800 SharedElementCallback mExitTransitionListener = SharedElementCallback.NULL_CALLBACK;
802 private boolean mHasCurrentPermissionsRequest;
804 /** Return the intent that started this activity. */
805 public Intent getIntent() {
810 * Change the intent returned by {@link #getIntent}. This holds a
811 * reference to the given intent; it does not copy it. Often used in
812 * conjunction with {@link #onNewIntent}.
814 * @param newIntent The new Intent object to return from getIntent
819 public void setIntent(Intent newIntent) {
823 /** Return the application that owns this activity. */
824 public final Application getApplication() {
828 /** Is this activity embedded inside of another activity? */
829 public final boolean isChild() {
830 return mParent != null;
833 /** Return the parent activity if this view is an embedded child. */
834 public final Activity getParent() {
838 /** Retrieve the window manager for showing custom windows. */
839 public WindowManager getWindowManager() {
840 return mWindowManager;
844 * Retrieve the current {@link android.view.Window} for the activity.
845 * This can be used to directly access parts of the Window API that
846 * are not available through Activity/Screen.
848 * @return Window The current window, or null if the activity is not
851 public Window getWindow() {
856 * Return the LoaderManager for this activity, creating it if needed.
858 public LoaderManager getLoaderManager() {
859 return mFragments.getLoaderManager();
863 * Calls {@link android.view.Window#getCurrentFocus} on the
864 * Window of this Activity to return the currently focused view.
866 * @return View The current View with focus or null.
869 * @see android.view.Window#getCurrentFocus
872 public View getCurrentFocus() {
873 return mWindow != null ? mWindow.getCurrentFocus() : null;
877 * Called when the activity is starting. This is where most initialization
878 * should go: calling {@link #setContentView(int)} to inflate the
879 * activity's UI, using {@link #findViewById} to programmatically interact
880 * with widgets in the UI, calling
881 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
882 * cursors for data being displayed, etc.
884 * <p>You can call {@link #finish} from within this function, in
885 * which case onDestroy() will be immediately called without any of the rest
886 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
887 * {@link #onPause}, etc) executing.
889 * <p><em>Derived classes must call through to the super class's
890 * implementation of this method. If they do not, an exception will be
893 * @param savedInstanceState If the activity is being re-initialized after
894 * previously being shut down then this Bundle contains the data it most
895 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
898 * @see #onSaveInstanceState
899 * @see #onRestoreInstanceState
904 protected void onCreate(@Nullable Bundle savedInstanceState) {
905 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
906 if (mLastNonConfigurationInstances != null) {
907 mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
909 if (mActivityInfo.parentActivityName != null) {
910 if (mActionBar == null) {
911 mEnableDefaultActionBarUp = true;
913 mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
916 if (savedInstanceState != null) {
917 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
918 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
919 ? mLastNonConfigurationInstances.fragments : null);
921 mFragments.dispatchCreate();
922 getApplication().dispatchActivityCreated(this, savedInstanceState);
923 if (mVoiceInteractor != null) {
924 mVoiceInteractor.attachActivity(this);
930 * Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
931 * the attribute {@link android.R.attr#persistableMode} set to
932 * <code>persistAcrossReboots</code>.
934 * @param savedInstanceState if the activity is being re-initialized after
935 * previously being shut down then this Bundle contains the data it most
936 * recently supplied in {@link #onSaveInstanceState}.
937 * <b><i>Note: Otherwise it is null.</i></b>
938 * @param persistentState if the activity is being re-initialized after
939 * previously being shut down or powered off then this Bundle contains the data it most
940 * recently supplied to outPersistentState in {@link #onSaveInstanceState}.
941 * <b><i>Note: Otherwise it is null.</i></b>
943 * @see #onCreate(android.os.Bundle)
945 * @see #onSaveInstanceState
946 * @see #onRestoreInstanceState
949 public void onCreate(@Nullable Bundle savedInstanceState,
950 @Nullable PersistableBundle persistentState) {
951 onCreate(savedInstanceState);
955 * The hook for {@link ActivityThread} to restore the state of this activity.
957 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
958 * {@link #restoreManagedDialogs(android.os.Bundle)}.
960 * @param savedInstanceState contains the saved state
962 final void performRestoreInstanceState(Bundle savedInstanceState) {
963 onRestoreInstanceState(savedInstanceState);
964 restoreManagedDialogs(savedInstanceState);
968 * The hook for {@link ActivityThread} to restore the state of this activity.
970 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
971 * {@link #restoreManagedDialogs(android.os.Bundle)}.
973 * @param savedInstanceState contains the saved state
974 * @param persistentState contains the persistable saved state
976 final void performRestoreInstanceState(Bundle savedInstanceState,
977 PersistableBundle persistentState) {
978 onRestoreInstanceState(savedInstanceState, persistentState);
979 if (savedInstanceState != null) {
980 restoreManagedDialogs(savedInstanceState);
985 * This method is called after {@link #onStart} when the activity is
986 * being re-initialized from a previously saved state, given here in
987 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
988 * to restore their state, but it is sometimes convenient to do it here
989 * after all of the initialization has been done or to allow subclasses to
990 * decide whether to use your default implementation. The default
991 * implementation of this method performs a restore of any view state that
992 * had previously been frozen by {@link #onSaveInstanceState}.
994 * <p>This method is called between {@link #onStart} and
995 * {@link #onPostCreate}.
997 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1000 * @see #onPostCreate
1002 * @see #onSaveInstanceState
1004 protected void onRestoreInstanceState(Bundle savedInstanceState) {
1005 if (mWindow != null) {
1006 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
1007 if (windowState != null) {
1008 mWindow.restoreHierarchyState(windowState);
1014 * This is the same as {@link #onRestoreInstanceState(Bundle)} but is called for activities
1015 * created with the attribute {@link android.R.attr#persistableMode} set to
1016 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1017 * came from the restored PersistableBundle first
1018 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1020 * <p>This method is called between {@link #onStart} and
1021 * {@link #onPostCreate}.
1023 * <p>If this method is called {@link #onRestoreInstanceState(Bundle)} will not be called.
1025 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1026 * @param persistentState the data most recently supplied in {@link #onSaveInstanceState}.
1028 * @see #onRestoreInstanceState(Bundle)
1030 * @see #onPostCreate
1032 * @see #onSaveInstanceState
1034 public void onRestoreInstanceState(Bundle savedInstanceState,
1035 PersistableBundle persistentState) {
1036 if (savedInstanceState != null) {
1037 onRestoreInstanceState(savedInstanceState);
1042 * Restore the state of any saved managed dialogs.
1044 * @param savedInstanceState The bundle to restore from.
1046 private void restoreManagedDialogs(Bundle savedInstanceState) {
1047 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
1052 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
1053 final int numDialogs = ids.length;
1054 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
1055 for (int i = 0; i < numDialogs; i++) {
1056 final Integer dialogId = ids[i];
1057 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
1058 if (dialogState != null) {
1059 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
1060 // so tell createDialog() not to do it, otherwise we get an exception
1061 final ManagedDialog md = new ManagedDialog();
1062 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
1063 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
1064 if (md.mDialog != null) {
1065 mManagedDialogs.put(dialogId, md);
1066 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
1067 md.mDialog.onRestoreInstanceState(dialogState);
1073 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
1074 final Dialog dialog = onCreateDialog(dialogId, args);
1075 if (dialog == null) {
1078 dialog.dispatchOnCreate(state);
1082 private static String savedDialogKeyFor(int key) {
1083 return SAVED_DIALOG_KEY_PREFIX + key;
1086 private static String savedDialogArgsKeyFor(int key) {
1087 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
1091 * Called when activity start-up is complete (after {@link #onStart}
1092 * and {@link #onRestoreInstanceState} have been called). Applications will
1093 * generally not implement this method; it is intended for system
1094 * classes to do final initialization after application code has run.
1096 * <p><em>Derived classes must call through to the super class's
1097 * implementation of this method. If they do not, an exception will be
1100 * @param savedInstanceState If the activity is being re-initialized after
1101 * previously being shut down then this Bundle contains the data it most
1102 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
1106 protected void onPostCreate(@Nullable Bundle savedInstanceState) {
1109 onTitleChanged(getTitle(), getTitleColor());
1115 * This is the same as {@link #onPostCreate(Bundle)} but is called for activities
1116 * created with the attribute {@link android.R.attr#persistableMode} set to
1117 * <code>persistAcrossReboots</code>.
1119 * @param savedInstanceState The data most recently supplied in {@link #onSaveInstanceState}
1120 * @param persistentState The data caming from the PersistableBundle first
1121 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1125 public void onPostCreate(@Nullable Bundle savedInstanceState,
1126 @Nullable PersistableBundle persistentState) {
1127 onPostCreate(savedInstanceState);
1131 * Called after {@link #onCreate} — or after {@link #onRestart} when
1132 * the activity had been stopped, but is now again being displayed to the
1133 * user. It will be followed by {@link #onResume}.
1135 * <p><em>Derived classes must call through to the super class's
1136 * implementation of this method. If they do not, an exception will be
1144 protected void onStart() {
1145 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
1148 mFragments.doLoaderStart();
1150 getApplication().dispatchActivityStarted(this);
1154 * Called after {@link #onStop} when the current activity is being
1155 * re-displayed to the user (the user has navigated back to it). It will
1156 * be followed by {@link #onStart} and then {@link #onResume}.
1158 * <p>For activities that are using raw {@link Cursor} objects (instead of
1159 * creating them through
1160 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1161 * this is usually the place
1162 * where the cursor should be requeried (because you had deactivated it in
1165 * <p><em>Derived classes must call through to the super class's
1166 * implementation of this method. If they do not, an exception will be
1174 protected void onRestart() {
1179 * Called when an {@link #onResume} is coming up, prior to other pre-resume callbacks
1180 * such as {@link #onNewIntent} and {@link #onActivityResult}. This is primarily intended
1181 * to give the activity a hint that its state is no longer saved -- it will generally
1182 * be called after {@link #onSaveInstanceState} and prior to the activity being
1183 * resumed/started again.
1185 public void onStateNotSaved() {
1189 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1190 * {@link #onPause}, for your activity to start interacting with the user.
1191 * This is a good place to begin animations, open exclusive-access devices
1192 * (such as the camera), etc.
1194 * <p>Keep in mind that onResume is not the best indicator that your activity
1195 * is visible to the user; a system window such as the keyguard may be in
1196 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1197 * activity is visible to the user (for example, to resume a game).
1199 * <p><em>Derived classes must call through to the super class's
1200 * implementation of this method. If they do not, an exception will be
1203 * @see #onRestoreInstanceState
1205 * @see #onPostResume
1209 protected void onResume() {
1210 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this);
1211 getApplication().dispatchActivityResumed(this);
1212 mActivityTransitionState.onResume();
1217 * Called when activity resume is complete (after {@link #onResume} has
1218 * been called). Applications will generally not implement this method;
1219 * it is intended for system classes to do final setup after application
1220 * resume code has run.
1222 * <p><em>Derived classes must call through to the super class's
1223 * implementation of this method. If they do not, an exception will be
1229 protected void onPostResume() {
1230 final Window win = getWindow();
1231 if (win != null) win.makeActive();
1232 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
1237 * Check whether this activity is running as part of a voice interaction with the user.
1238 * If true, it should perform its interaction with the user through the
1239 * {@link VoiceInteractor} returned by {@link #getVoiceInteractor}.
1241 public boolean isVoiceInteraction() {
1242 return mVoiceInteractor != null;
1246 * Like {@link #isVoiceInteraction}, but only returns true if this is also the root
1247 * of a voice interaction. That is, returns true if this activity was directly
1248 * started by the voice interaction service as the initiation of a voice interaction.
1249 * Otherwise, for example if it was started by another activity while under voice
1250 * interaction, returns false.
1252 public boolean isVoiceInteractionRoot() {
1254 return mVoiceInteractor != null
1255 && ActivityManagerNative.getDefault().isRootVoiceInteraction(mToken);
1256 } catch (RemoteException e) {
1262 * Retrieve the active {@link VoiceInteractor} that the user is going through to
1263 * interact with this activity.
1265 public VoiceInteractor getVoiceInteractor() {
1266 return mVoiceInteractor;
1270 * This is called for activities that set launchMode to "singleTop" in
1271 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1272 * flag when calling {@link #startActivity}. In either case, when the
1273 * activity is re-launched while at the top of the activity stack instead
1274 * of a new instance of the activity being started, onNewIntent() will be
1275 * called on the existing instance with the Intent that was used to
1278 * <p>An activity will always be paused before receiving a new intent, so
1279 * you can count on {@link #onResume} being called after this method.
1281 * <p>Note that {@link #getIntent} still returns the original Intent. You
1282 * can use {@link #setIntent} to update it to this new Intent.
1284 * @param intent The new intent that was started for the activity.
1290 protected void onNewIntent(Intent intent) {
1294 * The hook for {@link ActivityThread} to save the state of this activity.
1296 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1297 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1299 * @param outState The bundle to save the state to.
1301 final void performSaveInstanceState(Bundle outState) {
1302 onSaveInstanceState(outState);
1303 saveManagedDialogs(outState);
1304 mActivityTransitionState.saveState(outState);
1305 storeHasCurrentPermissionRequest(outState);
1306 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState);
1310 * The hook for {@link ActivityThread} to save the state of this activity.
1312 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1313 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1315 * @param outState The bundle to save the state to.
1316 * @param outPersistentState The bundle to save persistent state to.
1318 final void performSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1319 onSaveInstanceState(outState, outPersistentState);
1320 saveManagedDialogs(outState);
1321 storeHasCurrentPermissionRequest(outState);
1322 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState +
1323 ", " + outPersistentState);
1327 * Called to retrieve per-instance state from an activity before being killed
1328 * so that the state can be restored in {@link #onCreate} or
1329 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1330 * will be passed to both).
1332 * <p>This method is called before an activity may be killed so that when it
1333 * comes back some time in the future it can restore its state. For example,
1334 * if activity B is launched in front of activity A, and at some point activity
1335 * A is killed to reclaim resources, activity A will have a chance to save the
1336 * current state of its user interface via this method so that when the user
1337 * returns to activity A, the state of the user interface can be restored
1338 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1340 * <p>Do not confuse this method with activity lifecycle callbacks such as
1341 * {@link #onPause}, which is always called when an activity is being placed
1342 * in the background or on its way to destruction, or {@link #onStop} which
1343 * is called before destruction. One example of when {@link #onPause} and
1344 * {@link #onStop} is called and not this method is when a user navigates back
1345 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1346 * on B because that particular instance will never be restored, so the
1347 * system avoids calling it. An example when {@link #onPause} is called and
1348 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1349 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1350 * killed during the lifetime of B since the state of the user interface of
1351 * A will stay intact.
1353 * <p>The default implementation takes care of most of the UI per-instance
1354 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1355 * view in the hierarchy that has an id, and by saving the id of the currently
1356 * focused view (all of which is restored by the default implementation of
1357 * {@link #onRestoreInstanceState}). If you override this method to save additional
1358 * information not captured by each individual view, you will likely want to
1359 * call through to the default implementation, otherwise be prepared to save
1360 * all of the state of each view yourself.
1362 * <p>If called, this method will occur before {@link #onStop}. There are
1363 * no guarantees about whether it will occur before or after {@link #onPause}.
1365 * @param outState Bundle in which to place your saved state.
1368 * @see #onRestoreInstanceState
1371 protected void onSaveInstanceState(Bundle outState) {
1372 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
1373 Parcelable p = mFragments.saveAllState();
1375 outState.putParcelable(FRAGMENTS_TAG, p);
1377 getApplication().dispatchActivitySaveInstanceState(this, outState);
1381 * This is the same as {@link #onSaveInstanceState} but is called for activities
1382 * created with the attribute {@link android.R.attr#persistableMode} set to
1383 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1384 * in will be saved and presented in {@link #onCreate(Bundle, PersistableBundle)}
1385 * the first time that this activity is restarted following the next device reboot.
1387 * @param outState Bundle in which to place your saved state.
1388 * @param outPersistentState State which will be saved across reboots.
1390 * @see #onSaveInstanceState(Bundle)
1392 * @see #onRestoreInstanceState(Bundle, PersistableBundle)
1395 public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1396 onSaveInstanceState(outState);
1400 * Save the state of any managed dialogs.
1402 * @param outState place to store the saved state.
1404 private void saveManagedDialogs(Bundle outState) {
1405 if (mManagedDialogs == null) {
1409 final int numDialogs = mManagedDialogs.size();
1410 if (numDialogs == 0) {
1414 Bundle dialogState = new Bundle();
1416 int[] ids = new int[mManagedDialogs.size()];
1418 // save each dialog's bundle, gather the ids
1419 for (int i = 0; i < numDialogs; i++) {
1420 final int key = mManagedDialogs.keyAt(i);
1422 final ManagedDialog md = mManagedDialogs.valueAt(i);
1423 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1424 if (md.mArgs != null) {
1425 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1429 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1430 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1435 * Called as part of the activity lifecycle when an activity is going into
1436 * the background, but has not (yet) been killed. The counterpart to
1437 * {@link #onResume}.
1439 * <p>When activity B is launched in front of activity A, this callback will
1440 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1441 * so be sure to not do anything lengthy here.
1443 * <p>This callback is mostly used for saving any persistent state the
1444 * activity is editing, to present a "edit in place" model to the user and
1445 * making sure nothing is lost if there are not enough resources to start
1446 * the new activity without first killing this one. This is also a good
1447 * place to do things like stop animations and other things that consume a
1448 * noticeable amount of CPU in order to make the switch to the next activity
1449 * as fast as possible, or to close resources that are exclusive access
1450 * such as the camera.
1452 * <p>In situations where the system needs more memory it may kill paused
1453 * processes to reclaim resources. Because of this, you should be sure
1454 * that all of your state is saved by the time you return from
1455 * this function. In general {@link #onSaveInstanceState} is used to save
1456 * per-instance state in the activity and this method is used to store
1457 * global persistent data (in content providers, files, etc.)
1459 * <p>After receiving this call you will usually receive a following call
1460 * to {@link #onStop} (after the next activity has been resumed and
1461 * displayed), however in some cases there will be a direct call back to
1462 * {@link #onResume} without going through the stopped state.
1464 * <p><em>Derived classes must call through to the super class's
1465 * implementation of this method. If they do not, an exception will be
1469 * @see #onSaveInstanceState
1473 protected void onPause() {
1474 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this);
1475 getApplication().dispatchActivityPaused(this);
1480 * Called as part of the activity lifecycle when an activity is about to go
1481 * into the background as the result of user choice. For example, when the
1482 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1483 * when an incoming phone call causes the in-call Activity to be automatically
1484 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1485 * the activity being interrupted. In cases when it is invoked, this method
1486 * is called right before the activity's {@link #onPause} callback.
1488 * <p>This callback and {@link #onUserInteraction} are intended to help
1489 * activities manage status bar notifications intelligently; specifically,
1490 * for helping activities determine the proper time to cancel a notfication.
1492 * @see #onUserInteraction()
1494 protected void onUserLeaveHint() {
1498 * Generate a new thumbnail for this activity. This method is called before
1499 * pausing the activity, and should draw into <var>outBitmap</var> the
1500 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1501 * can use the given <var>canvas</var>, which is configured to draw into the
1502 * bitmap, for rendering if desired.
1504 * <p>The default implementation returns fails and does not draw a thumbnail;
1505 * this will result in the platform creating its own thumbnail if needed.
1507 * @param outBitmap The bitmap to contain the thumbnail.
1508 * @param canvas Can be used to render into the bitmap.
1510 * @return Return true if you have drawn into the bitmap; otherwise after
1511 * you return it will be filled with a default thumbnail.
1513 * @see #onCreateDescription
1514 * @see #onSaveInstanceState
1517 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
1522 * Generate a new description for this activity. This method is called
1523 * before pausing the activity and can, if desired, return some textual
1524 * description of its current state to be displayed to the user.
1526 * <p>The default implementation returns null, which will cause you to
1527 * inherit the description from the previous activity. If all activities
1528 * return null, generally the label of the top activity will be used as the
1531 * @return A description of what the user is doing. It should be short and
1532 * sweet (only a few words).
1534 * @see #onCreateThumbnail
1535 * @see #onSaveInstanceState
1539 public CharSequence onCreateDescription() {
1544 * This is called when the user is requesting an assist, to build a full
1545 * {@link Intent#ACTION_ASSIST} Intent with all of the context of the current
1546 * application. You can override this method to place into the bundle anything
1547 * you would like to appear in the {@link Intent#EXTRA_ASSIST_CONTEXT} part
1548 * of the assist Intent.
1550 * <p>This function will be called after any global assist callbacks that had
1551 * been registered with {@link Application#registerOnProvideAssistDataListener
1552 * Application.registerOnProvideAssistDataListener}.
1554 public void onProvideAssistData(Bundle data) {
1558 * This is called when the user is requesting an assist, to provide references
1559 * to content related to the current activity. Before being called, the
1560 * {@code outContent} Intent is filled with the base Intent of the activity (the Intent
1561 * returned by {@link #getIntent()}). The Intent's extras are stripped of any types
1562 * that are not valid for {@link PersistableBundle} or non-framework Parcelables, and
1563 * the flags {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} and
1564 * {@link Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION} are cleared from the Intent.
1566 * <p>Custom implementation may adjust the content intent to better reflect the top-level
1567 * context of the activity, and fill in its ClipData with additional content of
1568 * interest that the user is currently viewing. For example, an image gallery application
1569 * that has launched in to an activity allowing the user to swipe through pictures should
1570 * modify the intent to reference the current image they are looking it; such an
1571 * application when showing a list of pictures should add a ClipData that has
1572 * references to all of the pictures currently visible on screen.</p>
1574 * @param outContent The assist content to return.
1576 public void onProvideAssistContent(AssistContent outContent) {
1580 * Ask to have the current assistant shown to the user. This only works if the calling
1581 * activity is the current foreground activity. It is the same as calling
1582 * {@link android.service.voice.VoiceInteractionService#showSession
1583 * VoiceInteractionService.showSession} and requesting all of the possible context.
1584 * The receiver will always see
1585 * {@link android.service.voice.VoiceInteractionSession#SHOW_SOURCE_APPLICATION} set.
1586 * @return Returns true if the assistant was successfully invoked, else false. For example
1587 * false will be returned if the caller is not the current top activity.
1589 public boolean showAssist(Bundle args) {
1591 return ActivityManagerNative.getDefault().showAssistFromActivity(mToken, args);
1592 } catch (RemoteException e) {
1598 * Called when you are no longer visible to the user. You will next
1599 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1600 * depending on later user activity.
1602 * <p>Note that this method may never be called, in low memory situations
1603 * where the system does not have enough memory to keep your activity's
1604 * process running after its {@link #onPause} method is called.
1606 * <p><em>Derived classes must call through to the super class's
1607 * implementation of this method. If they do not, an exception will be
1612 * @see #onSaveInstanceState
1616 protected void onStop() {
1617 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
1618 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
1619 mActivityTransitionState.onStop();
1620 getApplication().dispatchActivityStopped(this);
1621 mTranslucentCallback = null;
1626 * Perform any final cleanup before an activity is destroyed. This can
1627 * happen either because the activity is finishing (someone called
1628 * {@link #finish} on it, or because the system is temporarily destroying
1629 * this instance of the activity to save space. You can distinguish
1630 * between these two scenarios with the {@link #isFinishing} method.
1632 * <p><em>Note: do not count on this method being called as a place for
1633 * saving data! For example, if an activity is editing data in a content
1634 * provider, those edits should be committed in either {@link #onPause} or
1635 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1636 * free resources like threads that are associated with an activity, so
1637 * that a destroyed activity does not leave such things around while the
1638 * rest of its application is still running. There are situations where
1639 * the system will simply kill the activity's hosting process without
1640 * calling this method (or any others) in it, so it should not be used to
1641 * do things that are intended to remain around after the process goes
1644 * <p><em>Derived classes must call through to the super class's
1645 * implementation of this method. If they do not, an exception will be
1654 protected void onDestroy() {
1655 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
1658 // dismiss any dialogs we are managing.
1659 if (mManagedDialogs != null) {
1660 final int numDialogs = mManagedDialogs.size();
1661 for (int i = 0; i < numDialogs; i++) {
1662 final ManagedDialog md = mManagedDialogs.valueAt(i);
1663 if (md.mDialog.isShowing()) {
1664 md.mDialog.dismiss();
1667 mManagedDialogs = null;
1670 // close any cursors we are managing.
1671 synchronized (mManagedCursors) {
1672 int numCursors = mManagedCursors.size();
1673 for (int i = 0; i < numCursors; i++) {
1674 ManagedCursor c = mManagedCursors.get(i);
1679 mManagedCursors.clear();
1682 // Close any open search dialog
1683 if (mSearchManager != null) {
1684 mSearchManager.stopSearch();
1687 getApplication().dispatchActivityDestroyed(this);
1691 * Report to the system that your app is now fully drawn, purely for diagnostic
1692 * purposes (calling it does not impact the visible behavior of the activity).
1693 * This is only used to help instrument application launch times, so that the
1694 * app can report when it is fully in a usable state; without this, the only thing
1695 * the system itself can determine is the point at which the activity's window
1696 * is <em>first</em> drawn and displayed. To participate in app launch time
1697 * measurement, you should always call this method after first launch (when
1698 * {@link #onCreate(android.os.Bundle)} is called), at the point where you have
1699 * entirely drawn your UI and populated with all of the significant data. You
1700 * can safely call this method any time after first launch as well, in which case
1701 * it will simply be ignored.
1703 public void reportFullyDrawn() {
1704 if (mDoReportFullyDrawn) {
1705 mDoReportFullyDrawn = false;
1707 ActivityManagerNative.getDefault().reportActivityFullyDrawn(mToken);
1708 } catch (RemoteException e) {
1714 * Called by the system when the device configuration changes while your
1715 * activity is running. Note that this will <em>only</em> be called if
1716 * you have selected configurations you would like to handle with the
1717 * {@link android.R.attr#configChanges} attribute in your manifest. If
1718 * any configuration change occurs that is not selected to be reported
1719 * by that attribute, then instead of reporting it the system will stop
1720 * and restart the activity (to have it launched with the new
1723 * <p>At the time that this function has been called, your Resources
1724 * object will have been updated to return resource values matching the
1725 * new configuration.
1727 * @param newConfig The new device configuration.
1729 public void onConfigurationChanged(Configuration newConfig) {
1730 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onConfigurationChanged " + this + ": " + newConfig);
1733 mFragments.dispatchConfigurationChanged(newConfig);
1735 if (mWindow != null) {
1736 // Pass the configuration changed event to the window
1737 mWindow.onConfigurationChanged(newConfig);
1740 if (mActionBar != null) {
1741 // Do this last; the action bar will need to access
1742 // view changes from above.
1743 mActionBar.onConfigurationChanged(newConfig);
1748 * If this activity is being destroyed because it can not handle a
1749 * configuration parameter being changed (and thus its
1750 * {@link #onConfigurationChanged(Configuration)} method is
1751 * <em>not</em> being called), then you can use this method to discover
1752 * the set of changes that have occurred while in the process of being
1753 * destroyed. Note that there is no guarantee that these will be
1754 * accurate (other changes could have happened at any time), so you should
1755 * only use this as an optimization hint.
1757 * @return Returns a bit field of the configuration parameters that are
1758 * changing, as defined by the {@link android.content.res.Configuration}
1761 public int getChangingConfigurations() {
1762 return mConfigChangeFlags;
1766 * Retrieve the non-configuration instance data that was previously
1767 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1768 * be available from the initial {@link #onCreate} and
1769 * {@link #onStart} calls to the new instance, allowing you to extract
1770 * any useful dynamic state from the previous instance.
1772 * <p>Note that the data you retrieve here should <em>only</em> be used
1773 * as an optimization for handling configuration changes. You should always
1774 * be able to handle getting a null pointer back, and an activity must
1775 * still be able to restore itself to its previous state (through the
1776 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1777 * function returns null.
1779 * @return Returns the object previously returned by
1780 * {@link #onRetainNonConfigurationInstance()}.
1782 * @deprecated Use the new {@link Fragment} API
1783 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
1784 * available on older platforms through the Android compatibility package.
1788 public Object getLastNonConfigurationInstance() {
1789 return mLastNonConfigurationInstances != null
1790 ? mLastNonConfigurationInstances.activity : null;
1794 * Called by the system, as part of destroying an
1795 * activity due to a configuration change, when it is known that a new
1796 * instance will immediately be created for the new configuration. You
1797 * can return any object you like here, including the activity instance
1798 * itself, which can later be retrieved by calling
1799 * {@link #getLastNonConfigurationInstance()} in the new activity
1802 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1803 * or later, consider instead using a {@link Fragment} with
1804 * {@link Fragment#setRetainInstance(boolean)
1805 * Fragment.setRetainInstance(boolean}.</em>
1807 * <p>This function is called purely as an optimization, and you must
1808 * not rely on it being called. When it is called, a number of guarantees
1809 * will be made to help optimize configuration switching:
1811 * <li> The function will be called between {@link #onStop} and
1812 * {@link #onDestroy}.
1813 * <li> A new instance of the activity will <em>always</em> be immediately
1814 * created after this one's {@link #onDestroy()} is called. In particular,
1815 * <em>no</em> messages will be dispatched during this time (when the returned
1816 * object does not have an activity to be associated with).
1817 * <li> The object you return here will <em>always</em> be available from
1818 * the {@link #getLastNonConfigurationInstance()} method of the following
1819 * activity instance as described there.
1822 * <p>These guarantees are designed so that an activity can use this API
1823 * to propagate extensive state from the old to new activity instance, from
1824 * loaded bitmaps, to network connections, to evenly actively running
1825 * threads. Note that you should <em>not</em> propagate any data that
1826 * may change based on the configuration, including any data loaded from
1827 * resources such as strings, layouts, or drawables.
1829 * <p>The guarantee of no message handling during the switch to the next
1830 * activity simplifies use with active objects. For example if your retained
1831 * state is an {@link android.os.AsyncTask} you are guaranteed that its
1832 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
1833 * not be called from the call here until you execute the next instance's
1834 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
1835 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
1836 * running in a separate thread.)
1838 * @return Return any Object holding the desired state to propagate to the
1839 * next activity instance.
1841 * @deprecated Use the new {@link Fragment} API
1842 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
1843 * available on older platforms through the Android compatibility package.
1845 public Object onRetainNonConfigurationInstance() {
1850 * Retrieve the non-configuration instance data that was previously
1851 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1852 * be available from the initial {@link #onCreate} and
1853 * {@link #onStart} calls to the new instance, allowing you to extract
1854 * any useful dynamic state from the previous instance.
1856 * <p>Note that the data you retrieve here should <em>only</em> be used
1857 * as an optimization for handling configuration changes. You should always
1858 * be able to handle getting a null pointer back, and an activity must
1859 * still be able to restore itself to its previous state (through the
1860 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1861 * function returns null.
1863 * @return Returns the object previously returned by
1864 * {@link #onRetainNonConfigurationChildInstances()}
1867 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1868 return mLastNonConfigurationInstances != null
1869 ? mLastNonConfigurationInstances.children : null;
1873 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1874 * it should return either a mapping from child activity id strings to arbitrary objects,
1875 * or null. This method is intended to be used by Activity framework subclasses that control a
1876 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1877 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1880 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1884 NonConfigurationInstances retainNonConfigurationInstances() {
1885 Object activity = onRetainNonConfigurationInstance();
1886 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1887 List<Fragment> fragments = mFragments.retainNonConfig();
1888 ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
1889 if (activity == null && children == null && fragments == null && loaders == null
1890 && mVoiceInteractor == null) {
1894 NonConfigurationInstances nci = new NonConfigurationInstances();
1895 nci.activity = activity;
1896 nci.children = children;
1897 nci.fragments = fragments;
1898 nci.loaders = loaders;
1899 if (mVoiceInteractor != null) {
1900 mVoiceInteractor.retainInstance();
1901 nci.voiceInteractor = mVoiceInteractor;
1906 public void onLowMemory() {
1907 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onLowMemory " + this);
1909 mFragments.dispatchLowMemory();
1912 public void onTrimMemory(int level) {
1913 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onTrimMemory " + this + ": " + level);
1915 mFragments.dispatchTrimMemory(level);
1919 * Return the FragmentManager for interacting with fragments associated
1920 * with this activity.
1922 public FragmentManager getFragmentManager() {
1923 return mFragments.getFragmentManager();
1927 * Called when a Fragment is being attached to this activity, immediately
1928 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1929 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1931 public void onAttachFragment(Fragment fragment) {
1936 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1937 * that gives the resulting {@link Cursor} to call
1938 * {@link #startManagingCursor} so that the activity will manage its
1939 * lifecycle for you.
1941 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1942 * or later, consider instead using {@link LoaderManager} instead, available
1943 * via {@link #getLoaderManager()}.</em>
1945 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
1946 * this method, because the activity will do that for you at the appropriate time. However, if
1947 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
1948 * not</em> automatically close the cursor and, in that case, you must call
1949 * {@link Cursor#close()}.</p>
1951 * @param uri The URI of the content provider to query.
1952 * @param projection List of columns to return.
1953 * @param selection SQL WHERE clause.
1954 * @param sortOrder SQL ORDER BY clause.
1956 * @return The Cursor that was returned by query().
1958 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1959 * @see #startManagingCursor
1962 * @deprecated Use {@link CursorLoader} instead.
1965 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1967 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1969 startManagingCursor(c);
1976 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1977 * that gives the resulting {@link Cursor} to call
1978 * {@link #startManagingCursor} so that the activity will manage its
1979 * lifecycle for you.
1981 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1982 * or later, consider instead using {@link LoaderManager} instead, available
1983 * via {@link #getLoaderManager()}.</em>
1985 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
1986 * this method, because the activity will do that for you at the appropriate time. However, if
1987 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
1988 * not</em> automatically close the cursor and, in that case, you must call
1989 * {@link Cursor#close()}.</p>
1991 * @param uri The URI of the content provider to query.
1992 * @param projection List of columns to return.
1993 * @param selection SQL WHERE clause.
1994 * @param selectionArgs The arguments to selection, if any ?s are pesent
1995 * @param sortOrder SQL ORDER BY clause.
1997 * @return The Cursor that was returned by query().
1999 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
2000 * @see #startManagingCursor
2002 * @deprecated Use {@link CursorLoader} instead.
2005 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
2006 String[] selectionArgs, String sortOrder) {
2007 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
2009 startManagingCursor(c);
2015 * This method allows the activity to take care of managing the given
2016 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
2017 * That is, when the activity is stopped it will automatically call
2018 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
2019 * it will call {@link Cursor#requery} for you. When the activity is
2020 * destroyed, all managed Cursors will be closed automatically.
2022 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2023 * or later, consider instead using {@link LoaderManager} instead, available
2024 * via {@link #getLoaderManager()}.</em>
2026 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on cursor obtained from
2027 * {@link #managedQuery}, because the activity will do that for you at the appropriate time.
2028 * However, if you call {@link #stopManagingCursor} on a cursor from a managed query, the system
2029 * <em>will not</em> automatically close the cursor and, in that case, you must call
2030 * {@link Cursor#close()}.</p>
2032 * @param c The Cursor to be managed.
2034 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
2035 * @see #stopManagingCursor
2037 * @deprecated Use the new {@link android.content.CursorLoader} class with
2038 * {@link LoaderManager} instead; this is also
2039 * available on older platforms through the Android compatibility package.
2042 public void startManagingCursor(Cursor c) {
2043 synchronized (mManagedCursors) {
2044 mManagedCursors.add(new ManagedCursor(c));
2049 * Given a Cursor that was previously given to
2050 * {@link #startManagingCursor}, stop the activity's management of that
2053 * <p><strong>Warning:</strong> After calling this method on a cursor from a managed query,
2054 * the system <em>will not</em> automatically close the cursor and you must call
2055 * {@link Cursor#close()}.</p>
2057 * @param c The Cursor that was being managed.
2059 * @see #startManagingCursor
2061 * @deprecated Use the new {@link android.content.CursorLoader} class with
2062 * {@link LoaderManager} instead; this is also
2063 * available on older platforms through the Android compatibility package.
2066 public void stopManagingCursor(Cursor c) {
2067 synchronized (mManagedCursors) {
2068 final int N = mManagedCursors.size();
2069 for (int i=0; i<N; i++) {
2070 ManagedCursor mc = mManagedCursors.get(i);
2071 if (mc.mCursor == c) {
2072 mManagedCursors.remove(i);
2080 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
2085 public void setPersistent(boolean isPersistent) {
2089 * Finds a view that was identified by the id attribute from the XML that
2090 * was processed in {@link #onCreate}.
2092 * @return The view if found or null otherwise.
2095 public View findViewById(@IdRes int id) {
2096 return getWindow().findViewById(id);
2100 * Retrieve a reference to this activity's ActionBar.
2102 * @return The Activity's ActionBar, or null if it does not have one.
2105 public ActionBar getActionBar() {
2106 initWindowDecorActionBar();
2111 * Set a {@link android.widget.Toolbar Toolbar} to act as the {@link ActionBar} for this
2114 * <p>When set to a non-null value the {@link #getActionBar()} method will return
2115 * an {@link ActionBar} object that can be used to control the given toolbar as if it were
2116 * a traditional window decor action bar. The toolbar's menu will be populated with the
2117 * Activity's options menu and the navigation button will be wired through the standard
2118 * {@link android.R.id#home home} menu select action.</p>
2120 * <p>In order to use a Toolbar within the Activity's window content the application
2121 * must not request the window feature {@link Window#FEATURE_ACTION_BAR FEATURE_ACTION_BAR}.</p>
2123 * @param toolbar Toolbar to set as the Activity's action bar
2125 public void setActionBar(@Nullable Toolbar toolbar) {
2126 if (getActionBar() instanceof WindowDecorActionBar) {
2127 throw new IllegalStateException("This Activity already has an action bar supplied " +
2128 "by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " +
2129 "android:windowActionBar to false in your theme to use a Toolbar instead.");
2131 // Clear out the MenuInflater to make sure that it is valid for the new Action Bar
2132 mMenuInflater = null;
2134 ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this);
2136 mWindow.setCallback(tbab.getWrappedWindowCallback());
2137 mActionBar.invalidateOptionsMenu();
2141 * Creates a new ActionBar, locates the inflated ActionBarView,
2142 * initializes the ActionBar with the view, and sets mActionBar.
2144 private void initWindowDecorActionBar() {
2145 Window window = getWindow();
2147 // Initializing the window decor can change window feature flags.
2148 // Make sure that we have the correct set before performing the test below.
2149 window.getDecorView();
2151 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
2155 mActionBar = new WindowDecorActionBar(this);
2156 mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
2158 mWindow.setDefaultIcon(mActivityInfo.getIconResource());
2159 mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
2163 * Set the activity content from a layout resource. The resource will be
2164 * inflated, adding all top-level views to the activity.
2166 * @param layoutResID Resource ID to be inflated.
2168 * @see #setContentView(android.view.View)
2169 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2171 public void setContentView(@LayoutRes int layoutResID) {
2172 getWindow().setContentView(layoutResID);
2173 initWindowDecorActionBar();
2177 * Set the activity content to an explicit view. This view is placed
2178 * directly into the activity's view hierarchy. It can itself be a complex
2179 * view hierarchy. When calling this method, the layout parameters of the
2180 * specified view are ignored. Both the width and the height of the view are
2181 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
2182 * your own layout parameters, invoke
2183 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
2186 * @param view The desired content to display.
2188 * @see #setContentView(int)
2189 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2191 public void setContentView(View view) {
2192 getWindow().setContentView(view);
2193 initWindowDecorActionBar();
2197 * Set the activity content to an explicit view. This view is placed
2198 * directly into the activity's view hierarchy. It can itself be a complex
2201 * @param view The desired content to display.
2202 * @param params Layout parameters for the view.
2204 * @see #setContentView(android.view.View)
2205 * @see #setContentView(int)
2207 public void setContentView(View view, ViewGroup.LayoutParams params) {
2208 getWindow().setContentView(view, params);
2209 initWindowDecorActionBar();
2213 * Add an additional content view to the activity. Added after any existing
2214 * ones in the activity -- existing views are NOT removed.
2216 * @param view The desired content to display.
2217 * @param params Layout parameters for the view.
2219 public void addContentView(View view, ViewGroup.LayoutParams params) {
2220 getWindow().addContentView(view, params);
2221 initWindowDecorActionBar();
2225 * Retrieve the {@link TransitionManager} responsible for default transitions in this window.
2226 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2228 * <p>This method will return non-null after content has been initialized (e.g. by using
2229 * {@link #setContentView}) if {@link Window#FEATURE_CONTENT_TRANSITIONS} has been granted.</p>
2231 * @return This window's content TransitionManager or null if none is set.
2233 public TransitionManager getContentTransitionManager() {
2234 return getWindow().getTransitionManager();
2238 * Set the {@link TransitionManager} to use for default transitions in this window.
2239 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2241 * @param tm The TransitionManager to use for scene changes.
2243 public void setContentTransitionManager(TransitionManager tm) {
2244 getWindow().setTransitionManager(tm);
2248 * Retrieve the {@link Scene} representing this window's current content.
2249 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2251 * <p>This method will return null if the current content is not represented by a Scene.</p>
2253 * @return Current Scene being shown or null
2255 public Scene getContentScene() {
2256 return getWindow().getContentScene();
2260 * Sets whether this activity is finished when touched outside its window's
2263 public void setFinishOnTouchOutside(boolean finish) {
2264 mWindow.setCloseOnTouchOutside(finish);
2269 DEFAULT_KEYS_DISABLE,
2270 DEFAULT_KEYS_DIALER,
2271 DEFAULT_KEYS_SHORTCUT,
2272 DEFAULT_KEYS_SEARCH_LOCAL,
2273 DEFAULT_KEYS_SEARCH_GLOBAL})
2274 @Retention(RetentionPolicy.SOURCE)
2275 @interface DefaultKeyMode {}
2278 * Use with {@link #setDefaultKeyMode} to turn off default handling of
2281 * @see #setDefaultKeyMode
2283 static public final int DEFAULT_KEYS_DISABLE = 0;
2285 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
2288 * @see #setDefaultKeyMode
2290 static public final int DEFAULT_KEYS_DIALER = 1;
2292 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
2293 * default key handling.
2295 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
2297 * @see #setDefaultKeyMode
2299 static public final int DEFAULT_KEYS_SHORTCUT = 2;
2301 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2302 * will start an application-defined search. (If the application or activity does not
2303 * actually define a search, the the keys will be ignored.)
2305 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2307 * @see #setDefaultKeyMode
2309 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
2312 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2313 * will start a global search (typically web search, but some platforms may define alternate
2314 * methods for global search)
2316 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2318 * @see #setDefaultKeyMode
2320 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
2323 * Select the default key handling for this activity. This controls what
2324 * will happen to key events that are not otherwise handled. The default
2325 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
2326 * floor. Other modes allow you to launch the dialer
2327 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
2328 * menu without requiring the menu key be held down
2329 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
2330 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
2332 * <p>Note that the mode selected here does not impact the default
2333 * handling of system keys, such as the "back" and "menu" keys, and your
2334 * activity and its views always get a first chance to receive and handle
2335 * all application keys.
2337 * @param mode The desired default key mode constant.
2339 * @see #DEFAULT_KEYS_DISABLE
2340 * @see #DEFAULT_KEYS_DIALER
2341 * @see #DEFAULT_KEYS_SHORTCUT
2342 * @see #DEFAULT_KEYS_SEARCH_LOCAL
2343 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
2346 public final void setDefaultKeyMode(@DefaultKeyMode int mode) {
2347 mDefaultKeyMode = mode;
2349 // Some modes use a SpannableStringBuilder to track & dispatch input events
2350 // This list must remain in sync with the switch in onKeyDown()
2352 case DEFAULT_KEYS_DISABLE:
2353 case DEFAULT_KEYS_SHORTCUT:
2354 mDefaultKeySsb = null; // not used in these modes
2356 case DEFAULT_KEYS_DIALER:
2357 case DEFAULT_KEYS_SEARCH_LOCAL:
2358 case DEFAULT_KEYS_SEARCH_GLOBAL:
2359 mDefaultKeySsb = new SpannableStringBuilder();
2360 Selection.setSelection(mDefaultKeySsb,0);
2363 throw new IllegalArgumentException();
2368 * Called when a key was pressed down and not handled by any of the views
2369 * inside of the activity. So, for example, key presses while the cursor
2370 * is inside a TextView will not trigger the event (unless it is a navigation
2371 * to another object) because TextView handles its own key presses.
2373 * <p>If the focused view didn't want this event, this method is called.
2375 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
2376 * by calling {@link #onBackPressed()}, though the behavior varies based
2377 * on the application compatibility mode: for
2378 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
2379 * it will set up the dispatch to call {@link #onKeyUp} where the action
2380 * will be performed; for earlier applications, it will perform the
2381 * action immediately in on-down, as those versions of the platform
2384 * <p>Other additional default key handling may be performed
2385 * if configured with {@link #setDefaultKeyMode}.
2387 * @return Return <code>true</code> to prevent this event from being propagated
2388 * further, or <code>false</code> to indicate that you have not handled
2389 * this event and it should continue to be propagated.
2391 * @see android.view.KeyEvent
2393 public boolean onKeyDown(int keyCode, KeyEvent event) {
2394 if (keyCode == KeyEvent.KEYCODE_BACK) {
2395 if (getApplicationInfo().targetSdkVersion
2396 >= Build.VERSION_CODES.ECLAIR) {
2397 event.startTracking();
2404 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
2406 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
2407 Window w = getWindow();
2408 if (w.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
2409 w.performPanelShortcut(Window.FEATURE_OPTIONS_PANEL, keyCode, event,
2410 Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
2415 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
2416 boolean clearSpannable = false;
2418 if ((event.getRepeatCount() != 0) || event.isSystem()) {
2419 clearSpannable = true;
2422 handled = TextKeyListener.getInstance().onKeyDown(
2423 null, mDefaultKeySsb, keyCode, event);
2424 if (handled && mDefaultKeySsb.length() > 0) {
2425 // something useable has been typed - dispatch it now.
2427 final String str = mDefaultKeySsb.toString();
2428 clearSpannable = true;
2430 switch (mDefaultKeyMode) {
2431 case DEFAULT_KEYS_DIALER:
2432 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
2433 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2434 startActivity(intent);
2436 case DEFAULT_KEYS_SEARCH_LOCAL:
2437 startSearch(str, false, null, false);
2439 case DEFAULT_KEYS_SEARCH_GLOBAL:
2440 startSearch(str, false, null, true);
2445 if (clearSpannable) {
2446 mDefaultKeySsb.clear();
2447 mDefaultKeySsb.clearSpans();
2448 Selection.setSelection(mDefaultKeySsb,0);
2455 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2456 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2459 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2464 * Called when a key was released and not handled by any of the views
2465 * inside of the activity. So, for example, key presses while the cursor
2466 * is inside a TextView will not trigger the event (unless it is a navigation
2467 * to another object) because TextView handles its own key presses.
2469 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2472 * @return Return <code>true</code> to prevent this event from being propagated
2473 * further, or <code>false</code> to indicate that you have not handled
2474 * this event and it should continue to be propagated.
2478 public boolean onKeyUp(int keyCode, KeyEvent event) {
2479 if (getApplicationInfo().targetSdkVersion
2480 >= Build.VERSION_CODES.ECLAIR) {
2481 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2482 && !event.isCanceled()) {
2491 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2492 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2495 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2500 * Called when the activity has detected the user's press of the back
2501 * key. The default implementation simply finishes the current activity,
2502 * but you can override this to do whatever you want.
2504 public void onBackPressed() {
2505 if (mActionBar != null && mActionBar.collapseActionView()) {
2509 if (!mFragments.getFragmentManager().popBackStackImmediate()) {
2510 finishAfterTransition();
2515 * Called when a key shortcut event is not handled by any of the views in the Activity.
2516 * Override this method to implement global key shortcuts for the Activity.
2517 * Key shortcuts can also be implemented by setting the
2518 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
2520 * @param keyCode The value in event.getKeyCode().
2521 * @param event Description of the key event.
2522 * @return True if the key shortcut was handled.
2524 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2525 // Let the Action Bar have a chance at handling the shortcut.
2526 ActionBar actionBar = getActionBar();
2527 return (actionBar != null && actionBar.onKeyShortcut(keyCode, event));
2531 * Called when a touch screen event was not handled by any of the views
2532 * under it. This is most useful to process touch events that happen
2533 * outside of your window bounds, where there is no view to receive it.
2535 * @param event The touch screen event being processed.
2537 * @return Return true if you have consumed the event, false if you haven't.
2538 * The default implementation always returns false.
2540 public boolean onTouchEvent(MotionEvent event) {
2541 if (mWindow.shouldCloseOnTouch(this, event)) {
2550 * Called when the trackball was moved and not handled by any of the
2551 * views inside of the activity. So, for example, if the trackball moves
2552 * while focus is on a button, you will receive a call here because
2553 * buttons do not normally do anything with trackball events. The call
2554 * here happens <em>before</em> trackball movements are converted to
2555 * DPAD key events, which then get sent back to the view hierarchy, and
2556 * will be processed at the point for things like focus navigation.
2558 * @param event The trackball event being processed.
2560 * @return Return true if you have consumed the event, false if you haven't.
2561 * The default implementation always returns false.
2563 public boolean onTrackballEvent(MotionEvent event) {
2568 * Called when a generic motion event was not handled by any of the
2569 * views inside of the activity.
2571 * Generic motion events describe joystick movements, mouse hovers, track pad
2572 * touches, scroll wheel movements and other input events. The
2573 * {@link MotionEvent#getSource() source} of the motion event specifies
2574 * the class of input that was received. Implementations of this method
2575 * must examine the bits in the source before processing the event.
2576 * The following code example shows how this is done.
2578 * Generic motion events with source class
2579 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
2580 * are delivered to the view under the pointer. All other generic motion events are
2581 * delivered to the focused view.
2583 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
2584 * handle this event.
2587 * @param event The generic motion event being processed.
2589 * @return Return true if you have consumed the event, false if you haven't.
2590 * The default implementation always returns false.
2592 public boolean onGenericMotionEvent(MotionEvent event) {
2597 * Called whenever a key, touch, or trackball event is dispatched to the
2598 * activity. Implement this method if you wish to know that the user has
2599 * interacted with the device in some way while your activity is running.
2600 * This callback and {@link #onUserLeaveHint} are intended to help
2601 * activities manage status bar notifications intelligently; specifically,
2602 * for helping activities determine the proper time to cancel a notfication.
2604 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2605 * be accompanied by calls to {@link #onUserInteraction}. This
2606 * ensures that your activity will be told of relevant user activity such
2607 * as pulling down the notification pane and touching an item there.
2609 * <p>Note that this callback will be invoked for the touch down action
2610 * that begins a touch gesture, but may not be invoked for the touch-moved
2611 * and touch-up actions that follow.
2613 * @see #onUserLeaveHint()
2615 public void onUserInteraction() {
2618 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2619 // Update window manager if: we have a view, that view is
2620 // attached to its parent (which will be a RootView), and
2621 // this activity is not embedded.
2622 if (mParent == null) {
2623 View decor = mDecor;
2624 if (decor != null && decor.getParent() != null) {
2625 getWindowManager().updateViewLayout(decor, params);
2630 public void onContentChanged() {
2634 * Called when the current {@link Window} of the activity gains or loses
2635 * focus. This is the best indicator of whether this activity is visible
2636 * to the user. The default implementation clears the key tracking
2637 * state, so should always be called.
2639 * <p>Note that this provides information about global focus state, which
2640 * is managed independently of activity lifecycles. As such, while focus
2641 * changes will generally have some relation to lifecycle changes (an
2642 * activity that is stopped will not generally get window focus), you
2643 * should not rely on any particular order between the callbacks here and
2644 * those in the other lifecycle methods such as {@link #onResume}.
2646 * <p>As a general rule, however, a resumed activity will have window
2647 * focus... unless it has displayed other dialogs or popups that take
2648 * input focus, in which case the activity itself will not have focus
2649 * when the other windows have it. Likewise, the system may display
2650 * system-level windows (such as the status bar notification panel or
2651 * a system alert) which will temporarily take window input focus without
2652 * pausing the foreground activity.
2654 * @param hasFocus Whether the window of this activity has focus.
2656 * @see #hasWindowFocus()
2658 * @see View#onWindowFocusChanged(boolean)
2660 public void onWindowFocusChanged(boolean hasFocus) {
2664 * Called when the main window associated with the activity has been
2665 * attached to the window manager.
2666 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2667 * for more information.
2668 * @see View#onAttachedToWindow
2670 public void onAttachedToWindow() {
2674 * Called when the main window associated with the activity has been
2675 * detached from the window manager.
2676 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2677 * for more information.
2678 * @see View#onDetachedFromWindow
2680 public void onDetachedFromWindow() {
2684 * Returns true if this activity's <em>main</em> window currently has window focus.
2685 * Note that this is not the same as the view itself having focus.
2687 * @return True if this activity's main window currently has window focus.
2689 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2691 public boolean hasWindowFocus() {
2692 Window w = getWindow();
2694 View d = w.getDecorView();
2696 return d.hasWindowFocus();
2703 * Called when the main window associated with the activity has been dismissed.
2707 public void onWindowDismissed() {
2712 * Called to process key events. You can override this to intercept all
2713 * key events before they are dispatched to the window. Be sure to call
2714 * this implementation for key events that should be handled normally.
2716 * @param event The key event.
2718 * @return boolean Return true if this event was consumed.
2720 public boolean dispatchKeyEvent(KeyEvent event) {
2721 onUserInteraction();
2723 // Let action bars open menus in response to the menu key prioritized over
2724 // the window handling it
2725 if (event.getKeyCode() == KeyEvent.KEYCODE_MENU &&
2726 mActionBar != null && mActionBar.onMenuKeyEvent(event)) {
2730 Window win = getWindow();
2731 if (win.superDispatchKeyEvent(event)) {
2734 View decor = mDecor;
2735 if (decor == null) decor = win.getDecorView();
2736 return event.dispatch(this, decor != null
2737 ? decor.getKeyDispatcherState() : null, this);
2741 * Called to process a key shortcut event.
2742 * You can override this to intercept all key shortcut events before they are
2743 * dispatched to the window. Be sure to call this implementation for key shortcut
2744 * events that should be handled normally.
2746 * @param event The key shortcut event.
2747 * @return True if this event was consumed.
2749 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
2750 onUserInteraction();
2751 if (getWindow().superDispatchKeyShortcutEvent(event)) {
2754 return onKeyShortcut(event.getKeyCode(), event);
2758 * Called to process touch screen events. You can override this to
2759 * intercept all touch screen events before they are dispatched to the
2760 * window. Be sure to call this implementation for touch screen events
2761 * that should be handled normally.
2763 * @param ev The touch screen event.
2765 * @return boolean Return true if this event was consumed.
2767 public boolean dispatchTouchEvent(MotionEvent ev) {
2768 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2769 onUserInteraction();
2771 if (getWindow().superDispatchTouchEvent(ev)) {
2774 return onTouchEvent(ev);
2778 * Called to process trackball events. You can override this to
2779 * intercept all trackball events before they are dispatched to the
2780 * window. Be sure to call this implementation for trackball events
2781 * that should be handled normally.
2783 * @param ev The trackball event.
2785 * @return boolean Return true if this event was consumed.
2787 public boolean dispatchTrackballEvent(MotionEvent ev) {
2788 onUserInteraction();
2789 if (getWindow().superDispatchTrackballEvent(ev)) {
2792 return onTrackballEvent(ev);
2796 * Called to process generic motion events. You can override this to
2797 * intercept all generic motion events before they are dispatched to the
2798 * window. Be sure to call this implementation for generic motion events
2799 * that should be handled normally.
2801 * @param ev The generic motion event.
2803 * @return boolean Return true if this event was consumed.
2805 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
2806 onUserInteraction();
2807 if (getWindow().superDispatchGenericMotionEvent(ev)) {
2810 return onGenericMotionEvent(ev);
2813 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2814 event.setClassName(getClass().getName());
2815 event.setPackageName(getPackageName());
2817 LayoutParams params = getWindow().getAttributes();
2818 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2819 (params.height == LayoutParams.MATCH_PARENT);
2820 event.setFullScreen(isFullScreen);
2822 CharSequence title = getTitle();
2823 if (!TextUtils.isEmpty(title)) {
2824 event.getText().add(title);
2831 * Default implementation of
2832 * {@link android.view.Window.Callback#onCreatePanelView}
2833 * for activities. This
2834 * simply returns null so that all panel sub-windows will have the default
2838 public View onCreatePanelView(int featureId) {
2843 * Default implementation of
2844 * {@link android.view.Window.Callback#onCreatePanelMenu}
2845 * for activities. This calls through to the new
2846 * {@link #onCreateOptionsMenu} method for the
2847 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2848 * so that subclasses of Activity don't need to deal with feature codes.
2850 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2851 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
2852 boolean show = onCreateOptionsMenu(menu);
2853 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2860 * Default implementation of
2861 * {@link android.view.Window.Callback#onPreparePanel}
2862 * for activities. This
2863 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2864 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2865 * panel, so that subclasses of
2866 * Activity don't need to deal with feature codes.
2868 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2869 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2870 boolean goforit = onPrepareOptionsMenu(menu);
2871 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
2880 * @return The default implementation returns true.
2882 public boolean onMenuOpened(int featureId, Menu menu) {
2883 if (featureId == Window.FEATURE_ACTION_BAR) {
2884 initWindowDecorActionBar();
2885 if (mActionBar != null) {
2886 mActionBar.dispatchMenuVisibilityChanged(true);
2888 Log.e(TAG, "Tried to open action bar menu with no action bar");
2895 * Default implementation of
2896 * {@link android.view.Window.Callback#onMenuItemSelected}
2897 * for activities. This calls through to the new
2898 * {@link #onOptionsItemSelected} method for the
2899 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2900 * panel, so that subclasses of
2901 * Activity don't need to deal with feature codes.
2903 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2904 CharSequence titleCondensed = item.getTitleCondensed();
2906 switch (featureId) {
2907 case Window.FEATURE_OPTIONS_PANEL:
2908 // Put event logging here so it gets called even if subclass
2909 // doesn't call through to superclass's implmeentation of each
2910 // of these methods below
2911 if(titleCondensed != null) {
2912 EventLog.writeEvent(50000, 0, titleCondensed.toString());
2914 if (onOptionsItemSelected(item)) {
2917 if (mFragments.dispatchOptionsItemSelected(item)) {
2920 if (item.getItemId() == android.R.id.home && mActionBar != null &&
2921 (mActionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
2922 if (mParent == null) {
2923 return onNavigateUp();
2925 return mParent.onNavigateUpFromChild(this);
2930 case Window.FEATURE_CONTEXT_MENU:
2931 if(titleCondensed != null) {
2932 EventLog.writeEvent(50000, 1, titleCondensed.toString());
2934 if (onContextItemSelected(item)) {
2937 return mFragments.dispatchContextItemSelected(item);
2945 * Default implementation of
2946 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2947 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2948 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2949 * so that subclasses of Activity don't need to deal with feature codes.
2950 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2951 * {@link #onContextMenuClosed(Menu)} will be called.
2953 public void onPanelClosed(int featureId, Menu menu) {
2954 switch (featureId) {
2955 case Window.FEATURE_OPTIONS_PANEL:
2956 mFragments.dispatchOptionsMenuClosed(menu);
2957 onOptionsMenuClosed(menu);
2960 case Window.FEATURE_CONTEXT_MENU:
2961 onContextMenuClosed(menu);
2964 case Window.FEATURE_ACTION_BAR:
2965 initWindowDecorActionBar();
2966 mActionBar.dispatchMenuVisibilityChanged(false);
2972 * Declare that the options menu has changed, so should be recreated.
2973 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2974 * time it needs to be displayed.
2976 public void invalidateOptionsMenu() {
2977 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
2978 (mActionBar == null || !mActionBar.invalidateOptionsMenu())) {
2979 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2984 * Initialize the contents of the Activity's standard options menu. You
2985 * should place your menu items in to <var>menu</var>.
2987 * <p>This is only called once, the first time the options menu is
2988 * displayed. To update the menu every time it is displayed, see
2989 * {@link #onPrepareOptionsMenu}.
2991 * <p>The default implementation populates the menu with standard system
2992 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2993 * they will be correctly ordered with application-defined menu items.
2994 * Deriving classes should always call through to the base implementation.
2996 * <p>You can safely hold on to <var>menu</var> (and any items created
2997 * from it), making modifications to it as desired, until the next
2998 * time onCreateOptionsMenu() is called.
3000 * <p>When you add items to the menu, you can implement the Activity's
3001 * {@link #onOptionsItemSelected} method to handle them there.
3003 * @param menu The options menu in which you place your items.
3005 * @return You must return true for the menu to be displayed;
3006 * if you return false it will not be shown.
3008 * @see #onPrepareOptionsMenu
3009 * @see #onOptionsItemSelected
3011 public boolean onCreateOptionsMenu(Menu menu) {
3012 if (mParent != null) {
3013 return mParent.onCreateOptionsMenu(menu);
3019 * Prepare the Screen's standard options menu to be displayed. This is
3020 * called right before the menu is shown, every time it is shown. You can
3021 * use this method to efficiently enable/disable items or otherwise
3022 * dynamically modify the contents.
3024 * <p>The default implementation updates the system menu items based on the
3025 * activity's state. Deriving classes should always call through to the
3026 * base class implementation.
3028 * @param menu The options menu as last shown or first initialized by
3029 * onCreateOptionsMenu().
3031 * @return You must return true for the menu to be displayed;
3032 * if you return false it will not be shown.
3034 * @see #onCreateOptionsMenu
3036 public boolean onPrepareOptionsMenu(Menu menu) {
3037 if (mParent != null) {
3038 return mParent.onPrepareOptionsMenu(menu);
3044 * This hook is called whenever an item in your options menu is selected.
3045 * The default implementation simply returns false to have the normal
3046 * processing happen (calling the item's Runnable or sending a message to
3047 * its Handler as appropriate). You can use this method for any items
3048 * for which you would like to do processing without those other
3051 * <p>Derived classes should call through to the base class for it to
3052 * perform the default menu handling.</p>
3054 * @param item The menu item that was selected.
3056 * @return boolean Return false to allow normal menu processing to
3057 * proceed, true to consume it here.
3059 * @see #onCreateOptionsMenu
3061 public boolean onOptionsItemSelected(MenuItem item) {
3062 if (mParent != null) {
3063 return mParent.onOptionsItemSelected(item);
3069 * This method is called whenever the user chooses to navigate Up within your application's
3070 * activity hierarchy from the action bar.
3072 * <p>If the attribute {@link android.R.attr#parentActivityName parentActivityName}
3073 * was specified in the manifest for this activity or an activity-alias to it,
3074 * default Up navigation will be handled automatically. If any activity
3075 * along the parent chain requires extra Intent arguments, the Activity subclass
3076 * should override the method {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}
3077 * to supply those arguments.</p>
3079 * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
3080 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
3081 * from the design guide for more information about navigating within your app.</p>
3083 * <p>See the {@link TaskStackBuilder} class and the Activity methods
3084 * {@link #getParentActivityIntent()}, {@link #shouldUpRecreateTask(Intent)}, and
3085 * {@link #navigateUpTo(Intent)} for help implementing custom Up navigation.
3086 * The AppNavigation sample application in the Android SDK is also available for reference.</p>
3088 * @return true if Up navigation completed successfully and this Activity was finished,
3091 public boolean onNavigateUp() {
3092 // Automatically handle hierarchical Up navigation if the proper
3093 // metadata is available.
3094 Intent upIntent = getParentActivityIntent();
3095 if (upIntent != null) {
3096 if (mActivityInfo.taskAffinity == null) {
3097 // Activities with a null affinity are special; they really shouldn't
3098 // specify a parent activity intent in the first place. Just finish
3099 // the current activity and call it a day.
3101 } else if (shouldUpRecreateTask(upIntent)) {
3102 TaskStackBuilder b = TaskStackBuilder.create(this);
3103 onCreateNavigateUpTaskStack(b);
3104 onPrepareNavigateUpTaskStack(b);
3105 b.startActivities();
3107 // We can't finishAffinity if we have a result.
3108 // Fall back and simply finish the current activity instead.
3109 if (mResultCode != RESULT_CANCELED || mResultData != null) {
3110 // Tell the developer what's going on to avoid hair-pulling.
3111 Log.i(TAG, "onNavigateUp only finishing topmost activity to return a result");
3117 navigateUpTo(upIntent);
3125 * This is called when a child activity of this one attempts to navigate up.
3126 * The default implementation simply calls onNavigateUp() on this activity (the parent).
3128 * @param child The activity making the call.
3130 public boolean onNavigateUpFromChild(Activity child) {
3131 return onNavigateUp();
3135 * Define the synthetic task stack that will be generated during Up navigation from
3138 * <p>The default implementation of this method adds the parent chain of this activity
3139 * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications
3140 * may choose to override this method to construct the desired task stack in a different
3143 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
3144 * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent
3145 * returned by {@link #getParentActivityIntent()}.</p>
3147 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
3148 * by the manifest should override {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}.</p>
3150 * @param builder An empty TaskStackBuilder - the application should add intents representing
3151 * the desired task stack
3153 public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) {
3154 builder.addParentStack(this);
3158 * Prepare the synthetic task stack that will be generated during Up navigation
3159 * from a different task.
3161 * <p>This method receives the {@link TaskStackBuilder} with the constructed series of
3162 * Intents as generated by {@link #onCreateNavigateUpTaskStack(TaskStackBuilder)}.
3163 * If any extra data should be added to these intents before launching the new task,
3164 * the application should override this method and add that data here.</p>
3166 * @param builder A TaskStackBuilder that has been populated with Intents by
3167 * onCreateNavigateUpTaskStack.
3169 public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) {
3173 * This hook is called whenever the options menu is being closed (either by the user canceling
3174 * the menu with the back/menu button, or when an item is selected).
3176 * @param menu The options menu as last shown or first initialized by
3177 * onCreateOptionsMenu().
3179 public void onOptionsMenuClosed(Menu menu) {
3180 if (mParent != null) {
3181 mParent.onOptionsMenuClosed(menu);
3186 * Programmatically opens the options menu. If the options menu is already
3187 * open, this method does nothing.
3189 public void openOptionsMenu() {
3190 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3191 (mActionBar == null || !mActionBar.openOptionsMenu())) {
3192 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
3197 * Progammatically closes the options menu. If the options menu is already
3198 * closed, this method does nothing.
3200 public void closeOptionsMenu() {
3201 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
3202 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
3207 * Called when a context menu for the {@code view} is about to be shown.
3208 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
3209 * time the context menu is about to be shown and should be populated for
3210 * the view (or item inside the view for {@link AdapterView} subclasses,
3211 * this can be found in the {@code menuInfo})).
3213 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
3214 * item has been selected.
3216 * It is not safe to hold onto the context menu after this method returns.
3219 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
3223 * Registers a context menu to be shown for the given view (multiple views
3224 * can show the context menu). This method will set the
3225 * {@link OnCreateContextMenuListener} on the view to this activity, so
3226 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
3227 * called when it is time to show the context menu.
3229 * @see #unregisterForContextMenu(View)
3230 * @param view The view that should show a context menu.
3232 public void registerForContextMenu(View view) {
3233 view.setOnCreateContextMenuListener(this);
3237 * Prevents a context menu to be shown for the given view. This method will remove the
3238 * {@link OnCreateContextMenuListener} on the view.
3240 * @see #registerForContextMenu(View)
3241 * @param view The view that should stop showing a context menu.
3243 public void unregisterForContextMenu(View view) {
3244 view.setOnCreateContextMenuListener(null);
3248 * Programmatically opens the context menu for a particular {@code view}.
3249 * The {@code view} should have been added via
3250 * {@link #registerForContextMenu(View)}.
3252 * @param view The view to show the context menu for.
3254 public void openContextMenu(View view) {
3255 view.showContextMenu();
3259 * Programmatically closes the most recently opened context menu, if showing.
3261 public void closeContextMenu() {
3262 if (mWindow.hasFeature(Window.FEATURE_CONTEXT_MENU)) {
3263 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
3268 * This hook is called whenever an item in a context menu is selected. The
3269 * default implementation simply returns false to have the normal processing
3270 * happen (calling the item's Runnable or sending a message to its Handler
3271 * as appropriate). You can use this method for any items for which you
3272 * would like to do processing without those other facilities.
3274 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
3275 * View that added this menu item.
3277 * Derived classes should call through to the base class for it to perform
3278 * the default menu handling.
3280 * @param item The context menu item that was selected.
3281 * @return boolean Return false to allow normal context menu processing to
3282 * proceed, true to consume it here.
3284 public boolean onContextItemSelected(MenuItem item) {
3285 if (mParent != null) {
3286 return mParent.onContextItemSelected(item);
3292 * This hook is called whenever the context menu is being closed (either by
3293 * the user canceling the menu with the back/menu button, or when an item is
3296 * @param menu The context menu that is being closed.
3298 public void onContextMenuClosed(Menu menu) {
3299 if (mParent != null) {
3300 mParent.onContextMenuClosed(menu);
3305 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
3308 protected Dialog onCreateDialog(int id) {
3313 * Callback for creating dialogs that are managed (saved and restored) for you
3314 * by the activity. The default implementation calls through to
3315 * {@link #onCreateDialog(int)} for compatibility.
3317 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3318 * or later, consider instead using a {@link DialogFragment} instead.</em>
3320 * <p>If you use {@link #showDialog(int)}, the activity will call through to
3321 * this method the first time, and hang onto it thereafter. Any dialog
3322 * that is created by this method will automatically be saved and restored
3323 * for you, including whether it is showing.
3325 * <p>If you would like the activity to manage saving and restoring dialogs
3326 * for you, you should override this method and handle any ids that are
3327 * passed to {@link #showDialog}.
3329 * <p>If you would like an opportunity to prepare your dialog before it is shown,
3330 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
3332 * @param id The id of the dialog.
3333 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3334 * @return The dialog. If you return null, the dialog will not be created.
3336 * @see #onPrepareDialog(int, Dialog, Bundle)
3337 * @see #showDialog(int, Bundle)
3338 * @see #dismissDialog(int)
3339 * @see #removeDialog(int)
3341 * @deprecated Use the new {@link DialogFragment} class with
3342 * {@link FragmentManager} instead; this is also
3343 * available on older platforms through the Android compatibility package.
3347 protected Dialog onCreateDialog(int id, Bundle args) {
3348 return onCreateDialog(id);
3352 * @deprecated Old no-arguments version of
3353 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
3356 protected void onPrepareDialog(int id, Dialog dialog) {
3357 dialog.setOwnerActivity(this);
3361 * Provides an opportunity to prepare a managed dialog before it is being
3362 * shown. The default implementation calls through to
3363 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
3366 * Override this if you need to update a managed dialog based on the state
3367 * of the application each time it is shown. For example, a time picker
3368 * dialog might want to be updated with the current time. You should call
3369 * through to the superclass's implementation. The default implementation
3370 * will set this Activity as the owner activity on the Dialog.
3372 * @param id The id of the managed dialog.
3373 * @param dialog The dialog.
3374 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3375 * @see #onCreateDialog(int, Bundle)
3376 * @see #showDialog(int)
3377 * @see #dismissDialog(int)
3378 * @see #removeDialog(int)
3380 * @deprecated Use the new {@link DialogFragment} class with
3381 * {@link FragmentManager} instead; this is also
3382 * available on older platforms through the Android compatibility package.
3385 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
3386 onPrepareDialog(id, dialog);
3390 * Simple version of {@link #showDialog(int, Bundle)} that does not
3391 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
3392 * with null arguments.
3394 * @deprecated Use the new {@link DialogFragment} class with
3395 * {@link FragmentManager} instead; this is also
3396 * available on older platforms through the Android compatibility package.
3399 public final void showDialog(int id) {
3400 showDialog(id, null);
3404 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
3405 * will be made with the same id the first time this is called for a given
3406 * id. From thereafter, the dialog will be automatically saved and restored.
3408 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3409 * or later, consider instead using a {@link DialogFragment} instead.</em>
3411 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
3412 * be made to provide an opportunity to do any timely preparation.
3414 * @param id The id of the managed dialog.
3415 * @param args Arguments to pass through to the dialog. These will be saved
3416 * and restored for you. Note that if the dialog is already created,
3417 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
3418 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
3419 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
3420 * @return Returns true if the Dialog was created; false is returned if
3421 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
3424 * @see #onCreateDialog(int, Bundle)
3425 * @see #onPrepareDialog(int, Dialog, Bundle)
3426 * @see #dismissDialog(int)
3427 * @see #removeDialog(int)
3429 * @deprecated Use the new {@link DialogFragment} class with
3430 * {@link FragmentManager} instead; this is also
3431 * available on older platforms through the Android compatibility package.
3435 public final boolean showDialog(int id, Bundle args) {
3436 if (mManagedDialogs == null) {
3437 mManagedDialogs = new SparseArray<ManagedDialog>();
3439 ManagedDialog md = mManagedDialogs.get(id);
3441 md = new ManagedDialog();
3442 md.mDialog = createDialog(id, null, args);
3443 if (md.mDialog == null) {
3446 mManagedDialogs.put(id, md);
3450 onPrepareDialog(id, md.mDialog, args);
3456 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
3458 * @param id The id of the managed dialog.
3460 * @throws IllegalArgumentException if the id was not previously shown via
3461 * {@link #showDialog(int)}.
3463 * @see #onCreateDialog(int, Bundle)
3464 * @see #onPrepareDialog(int, Dialog, Bundle)
3465 * @see #showDialog(int)
3466 * @see #removeDialog(int)
3468 * @deprecated Use the new {@link DialogFragment} class with
3469 * {@link FragmentManager} instead; this is also
3470 * available on older platforms through the Android compatibility package.
3473 public final void dismissDialog(int id) {
3474 if (mManagedDialogs == null) {
3475 throw missingDialog(id);
3478 final ManagedDialog md = mManagedDialogs.get(id);
3480 throw missingDialog(id);
3482 md.mDialog.dismiss();
3486 * Creates an exception to throw if a user passed in a dialog id that is
3489 private IllegalArgumentException missingDialog(int id) {
3490 return new IllegalArgumentException("no dialog with id " + id + " was ever "
3491 + "shown via Activity#showDialog");
3495 * Removes any internal references to a dialog managed by this Activity.
3496 * If the dialog is showing, it will dismiss it as part of the clean up.
3498 * <p>This can be useful if you know that you will never show a dialog again and
3499 * want to avoid the overhead of saving and restoring it in the future.
3501 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
3502 * will not throw an exception if you try to remove an ID that does not
3503 * currently have an associated dialog.</p>
3505 * @param id The id of the managed dialog.
3507 * @see #onCreateDialog(int, Bundle)
3508 * @see #onPrepareDialog(int, Dialog, Bundle)
3509 * @see #showDialog(int)
3510 * @see #dismissDialog(int)
3512 * @deprecated Use the new {@link DialogFragment} class with
3513 * {@link FragmentManager} instead; this is also
3514 * available on older platforms through the Android compatibility package.
3517 public final void removeDialog(int id) {
3518 if (mManagedDialogs != null) {
3519 final ManagedDialog md = mManagedDialogs.get(id);
3521 md.mDialog.dismiss();
3522 mManagedDialogs.remove(id);
3528 * This hook is called when the user signals the desire to start a search.
3530 * <p>You can use this function as a simple way to launch the search UI, in response to a
3531 * menu item, search button, or other widgets within your activity. Unless overidden,
3532 * calling this function is the same as calling
3533 * {@link #startSearch startSearch(null, false, null, false)}, which launches
3534 * search for the current activity as specified in its manifest, see {@link SearchManager}.
3536 * <p>You can override this function to force global search, e.g. in response to a dedicated
3537 * search key, or to block search entirely (by simply returning false).
3539 * <p>Note: when running in a {@link Configuration#UI_MODE_TYPE_TELEVISION}, the default
3540 * implementation changes to simply return false and you must supply your own custom
3541 * implementation if you want to support search.</p>
3543 * @param searchEvent The {@link SearchEvent} that signaled this search.
3544 * @return Returns {@code true} if search launched, and {@code false} if the activity does
3545 * not respond to search. The default implementation always returns {@code true}, except
3546 * when in {@link Configuration#UI_MODE_TYPE_TELEVISION} mode where it returns false.
3548 * @see android.app.SearchManager
3550 public boolean onSearchRequested(@Nullable SearchEvent searchEvent) {
3551 mSearchEvent = searchEvent;
3552 boolean result = onSearchRequested();
3553 mSearchEvent = null;
3558 * @see #onSearchRequested(SearchEvent)
3560 public boolean onSearchRequested() {
3561 if ((getResources().getConfiguration().uiMode&Configuration.UI_MODE_TYPE_MASK)
3562 != Configuration.UI_MODE_TYPE_TELEVISION) {
3563 startSearch(null, false, null, false);
3571 * During the onSearchRequested() callbacks, this function will return the
3572 * {@link SearchEvent} that triggered the callback, if it exists.
3574 * @return SearchEvent The SearchEvent that triggered the {@link
3575 * #onSearchRequested} callback.
3577 public final SearchEvent getSearchEvent() {
3578 return mSearchEvent;
3582 * This hook is called to launch the search UI.
3584 * <p>It is typically called from onSearchRequested(), either directly from
3585 * Activity.onSearchRequested() or from an overridden version in any given
3586 * Activity. If your goal is simply to activate search, it is preferred to call
3587 * onSearchRequested(), which may have been overridden elsewhere in your Activity. If your goal
3588 * is to inject specific data such as context data, it is preferred to <i>override</i>
3589 * onSearchRequested(), so that any callers to it will benefit from the override.
3591 * @param initialQuery Any non-null non-empty string will be inserted as
3592 * pre-entered text in the search query box.
3593 * @param selectInitialQuery If true, the initial query will be preselected, which means that
3594 * any further typing will replace it. This is useful for cases where an entire pre-formed
3595 * query is being inserted. If false, the selection point will be placed at the end of the
3596 * inserted query. This is useful when the inserted query is text that the user entered,
3597 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
3598 * if initialQuery is a non-empty string.</i>
3599 * @param appSearchData An application can insert application-specific
3600 * context here, in order to improve quality or specificity of its own
3601 * searches. This data will be returned with SEARCH intent(s). Null if
3602 * no extra data is required.
3603 * @param globalSearch If false, this will only launch the search that has been specifically
3604 * defined by the application (which is usually defined as a local search). If no default
3605 * search is defined in the current application or activity, global search will be launched.
3606 * If true, this will always launch a platform-global (e.g. web-based) search instead.
3608 * @see android.app.SearchManager
3609 * @see #onSearchRequested
3611 public void startSearch(@Nullable String initialQuery, boolean selectInitialQuery,
3612 @Nullable Bundle appSearchData, boolean globalSearch) {
3613 ensureSearchManager();
3614 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
3615 appSearchData, globalSearch);
3619 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
3620 * the search dialog. Made available for testing purposes.
3622 * @param query The query to trigger. If empty, the request will be ignored.
3623 * @param appSearchData An application can insert application-specific
3624 * context here, in order to improve quality or specificity of its own
3625 * searches. This data will be returned with SEARCH intent(s). Null if
3626 * no extra data is required.
3628 public void triggerSearch(String query, @Nullable Bundle appSearchData) {
3629 ensureSearchManager();
3630 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
3634 * Request that key events come to this activity. Use this if your
3635 * activity has no views with focus, but the activity still wants
3636 * a chance to process key events.
3638 * @see android.view.Window#takeKeyEvents
3640 public void takeKeyEvents(boolean get) {
3641 getWindow().takeKeyEvents(get);
3645 * Enable extended window features. This is a convenience for calling
3646 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
3648 * @param featureId The desired feature as defined in
3649 * {@link android.view.Window}.
3650 * @return Returns true if the requested feature is supported and now
3653 * @see android.view.Window#requestFeature
3655 public final boolean requestWindowFeature(int featureId) {
3656 return getWindow().requestFeature(featureId);
3660 * Convenience for calling
3661 * {@link android.view.Window#setFeatureDrawableResource}.
3663 public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) {
3664 getWindow().setFeatureDrawableResource(featureId, resId);
3668 * Convenience for calling
3669 * {@link android.view.Window#setFeatureDrawableUri}.
3671 public final void setFeatureDrawableUri(int featureId, Uri uri) {
3672 getWindow().setFeatureDrawableUri(featureId, uri);
3676 * Convenience for calling
3677 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
3679 public final void setFeatureDrawable(int featureId, Drawable drawable) {
3680 getWindow().setFeatureDrawable(featureId, drawable);
3684 * Convenience for calling
3685 * {@link android.view.Window#setFeatureDrawableAlpha}.
3687 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
3688 getWindow().setFeatureDrawableAlpha(featureId, alpha);
3692 * Convenience for calling
3693 * {@link android.view.Window#getLayoutInflater}.
3696 public LayoutInflater getLayoutInflater() {
3697 return getWindow().getLayoutInflater();
3701 * Returns a {@link MenuInflater} with this context.
3704 public MenuInflater getMenuInflater() {
3705 // Make sure that action views can get an appropriate theme.
3706 if (mMenuInflater == null) {
3707 initWindowDecorActionBar();
3708 if (mActionBar != null) {
3709 mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this);
3711 mMenuInflater = new MenuInflater(this);
3714 return mMenuInflater;
3718 protected void onApplyThemeResource(Resources.Theme theme, @StyleRes int resid,
3720 if (mParent == null) {
3721 super.onApplyThemeResource(theme, resid, first);
3724 theme.setTo(mParent.getTheme());
3725 } catch (Exception e) {
3728 theme.applyStyle(resid, false);
3731 // Get the primary color and update the TaskDescription for this activity
3732 if (theme != null) {
3733 TypedArray a = theme.obtainStyledAttributes(com.android.internal.R.styleable.Theme);
3734 int colorPrimary = a.getColor(com.android.internal.R.styleable.Theme_colorPrimary, 0);
3736 if (colorPrimary != 0) {
3737 ActivityManager.TaskDescription v = new ActivityManager.TaskDescription(null, null,
3739 setTaskDescription(v);
3745 * Requests permissions to be granted to this application. These permissions
3746 * must be requested in your manifest, they should not be granted to your app,
3747 * and they should have protection level {@link android.content.pm.PermissionInfo
3748 * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by
3749 * the platform or a third-party app.
3751 * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
3752 * are granted at install time if requested in the manifest. Signature permissions
3753 * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
3754 * install time if requested in the manifest and the signature of your app matches
3755 * the signature of the app declaring the permissions.
3758 * If your app does not have the requested permissions the user will be presented
3759 * with UI for accepting them. After the user has accepted or rejected the
3760 * requested permissions you will receive a callback on {@link
3761 * #onRequestPermissionsResult(int, String[], int[])} reporting whether the
3762 * permissions were granted or not.
3765 * Note that requesting a permission does not guarantee it will be granted and
3766 * your app should be able to run without having this permission.
3769 * This method may start an activity allowing the user to choose which permissions
3770 * to grant and which to reject. Hence, you should be prepared that your activity
3771 * may be paused and resumed. Further, granting some permissions may require
3772 * a restart of you application. In such a case, the system will recreate the
3773 * activity stack before delivering the result to {@link
3774 * #onRequestPermissionsResult(int, String[], int[])}.
3777 * When checking whether you have a permission you should use {@link
3778 * #checkSelfPermission(String)}.
3781 * You cannot request a permission if your activity sets {@link
3782 * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
3783 * <code>true</code> because in this case the activity would not receive
3784 * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}.
3787 * A sample permissions request looks like this:
3790 * private void showContacts() {
3791 * if (checkSelfPermission(Manifest.permission.READ_CONTACTS)
3792 * != PackageManager.PERMISSION_GRANTED) {
3793 * requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
3794 * PERMISSIONS_REQUEST_READ_CONTACTS);
3800 * {@literal @}Override
3801 * public void onRequestPermissionsResult(int requestCode, String[] permissions,
3802 * int[] grantResults) {
3803 * if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS
3804 * && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
3810 * @param permissions The requested permissions.
3811 * @param requestCode Application specific request code to match with a result
3812 * reported to {@link #onRequestPermissionsResult(int, String[], int[])}.
3815 * @see #onRequestPermissionsResult(int, String[], int[])
3816 * @see #checkSelfPermission(String)
3817 * @see #shouldShowRequestPermissionRationale(String)
3819 public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
3820 if (mHasCurrentPermissionsRequest) {
3821 Log.w(TAG, "Can reqeust only one set of permissions at a time");
3822 // Dispatch the callback with empty arrays which means a cancellation.
3823 onRequestPermissionsResult(requestCode, new String[0], new int[0]);
3826 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
3827 startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
3828 mHasCurrentPermissionsRequest = true;
3832 * Callback for the result from requesting permissions. This method
3833 * is invoked for every call on {@link #requestPermissions(String[], int)}.
3835 * <strong>Note:</strong> It is possible that the permissions request interaction
3836 * with the user is interrupted. In this case you will receive empty permissions
3837 * and results arrays which should be treated as a cancellation.
3840 * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
3841 * @param permissions The requested permissions. Never null.
3842 * @param grantResults The grant results for the corresponding permissions
3843 * which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
3844 * or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
3846 * @see #requestPermissions(String[], int)
3848 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
3849 @NonNull int[] grantResults) {
3850 /* callback - no nothing */
3854 * Gets whether you should show UI with rationale for requesting a permission.
3855 * You should do this only if you do not have the permission and the context in
3856 * which the permission is requested does not clearly communicate to the user
3857 * what would be the benefit from granting this permission.
3859 * For example, if you write a camera app, requesting the camera permission
3860 * would be expected by the user and no rationale for why it is requested is
3861 * needed. If however, the app needs location for tagging photos then a non-tech
3862 * savvy user may wonder how location is related to taking photos. In this case
3863 * you may choose to show UI with rationale of requesting this permission.
3866 * @param permission A permission your app wants to request.
3867 * @return Whether you can show permission rationale UI.
3869 * @see #checkSelfPermission(String)
3870 * @see #requestPermissions(String[], int)
3871 * @see #onRequestPermissionsResult(int, String[], int[])
3873 public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
3874 return getPackageManager().shouldShowRequestPermissionRationale(permission);
3878 * Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
3881 * @param intent The intent to start.
3882 * @param requestCode If >= 0, this code will be returned in
3883 * onActivityResult() when the activity exits.
3885 * @throws android.content.ActivityNotFoundException
3887 * @see #startActivity
3889 public void startActivityForResult(Intent intent, int requestCode) {
3890 startActivityForResult(intent, requestCode, null);
3894 * Launch an activity for which you would like a result when it finished.
3895 * When this activity exits, your
3896 * onActivityResult() method will be called with the given requestCode.
3897 * Using a negative requestCode is the same as calling
3898 * {@link #startActivity} (the activity is not launched as a sub-activity).
3900 * <p>Note that this method should only be used with Intent protocols
3901 * that are defined to return a result. In other protocols (such as
3902 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3903 * not get the result when you expect. For example, if the activity you
3904 * are launching uses the singleTask launch mode, it will not run in your
3905 * task and thus you will immediately receive a cancel result.
3907 * <p>As a special case, if you call startActivityForResult() with a requestCode
3908 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3909 * activity, then your window will not be displayed until a result is
3910 * returned back from the started activity. This is to avoid visible
3911 * flickering when redirecting to another activity.
3913 * <p>This method throws {@link android.content.ActivityNotFoundException}
3914 * if there was no Activity found to run the given Intent.
3916 * @param intent The intent to start.
3917 * @param requestCode If >= 0, this code will be returned in
3918 * onActivityResult() when the activity exits.
3919 * @param options Additional options for how the Activity should be started.
3920 * See {@link android.content.Context#startActivity(Intent, Bundle)
3921 * Context.startActivity(Intent, Bundle)} for more details.
3923 * @throws android.content.ActivityNotFoundException
3925 * @see #startActivity
3927 public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
3928 if (mParent == null) {
3929 Instrumentation.ActivityResult ar =
3930 mInstrumentation.execStartActivity(
3931 this, mMainThread.getApplicationThread(), mToken, this,
3932 intent, requestCode, options);
3934 mMainThread.sendActivityResult(
3935 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3936 ar.getResultData());
3938 if (requestCode >= 0) {
3939 // If this start is requesting a result, we can avoid making
3940 // the activity visible until the result is received. Setting
3941 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3942 // activity hidden during this time, to avoid flickering.
3943 // This can only be done when a result is requested because
3944 // that guarantees we will get information back when the
3945 // activity is finished, no matter what happens to it.
3946 mStartedActivity = true;
3949 cancelInputsAndStartExitTransition(options);
3950 // TODO Consider clearing/flushing other event sources and events for child windows.
3952 if (options != null) {
3953 mParent.startActivityFromChild(this, intent, requestCode, options);
3955 // Note we want to go through this method for compatibility with
3956 // existing applications that may have overridden it.
3957 mParent.startActivityFromChild(this, intent, requestCode);
3963 * Cancels pending inputs and if an Activity Transition is to be run, starts the transition.
3965 * @param options The ActivityOptions bundle used to start an Activity.
3967 private void cancelInputsAndStartExitTransition(Bundle options) {
3968 final View decor = mWindow != null ? mWindow.peekDecorView() : null;
3969 if (decor != null) {
3970 decor.cancelPendingInputEvents();
3972 if (options != null && !isTopOfTask()) {
3973 mActivityTransitionState.startExitOutTransition(this, options);
3978 * @hide Implement to provide correct calling token.
3980 public void startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user) {
3981 startActivityForResultAsUser(intent, requestCode, null, user);
3985 * @hide Implement to provide correct calling token.
3987 public void startActivityForResultAsUser(Intent intent, int requestCode,
3988 @Nullable Bundle options, UserHandle user) {
3989 if (mParent != null) {
3990 throw new RuntimeException("Can't be called from a child");
3992 Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
3993 this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode,
3996 mMainThread.sendActivityResult(
3997 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
3999 if (requestCode >= 0) {
4000 // If this start is requesting a result, we can avoid making
4001 // the activity visible until the result is received. Setting
4002 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4003 // activity hidden during this time, to avoid flickering.
4004 // This can only be done when a result is requested because
4005 // that guarantees we will get information back when the
4006 // activity is finished, no matter what happens to it.
4007 mStartedActivity = true;
4010 cancelInputsAndStartExitTransition(options);
4014 * @hide Implement to provide correct calling token.
4016 public void startActivityAsUser(Intent intent, UserHandle user) {
4017 startActivityAsUser(intent, null, user);
4021 * @hide Implement to provide correct calling token.
4023 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
4024 if (mParent != null) {
4025 throw new RuntimeException("Can't be called from a child");
4027 Instrumentation.ActivityResult ar =
4028 mInstrumentation.execStartActivity(
4029 this, mMainThread.getApplicationThread(), mToken, this,
4030 intent, -1, options, user);
4032 mMainThread.sendActivityResult(
4033 mToken, mEmbeddedID, -1, ar.getResultCode(),
4034 ar.getResultData());
4036 cancelInputsAndStartExitTransition(options);
4040 * Start a new activity as if it was started by the activity that started our
4041 * current activity. This is for the resolver and chooser activities, which operate
4042 * as intermediaries that dispatch their intent to the target the user selects -- to
4043 * do this, they must perform all security checks including permission grants as if
4044 * their launch had come from the original activity.
4045 * @param intent The Intent to start.
4046 * @param options ActivityOptions or null.
4047 * @param ignoreTargetSecurity If true, the activity manager will not check whether the
4048 * caller it is doing the start is, is actually allowed to start the target activity.
4049 * If you set this to true, you must set an explicit component in the Intent and do any
4050 * appropriate security checks yourself.
4051 * @param userId The user the new activity should run as.
4054 public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
4055 boolean ignoreTargetSecurity, int userId) {
4056 if (mParent != null) {
4057 throw new RuntimeException("Can't be called from a child");
4059 Instrumentation.ActivityResult ar =
4060 mInstrumentation.execStartActivityAsCaller(
4061 this, mMainThread.getApplicationThread(), mToken, this,
4062 intent, -1, options, ignoreTargetSecurity, userId);
4064 mMainThread.sendActivityResult(
4065 mToken, mEmbeddedID, -1, ar.getResultCode(),
4066 ar.getResultData());
4068 cancelInputsAndStartExitTransition(options);
4072 * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
4073 * Intent, int, int, int, Bundle)} with no options.
4075 * @param intent The IntentSender to launch.
4076 * @param requestCode If >= 0, this code will be returned in
4077 * onActivityResult() when the activity exits.
4078 * @param fillInIntent If non-null, this will be provided as the
4079 * intent parameter to {@link IntentSender#sendIntent}.
4080 * @param flagsMask Intent flags in the original IntentSender that you
4081 * would like to change.
4082 * @param flagsValues Desired values for any bits set in
4083 * <var>flagsMask</var>
4084 * @param extraFlags Always set to 0.
4086 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4087 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4088 throws IntentSender.SendIntentException {
4089 startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
4090 flagsValues, extraFlags, null);
4094 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
4095 * to use a IntentSender to describe the activity to be started. If
4096 * the IntentSender is for an activity, that activity will be started
4097 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
4098 * here; otherwise, its associated action will be executed (such as
4099 * sending a broadcast) as if you had called
4100 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
4102 * @param intent The IntentSender to launch.
4103 * @param requestCode If >= 0, this code will be returned in
4104 * onActivityResult() when the activity exits.
4105 * @param fillInIntent If non-null, this will be provided as the
4106 * intent parameter to {@link IntentSender#sendIntent}.
4107 * @param flagsMask Intent flags in the original IntentSender that you
4108 * would like to change.
4109 * @param flagsValues Desired values for any bits set in
4110 * <var>flagsMask</var>
4111 * @param extraFlags Always set to 0.
4112 * @param options Additional options for how the Activity should be started.
4113 * See {@link android.content.Context#startActivity(Intent, Bundle)
4114 * Context.startActivity(Intent, Bundle)} for more details. If options
4115 * have also been supplied by the IntentSender, options given here will
4116 * override any that conflict with those given by the IntentSender.
4118 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4119 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4120 Bundle options) throws IntentSender.SendIntentException {
4121 if (mParent == null) {
4122 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
4123 flagsMask, flagsValues, this, options);
4124 } else if (options != null) {
4125 mParent.startIntentSenderFromChild(this, intent, requestCode,
4126 fillInIntent, flagsMask, flagsValues, extraFlags, options);
4128 // Note we want to go through this call for compatibility with
4129 // existing applications that may have overridden the method.
4130 mParent.startIntentSenderFromChild(this, intent, requestCode,
4131 fillInIntent, flagsMask, flagsValues, extraFlags);
4135 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
4136 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity,
4138 throws IntentSender.SendIntentException {
4140 String resolvedType = null;
4141 if (fillInIntent != null) {
4142 fillInIntent.migrateExtraStreamToClipData();
4143 fillInIntent.prepareToLeaveProcess();
4144 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
4146 int result = ActivityManagerNative.getDefault()
4147 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
4148 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
4149 requestCode, flagsMask, flagsValues, options);
4150 if (result == ActivityManager.START_CANCELED) {
4151 throw new IntentSender.SendIntentException();
4153 Instrumentation.checkStartActivityResult(result, null);
4154 } catch (RemoteException e) {
4156 if (requestCode >= 0) {
4157 // If this start is requesting a result, we can avoid making
4158 // the activity visible until the result is received. Setting
4159 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4160 // activity hidden during this time, to avoid flickering.
4161 // This can only be done when a result is requested because
4162 // that guarantees we will get information back when the
4163 // activity is finished, no matter what happens to it.
4164 mStartedActivity = true;
4169 * Same as {@link #startActivity(Intent, Bundle)} with no options
4172 * @param intent The intent to start.
4174 * @throws android.content.ActivityNotFoundException
4176 * @see {@link #startActivity(Intent, Bundle)}
4177 * @see #startActivityForResult
4180 public void startActivity(Intent intent) {
4181 this.startActivity(intent, null);
4185 * Launch a new activity. You will not receive any information about when
4186 * the activity exits. This implementation overrides the base version,
4187 * providing information about
4188 * the activity performing the launch. Because of this additional
4189 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4190 * required; if not specified, the new activity will be added to the
4191 * task of the caller.
4193 * <p>This method throws {@link android.content.ActivityNotFoundException}
4194 * if there was no Activity found to run the given Intent.
4196 * @param intent The intent to start.
4197 * @param options Additional options for how the Activity should be started.
4198 * See {@link android.content.Context#startActivity(Intent, Bundle)
4199 * Context.startActivity(Intent, Bundle)} for more details.
4201 * @throws android.content.ActivityNotFoundException
4203 * @see {@link #startActivity(Intent)}
4204 * @see #startActivityForResult
4207 public void startActivity(Intent intent, @Nullable Bundle options) {
4208 if (options != null) {
4209 startActivityForResult(intent, -1, options);
4211 // Note we want to go through this call for compatibility with
4212 // applications that may have overridden the method.
4213 startActivityForResult(intent, -1);
4218 * Same as {@link #startActivities(Intent[], Bundle)} with no options
4221 * @param intents The intents to start.
4223 * @throws android.content.ActivityNotFoundException
4225 * @see {@link #startActivities(Intent[], Bundle)}
4226 * @see #startActivityForResult
4229 public void startActivities(Intent[] intents) {
4230 startActivities(intents, null);
4234 * Launch a new activity. You will not receive any information about when
4235 * the activity exits. This implementation overrides the base version,
4236 * providing information about
4237 * the activity performing the launch. Because of this additional
4238 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4239 * required; if not specified, the new activity will be added to the
4240 * task of the caller.
4242 * <p>This method throws {@link android.content.ActivityNotFoundException}
4243 * if there was no Activity found to run the given Intent.
4245 * @param intents The intents to start.
4246 * @param options Additional options for how the Activity should be started.
4247 * See {@link android.content.Context#startActivity(Intent, Bundle)
4248 * Context.startActivity(Intent, Bundle)} for more details.
4250 * @throws android.content.ActivityNotFoundException
4252 * @see {@link #startActivities(Intent[])}
4253 * @see #startActivityForResult
4256 public void startActivities(Intent[] intents, @Nullable Bundle options) {
4257 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
4258 mToken, this, intents, options);
4262 * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
4265 * @param intent The IntentSender to launch.
4266 * @param fillInIntent If non-null, this will be provided as the
4267 * intent parameter to {@link IntentSender#sendIntent}.
4268 * @param flagsMask Intent flags in the original IntentSender that you
4269 * would like to change.
4270 * @param flagsValues Desired values for any bits set in
4271 * <var>flagsMask</var>
4272 * @param extraFlags Always set to 0.
4274 public void startIntentSender(IntentSender intent,
4275 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4276 throws IntentSender.SendIntentException {
4277 startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
4282 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
4284 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
4285 * for more information.
4287 * @param intent The IntentSender to launch.
4288 * @param fillInIntent If non-null, this will be provided as the
4289 * intent parameter to {@link IntentSender#sendIntent}.
4290 * @param flagsMask Intent flags in the original IntentSender that you
4291 * would like to change.
4292 * @param flagsValues Desired values for any bits set in
4293 * <var>flagsMask</var>
4294 * @param extraFlags Always set to 0.
4295 * @param options Additional options for how the Activity should be started.
4296 * See {@link android.content.Context#startActivity(Intent, Bundle)
4297 * Context.startActivity(Intent, Bundle)} for more details. If options
4298 * have also been supplied by the IntentSender, options given here will
4299 * override any that conflict with those given by the IntentSender.
4301 public void startIntentSender(IntentSender intent,
4302 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4303 Bundle options) throws IntentSender.SendIntentException {
4304 if (options != null) {
4305 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4306 flagsValues, extraFlags, options);
4308 // Note we want to go through this call for compatibility with
4309 // applications that may have overridden the method.
4310 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4311 flagsValues, extraFlags);
4316 * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
4319 * @param intent The intent to start.
4320 * @param requestCode If >= 0, this code will be returned in
4321 * onActivityResult() when the activity exits, as described in
4322 * {@link #startActivityForResult}.
4324 * @return If a new activity was launched then true is returned; otherwise
4325 * false is returned and you must handle the Intent yourself.
4327 * @see #startActivity
4328 * @see #startActivityForResult
4330 public boolean startActivityIfNeeded(@NonNull Intent intent, int requestCode) {
4331 return startActivityIfNeeded(intent, requestCode, null);
4335 * A special variation to launch an activity only if a new activity
4336 * instance is needed to handle the given Intent. In other words, this is
4337 * just like {@link #startActivityForResult(Intent, int)} except: if you are
4338 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
4339 * singleTask or singleTop
4340 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
4342 * that handles <var>intent</var> is the same as your currently running
4343 * activity, then a new instance is not needed. In this case, instead of
4344 * the normal behavior of calling {@link #onNewIntent} this function will
4345 * return and you can handle the Intent yourself.
4347 * <p>This function can only be called from a top-level activity; if it is
4348 * called from a child activity, a runtime exception will be thrown.
4350 * @param intent The intent to start.
4351 * @param requestCode If >= 0, this code will be returned in
4352 * onActivityResult() when the activity exits, as described in
4353 * {@link #startActivityForResult}.
4354 * @param options Additional options for how the Activity should be started.
4355 * See {@link android.content.Context#startActivity(Intent, Bundle)
4356 * Context.startActivity(Intent, Bundle)} for more details.
4358 * @return If a new activity was launched then true is returned; otherwise
4359 * false is returned and you must handle the Intent yourself.
4361 * @see #startActivity
4362 * @see #startActivityForResult
4364 public boolean startActivityIfNeeded(@NonNull Intent intent, int requestCode,
4365 @Nullable Bundle options) {
4366 if (mParent == null) {
4367 int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
4369 Uri referrer = onProvideReferrer();
4370 if (referrer != null) {
4371 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4373 intent.migrateExtraStreamToClipData();
4374 intent.prepareToLeaveProcess();
4375 result = ActivityManagerNative.getDefault()
4376 .startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
4377 intent, intent.resolveTypeIfNeeded(getContentResolver()), mToken,
4378 mEmbeddedID, requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4380 } catch (RemoteException e) {
4384 Instrumentation.checkStartActivityResult(result, intent);
4386 if (requestCode >= 0) {
4387 // If this start is requesting a result, we can avoid making
4388 // the activity visible until the result is received. Setting
4389 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4390 // activity hidden during this time, to avoid flickering.
4391 // This can only be done when a result is requested because
4392 // that guarantees we will get information back when the
4393 // activity is finished, no matter what happens to it.
4394 mStartedActivity = true;
4396 return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
4399 throw new UnsupportedOperationException(
4400 "startActivityIfNeeded can only be called from a top-level activity");
4404 * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
4407 * @param intent The intent to dispatch to the next activity. For
4408 * correct behavior, this must be the same as the Intent that started
4409 * your own activity; the only changes you can make are to the extras
4412 * @return Returns a boolean indicating whether there was another Activity
4413 * to start: true if there was a next activity to start, false if there
4414 * wasn't. In general, if true is returned you will then want to call
4415 * finish() on yourself.
4417 public boolean startNextMatchingActivity(@NonNull Intent intent) {
4418 return startNextMatchingActivity(intent, null);
4422 * Special version of starting an activity, for use when you are replacing
4423 * other activity components. You can use this to hand the Intent off
4424 * to the next Activity that can handle it. You typically call this in
4425 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
4427 * @param intent The intent to dispatch to the next activity. For
4428 * correct behavior, this must be the same as the Intent that started
4429 * your own activity; the only changes you can make are to the extras
4431 * @param options Additional options for how the Activity should be started.
4432 * See {@link android.content.Context#startActivity(Intent, Bundle)
4433 * Context.startActivity(Intent, Bundle)} for more details.
4435 * @return Returns a boolean indicating whether there was another Activity
4436 * to start: true if there was a next activity to start, false if there
4437 * wasn't. In general, if true is returned you will then want to call
4438 * finish() on yourself.
4440 public boolean startNextMatchingActivity(@NonNull Intent intent, @Nullable Bundle options) {
4441 if (mParent == null) {
4443 intent.migrateExtraStreamToClipData();
4444 intent.prepareToLeaveProcess();
4445 return ActivityManagerNative.getDefault()
4446 .startNextMatchingActivity(mToken, intent, options);
4447 } catch (RemoteException e) {
4453 throw new UnsupportedOperationException(
4454 "startNextMatchingActivity can only be called from a top-level activity");
4458 * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
4461 * @param child The activity making the call.
4462 * @param intent The intent to start.
4463 * @param requestCode Reply request code. < 0 if reply is not requested.
4465 * @throws android.content.ActivityNotFoundException
4467 * @see #startActivity
4468 * @see #startActivityForResult
4470 public void startActivityFromChild(@NonNull Activity child, Intent intent,
4472 startActivityFromChild(child, intent, requestCode, null);
4476 * This is called when a child activity of this one calls its
4477 * {@link #startActivity} or {@link #startActivityForResult} method.
4479 * <p>This method throws {@link android.content.ActivityNotFoundException}
4480 * if there was no Activity found to run the given Intent.
4482 * @param child The activity making the call.
4483 * @param intent The intent to start.
4484 * @param requestCode Reply request code. < 0 if reply is not requested.
4485 * @param options Additional options for how the Activity should be started.
4486 * See {@link android.content.Context#startActivity(Intent, Bundle)
4487 * Context.startActivity(Intent, Bundle)} for more details.
4489 * @throws android.content.ActivityNotFoundException
4491 * @see #startActivity
4492 * @see #startActivityForResult
4494 public void startActivityFromChild(@NonNull Activity child, Intent intent,
4495 int requestCode, @Nullable Bundle options) {
4496 Instrumentation.ActivityResult ar =
4497 mInstrumentation.execStartActivity(
4498 this, mMainThread.getApplicationThread(), mToken, child,
4499 intent, requestCode, options);
4501 mMainThread.sendActivityResult(
4502 mToken, child.mEmbeddedID, requestCode,
4503 ar.getResultCode(), ar.getResultData());
4505 cancelInputsAndStartExitTransition(options);
4509 * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
4512 * @param fragment The fragment making the call.
4513 * @param intent The intent to start.
4514 * @param requestCode Reply request code. < 0 if reply is not requested.
4516 * @throws android.content.ActivityNotFoundException
4518 * @see Fragment#startActivity
4519 * @see Fragment#startActivityForResult
4521 public void startActivityFromFragment(@NonNull Fragment fragment, Intent intent,
4523 startActivityFromFragment(fragment, intent, requestCode, null);
4527 * This is called when a Fragment in this activity calls its
4528 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
4531 * <p>This method throws {@link android.content.ActivityNotFoundException}
4532 * if there was no Activity found to run the given Intent.
4534 * @param fragment The fragment making the call.
4535 * @param intent The intent to start.
4536 * @param requestCode Reply request code. < 0 if reply is not requested.
4537 * @param options Additional options for how the Activity should be started.
4538 * See {@link android.content.Context#startActivity(Intent, Bundle)
4539 * Context.startActivity(Intent, Bundle)} for more details.
4541 * @throws android.content.ActivityNotFoundException
4543 * @see Fragment#startActivity
4544 * @see Fragment#startActivityForResult
4546 public void startActivityFromFragment(@NonNull Fragment fragment, Intent intent,
4547 int requestCode, @Nullable Bundle options) {
4548 startActivityForResult(fragment.mWho, intent, requestCode, options);
4555 public void startActivityForResult(
4556 String who, Intent intent, int requestCode, @Nullable Bundle options) {
4557 Uri referrer = onProvideReferrer();
4558 if (referrer != null) {
4559 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4561 Instrumentation.ActivityResult ar =
4562 mInstrumentation.execStartActivity(
4563 this, mMainThread.getApplicationThread(), mToken, who,
4564 intent, requestCode, options);
4566 mMainThread.sendActivityResult(
4567 mToken, who, requestCode,
4568 ar.getResultCode(), ar.getResultData());
4570 cancelInputsAndStartExitTransition(options);
4577 public boolean canStartActivityForResult() {
4582 * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
4583 * int, Intent, int, int, int, Bundle)} with no options.
4585 public void startIntentSenderFromChild(Activity child, IntentSender intent,
4586 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
4588 throws IntentSender.SendIntentException {
4589 startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
4590 flagsMask, flagsValues, extraFlags, null);
4594 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
4595 * taking a IntentSender; see
4596 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
4597 * for more information.
4599 public void startIntentSenderFromChild(Activity child, IntentSender intent,
4600 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
4601 int extraFlags, @Nullable Bundle options)
4602 throws IntentSender.SendIntentException {
4603 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
4604 flagsMask, flagsValues, child, options);
4608 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
4609 * or {@link #finish} to specify an explicit transition animation to
4612 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
4613 * to using this with starting activities is to supply the desired animation
4614 * information through a {@link ActivityOptions} bundle to
4615 * {@link #startActivity(Intent, Bundle) or a related function. This allows
4616 * you to specify a custom animation even when starting an activity from
4617 * outside the context of the current top activity.
4619 * @param enterAnim A resource ID of the animation resource to use for
4620 * the incoming activity. Use 0 for no animation.
4621 * @param exitAnim A resource ID of the animation resource to use for
4622 * the outgoing activity. Use 0 for no animation.
4624 public void overridePendingTransition(int enterAnim, int exitAnim) {
4626 ActivityManagerNative.getDefault().overridePendingTransition(
4627 mToken, getPackageName(), enterAnim, exitAnim);
4628 } catch (RemoteException e) {
4633 * Call this to set the result that your activity will return to its
4636 * @param resultCode The result code to propagate back to the originating
4637 * activity, often RESULT_CANCELED or RESULT_OK
4639 * @see #RESULT_CANCELED
4641 * @see #RESULT_FIRST_USER
4642 * @see #setResult(int, Intent)
4644 public final void setResult(int resultCode) {
4645 synchronized (this) {
4646 mResultCode = resultCode;
4652 * Call this to set the result that your activity will return to its
4655 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
4656 * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
4657 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4658 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the
4659 * Activity receiving the result access to the specific URIs in the Intent.
4660 * Access will remain until the Activity has finished (it will remain across the hosting
4661 * process being killed and other temporary destruction) and will be added
4662 * to any existing set of URI permissions it already holds.
4664 * @param resultCode The result code to propagate back to the originating
4665 * activity, often RESULT_CANCELED or RESULT_OK
4666 * @param data The data to propagate back to the originating activity.
4668 * @see #RESULT_CANCELED
4670 * @see #RESULT_FIRST_USER
4671 * @see #setResult(int)
4673 public final void setResult(int resultCode, Intent data) {
4674 synchronized (this) {
4675 mResultCode = resultCode;
4681 * Return information about who launched this activity. If the launching Intent
4682 * contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
4683 * that will be returned as-is; otherwise, if known, an
4684 * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
4685 * package name that started the Intent will be returned. This may return null if no
4686 * referrer can be identified -- it is neither explicitly specified, nor is it known which
4687 * application package was involved.
4689 * <p>If called while inside the handling of {@link #onNewIntent}, this function will
4690 * return the referrer that submitted that new intent to the activity. Otherwise, it
4691 * always returns the referrer of the original Intent.</p>
4693 * <p>Note that this is <em>not</em> a security feature -- you can not trust the
4694 * referrer information, applications can spoof it.</p>
4697 public Uri getReferrer() {
4698 Intent intent = getIntent();
4699 Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
4700 if (referrer != null) {
4703 String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
4704 if (referrerName != null) {
4705 return Uri.parse(referrerName);
4707 if (mReferrer != null) {
4708 return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
4714 * Override to generate the desired referrer for the content currently being shown
4715 * by the app. The default implementation returns null, meaning the referrer will simply
4716 * be the android-app: of the package name of this activity. Return a non-null Uri to
4717 * have that supplied as the {@link Intent#EXTRA_REFERRER} of any activities started from it.
4719 public Uri onProvideReferrer() {
4724 * Return the name of the package that invoked this activity. This is who
4725 * the data in {@link #setResult setResult()} will be sent to. You can
4726 * use this information to validate that the recipient is allowed to
4729 * <p class="note">Note: if the calling activity is not expecting a result (that is it
4730 * did not use the {@link #startActivityForResult}
4731 * form that includes a request code), then the calling package will be
4734 * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
4735 * the result from this method was unstable. If the process hosting the calling
4736 * package was no longer running, it would return null instead of the proper package
4737 * name. You can use {@link #getCallingActivity()} and retrieve the package name
4738 * from that instead.</p>
4740 * @return The package of the activity that will receive your
4741 * reply, or null if none.
4744 public String getCallingPackage() {
4746 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
4747 } catch (RemoteException e) {
4753 * Return the name of the activity that invoked this activity. This is
4754 * who the data in {@link #setResult setResult()} will be sent to. You
4755 * can use this information to validate that the recipient is allowed to
4758 * <p class="note">Note: if the calling activity is not expecting a result (that is it
4759 * did not use the {@link #startActivityForResult}
4760 * form that includes a request code), then the calling package will be
4763 * @return The ComponentName of the activity that will receive your
4764 * reply, or null if none.
4767 public ComponentName getCallingActivity() {
4769 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
4770 } catch (RemoteException e) {
4776 * Control whether this activity's main window is visible. This is intended
4777 * only for the special case of an activity that is not going to show a
4778 * UI itself, but can't just finish prior to onResume() because it needs
4779 * to wait for a service binding or such. Setting this to false allows
4780 * you to prevent your UI from being shown during that time.
4782 * <p>The default value for this is taken from the
4783 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
4785 public void setVisible(boolean visible) {
4786 if (mVisibleFromClient != visible) {
4787 mVisibleFromClient = visible;
4788 if (mVisibleFromServer) {
4789 if (visible) makeVisible();
4790 else mDecor.setVisibility(View.INVISIBLE);
4795 void makeVisible() {
4796 if (!mWindowAdded) {
4797 ViewManager wm = getWindowManager();
4798 wm.addView(mDecor, getWindow().getAttributes());
4799 mWindowAdded = true;
4801 mDecor.setVisibility(View.VISIBLE);
4805 * Check to see whether this activity is in the process of finishing,
4806 * either because you called {@link #finish} on it or someone else
4807 * has requested that it finished. This is often used in
4808 * {@link #onPause} to determine whether the activity is simply pausing or
4809 * completely finishing.
4811 * @return If the activity is finishing, returns true; else returns false.
4815 public boolean isFinishing() {
4820 * Returns true if the final {@link #onDestroy()} call has been made
4821 * on the Activity, so this instance is now dead.
4823 public boolean isDestroyed() {
4828 * Check to see whether this activity is in the process of being destroyed in order to be
4829 * recreated with a new configuration. This is often used in
4830 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
4831 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
4833 * @return If the activity is being torn down in order to be recreated with a new configuration,
4834 * returns true; else returns false.
4836 public boolean isChangingConfigurations() {
4837 return mChangingConfigurations;
4841 * Cause this Activity to be recreated with a new instance. This results
4842 * in essentially the same flow as when the Activity is created due to
4843 * a configuration change -- the current instance will go through its
4844 * lifecycle to {@link #onDestroy} and a new instance then created after it.
4846 public void recreate() {
4847 if (mParent != null) {
4848 throw new IllegalStateException("Can only be called on top-level activity");
4850 if (Looper.myLooper() != mMainThread.getLooper()) {
4851 throw new IllegalStateException("Must be called from main thread");
4853 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, null, false);
4857 * Finishes the current activity and specifies whether to remove the task associated with this
4860 private void finish(boolean finishTask) {
4861 if (mParent == null) {
4864 synchronized (this) {
4865 resultCode = mResultCode;
4866 resultData = mResultData;
4868 if (false) Log.v(TAG, "Finishing self: token=" + mToken);
4870 if (resultData != null) {
4871 resultData.prepareToLeaveProcess();
4873 if (ActivityManagerNative.getDefault()
4874 .finishActivity(mToken, resultCode, resultData, finishTask)) {
4877 } catch (RemoteException e) {
4881 mParent.finishFromChild(this);
4886 * Call this when your activity is done and should be closed. The
4887 * ActivityResult is propagated back to whoever launched you via
4888 * onActivityResult().
4890 public void finish() {
4895 * Finish this activity as well as all activities immediately below it
4896 * in the current task that have the same affinity. This is typically
4897 * used when an application can be launched on to another task (such as
4898 * from an ACTION_VIEW of a content type it understands) and the user
4899 * has used the up navigation to switch out of the current task and in
4900 * to its own task. In this case, if the user has navigated down into
4901 * any other activities of the second application, all of those should
4902 * be removed from the original task as part of the task switch.
4904 * <p>Note that this finish does <em>not</em> allow you to deliver results
4905 * to the previous activity, and an exception will be thrown if you are trying
4908 public void finishAffinity() {
4909 if (mParent != null) {
4910 throw new IllegalStateException("Can not be called from an embedded activity");
4912 if (mResultCode != RESULT_CANCELED || mResultData != null) {
4913 throw new IllegalStateException("Can not be called to deliver a result");
4916 if (ActivityManagerNative.getDefault().finishActivityAffinity(mToken)) {
4919 } catch (RemoteException e) {
4925 * This is called when a child activity of this one calls its
4926 * {@link #finish} method. The default implementation simply calls
4927 * finish() on this activity (the parent), finishing the entire group.
4929 * @param child The activity making the call.
4933 public void finishFromChild(Activity child) {
4938 * Reverses the Activity Scene entry Transition and triggers the calling Activity
4939 * to reverse its exit Transition. When the exit Transition completes,
4940 * {@link #finish()} is called. If no entry Transition was used, finish() is called
4941 * immediately and the Activity exit Transition is run.
4942 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, android.util.Pair[])
4944 public void finishAfterTransition() {
4945 if (!mActivityTransitionState.startExitBackTransition(this)) {
4951 * Force finish another activity that you had previously started with
4952 * {@link #startActivityForResult}.
4954 * @param requestCode The request code of the activity that you had
4955 * given to startActivityForResult(). If there are multiple
4956 * activities started with this request code, they
4957 * will all be finished.
4959 public void finishActivity(int requestCode) {
4960 if (mParent == null) {
4962 ActivityManagerNative.getDefault()
4963 .finishSubActivity(mToken, mEmbeddedID, requestCode);
4964 } catch (RemoteException e) {
4968 mParent.finishActivityFromChild(this, requestCode);
4973 * This is called when a child activity of this one calls its
4976 * @param child The activity making the call.
4977 * @param requestCode Request code that had been used to start the
4980 public void finishActivityFromChild(@NonNull Activity child, int requestCode) {
4982 ActivityManagerNative.getDefault()
4983 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
4984 } catch (RemoteException e) {
4990 * Call this when your activity is done and should be closed and the task should be completely
4991 * removed as a part of finishing the Activity.
4993 public void finishAndRemoveTask() {
4998 * Ask that the local app instance of this activity be released to free up its memory.
4999 * This is asking for the activity to be destroyed, but does <b>not</b> finish the activity --
5000 * a new instance of the activity will later be re-created if needed due to the user
5001 * navigating back to it.
5003 * @return Returns true if the activity was in a state that it has started the process
5004 * of destroying its current instance; returns false if for any reason this could not
5005 * be done: it is currently visible to the user, it is already being destroyed, it is
5006 * being finished, it hasn't yet saved its state, etc.
5008 public boolean releaseInstance() {
5010 return ActivityManagerNative.getDefault().releaseActivityInstance(mToken);
5011 } catch (RemoteException e) {
5018 * Called when an activity you launched exits, giving you the requestCode
5019 * you started it with, the resultCode it returned, and any additional
5020 * data from it. The <var>resultCode</var> will be
5021 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
5022 * didn't return any result, or crashed during its operation.
5024 * <p>You will receive this call immediately before onResume() when your
5025 * activity is re-starting.
5027 * <p>This method is never invoked if your activity sets
5028 * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
5029 * <code>true</code>.
5031 * @param requestCode The integer request code originally supplied to
5032 * startActivityForResult(), allowing you to identify who this
5034 * @param resultCode The integer result code returned by the child activity
5035 * through its setResult().
5036 * @param data An Intent, which can return result data to the caller
5037 * (various data can be attached to Intent "extras").
5039 * @see #startActivityForResult
5040 * @see #createPendingResult
5041 * @see #setResult(int)
5043 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
5047 * Called when an activity you launched with an activity transition exposes this
5048 * Activity through a returning activity transition, giving you the resultCode
5049 * and any additional data from it. This method will only be called if the activity
5050 * set a result code other than {@link #RESULT_CANCELED} and it supports activity
5051 * transitions with {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
5053 * <p>The purpose of this function is to let the called Activity send a hint about
5054 * its state so that this underlying Activity can prepare to be exposed. A call to
5055 * this method does not guarantee that the called Activity has or will be exiting soon.
5056 * It only indicates that it will expose this Activity's Window and it has
5057 * some data to pass to prepare it.</p>
5059 * @param resultCode The integer result code returned by the child activity
5060 * through its setResult().
5061 * @param data An Intent, which can return result data to the caller
5062 * (various data can be attached to Intent "extras").
5064 public void onActivityReenter(int resultCode, Intent data) {
5068 * Create a new PendingIntent object which you can hand to others
5069 * for them to use to send result data back to your
5070 * {@link #onActivityResult} callback. The created object will be either
5071 * one-shot (becoming invalid after a result is sent back) or multiple
5072 * (allowing any number of results to be sent through it).
5074 * @param requestCode Private request code for the sender that will be
5075 * associated with the result data when it is returned. The sender can not
5076 * modify this value, allowing you to identify incoming results.
5077 * @param data Default data to supply in the result, which may be modified
5079 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
5080 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
5081 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
5082 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
5083 * or any of the flags as supported by
5084 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
5085 * of the intent that can be supplied when the actual send happens.
5087 * @return Returns an existing or new PendingIntent matching the given
5088 * parameters. May return null only if
5089 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
5092 * @see PendingIntent
5094 public PendingIntent createPendingResult(int requestCode, @NonNull Intent data,
5095 @PendingIntent.Flags int flags) {
5096 String packageName = getPackageName();
5098 data.prepareToLeaveProcess();
5099 IIntentSender target =
5100 ActivityManagerNative.getDefault().getIntentSender(
5101 ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
5102 mParent == null ? mToken : mParent.mToken,
5103 mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null,
5104 UserHandle.myUserId());
5105 return target != null ? new PendingIntent(target) : null;
5106 } catch (RemoteException e) {
5113 * Change the desired orientation of this activity. If the activity
5114 * is currently in the foreground or otherwise impacting the screen
5115 * orientation, the screen will immediately be changed (possibly causing
5116 * the activity to be restarted). Otherwise, this will be used the next
5117 * time the activity is visible.
5119 * @param requestedOrientation An orientation constant as used in
5120 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5122 public void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) {
5123 if (mParent == null) {
5125 ActivityManagerNative.getDefault().setRequestedOrientation(
5126 mToken, requestedOrientation);
5127 } catch (RemoteException e) {
5131 mParent.setRequestedOrientation(requestedOrientation);
5136 * Return the current requested orientation of the activity. This will
5137 * either be the orientation requested in its component's manifest, or
5138 * the last requested orientation given to
5139 * {@link #setRequestedOrientation(int)}.
5141 * @return Returns an orientation constant as used in
5142 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5144 @ActivityInfo.ScreenOrientation
5145 public int getRequestedOrientation() {
5146 if (mParent == null) {
5148 return ActivityManagerNative.getDefault()
5149 .getRequestedOrientation(mToken);
5150 } catch (RemoteException e) {
5154 return mParent.getRequestedOrientation();
5156 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
5160 * Return the identifier of the task this activity is in. This identifier
5161 * will remain the same for the lifetime of the activity.
5163 * @return Task identifier, an opaque integer.
5165 public int getTaskId() {
5167 return ActivityManagerNative.getDefault()
5168 .getTaskForActivity(mToken, false);
5169 } catch (RemoteException e) {
5175 * Return whether this activity is the root of a task. The root is the
5176 * first activity in a task.
5178 * @return True if this is the root activity, else false.
5180 public boolean isTaskRoot() {
5182 return ActivityManagerNative.getDefault()
5183 .getTaskForActivity(mToken, true) >= 0;
5184 } catch (RemoteException e) {
5190 * Move the task containing this activity to the back of the activity
5191 * stack. The activity's order within the task is unchanged.
5193 * @param nonRoot If false then this only works if the activity is the root
5194 * of a task; if true it will work for any activity in
5197 * @return If the task was moved (or it was already at the
5198 * back) true is returned, else false.
5200 public boolean moveTaskToBack(boolean nonRoot) {
5202 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
5204 } catch (RemoteException e) {
5211 * Returns class name for this activity with the package prefix removed.
5212 * This is the default name used to read and write settings.
5214 * @return The local class name.
5217 public String getLocalClassName() {
5218 final String pkg = getPackageName();
5219 final String cls = mComponent.getClassName();
5220 int packageLen = pkg.length();
5221 if (!cls.startsWith(pkg) || cls.length() <= packageLen
5222 || cls.charAt(packageLen) != '.') {
5225 return cls.substring(packageLen+1);
5229 * Returns complete component name of this activity.
5231 * @return Returns the complete component name for this activity
5233 public ComponentName getComponentName()
5239 * Retrieve a {@link SharedPreferences} object for accessing preferences
5240 * that are private to this activity. This simply calls the underlying
5241 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
5242 * class name as the preferences name.
5244 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
5245 * operation, {@link #MODE_WORLD_READABLE} and
5246 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
5248 * @return Returns the single SharedPreferences instance that can be used
5249 * to retrieve and modify the preference values.
5251 public SharedPreferences getPreferences(int mode) {
5252 return getSharedPreferences(getLocalClassName(), mode);
5255 private void ensureSearchManager() {
5256 if (mSearchManager != null) {
5260 mSearchManager = new SearchManager(this, null);
5264 public Object getSystemService(@ServiceName @NonNull String name) {
5265 if (getBaseContext() == null) {
5266 throw new IllegalStateException(
5267 "System services not available to Activities before onCreate()");
5270 if (WINDOW_SERVICE.equals(name)) {
5271 return mWindowManager;
5272 } else if (SEARCH_SERVICE.equals(name)) {
5273 ensureSearchManager();
5274 return mSearchManager;
5276 return super.getSystemService(name);
5280 * Change the title associated with this activity. If this is a
5281 * top-level activity, the title for its window will change. If it
5282 * is an embedded activity, the parent can do whatever it wants
5285 public void setTitle(CharSequence title) {
5287 onTitleChanged(title, mTitleColor);
5289 if (mParent != null) {
5290 mParent.onChildTitleChanged(this, title);
5295 * Change the title associated with this activity. If this is a
5296 * top-level activity, the title for its window will change. If it
5297 * is an embedded activity, the parent can do whatever it wants
5300 public void setTitle(int titleId) {
5301 setTitle(getText(titleId));
5305 * Change the color of the title associated with this activity.
5307 * This method is deprecated starting in API Level 11 and replaced by action
5308 * bar styles. For information on styling the Action Bar, read the <a
5309 * href="{@docRoot} guide/topics/ui/actionbar.html">Action Bar</a> developer
5312 * @deprecated Use action bar styles instead.
5315 public void setTitleColor(int textColor) {
5316 mTitleColor = textColor;
5317 onTitleChanged(mTitle, textColor);
5320 public final CharSequence getTitle() {
5324 public final int getTitleColor() {
5328 protected void onTitleChanged(CharSequence title, int color) {
5330 final Window win = getWindow();
5332 win.setTitle(title);
5334 win.setTitleColor(color);
5337 if (mActionBar != null) {
5338 mActionBar.setWindowTitle(title);
5343 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
5347 * Sets information describing the task with this activity for presentation inside the Recents
5348 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
5349 * are traversed in order from the topmost activity to the bottommost. The traversal continues
5350 * for each property until a suitable value is found. For each task the taskDescription will be
5351 * returned in {@link android.app.ActivityManager.TaskDescription}.
5353 * @see ActivityManager#getRecentTasks
5354 * @see android.app.ActivityManager.TaskDescription
5356 * @param taskDescription The TaskDescription properties that describe the task with this activity
5358 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
5359 ActivityManager.TaskDescription td;
5360 // Scale the icon down to something reasonable if it is provided
5361 if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
5362 final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
5363 final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size, true);
5364 td = new ActivityManager.TaskDescription(taskDescription.getLabel(), icon,
5365 taskDescription.getPrimaryColor());
5367 td = taskDescription;
5370 ActivityManagerNative.getDefault().setTaskDescription(mToken, td);
5371 } catch (RemoteException e) {
5376 * Sets the visibility of the progress bar in the title.
5378 * In order for the progress bar to be shown, the feature must be requested
5379 * via {@link #requestWindowFeature(int)}.
5381 * @param visible Whether to show the progress bars in the title.
5383 public final void setProgressBarVisibility(boolean visible) {
5384 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
5385 Window.PROGRESS_VISIBILITY_OFF);
5389 * Sets the visibility of the indeterminate progress bar in the title.
5391 * In order for the progress bar to be shown, the feature must be requested
5392 * via {@link #requestWindowFeature(int)}.
5394 * @param visible Whether to show the progress bars in the title.
5396 public final void setProgressBarIndeterminateVisibility(boolean visible) {
5397 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
5398 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
5402 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
5403 * is always indeterminate).
5405 * In order for the progress bar to be shown, the feature must be requested
5406 * via {@link #requestWindowFeature(int)}.
5408 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
5410 public final void setProgressBarIndeterminate(boolean indeterminate) {
5411 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
5412 indeterminate ? Window.PROGRESS_INDETERMINATE_ON
5413 : Window.PROGRESS_INDETERMINATE_OFF);
5417 * Sets the progress for the progress bars in the title.
5419 * In order for the progress bar to be shown, the feature must be requested
5420 * via {@link #requestWindowFeature(int)}.
5422 * @param progress The progress for the progress bar. Valid ranges are from
5423 * 0 to 10000 (both inclusive). If 10000 is given, the progress
5424 * bar will be completely filled and will fade out.
5426 public final void setProgress(int progress) {
5427 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
5431 * Sets the secondary progress for the progress bar in the title. This
5432 * progress is drawn between the primary progress (set via
5433 * {@link #setProgress(int)} and the background. It can be ideal for media
5434 * scenarios such as showing the buffering progress while the default
5435 * progress shows the play progress.
5437 * In order for the progress bar to be shown, the feature must be requested
5438 * via {@link #requestWindowFeature(int)}.
5440 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
5441 * 0 to 10000 (both inclusive).
5443 public final void setSecondaryProgress(int secondaryProgress) {
5444 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
5445 secondaryProgress + Window.PROGRESS_SECONDARY_START);
5449 * Suggests an audio stream whose volume should be changed by the hardware
5452 * The suggested audio stream will be tied to the window of this Activity.
5453 * Volume requests which are received while the Activity is in the
5454 * foreground will affect this stream.
5456 * It is not guaranteed that the hardware volume controls will always change
5457 * this stream's volume (for example, if a call is in progress, its stream's
5458 * volume may be changed instead). To reset back to the default, use
5459 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
5461 * @param streamType The type of the audio stream whose volume should be
5462 * changed by the hardware volume controls.
5464 public final void setVolumeControlStream(int streamType) {
5465 getWindow().setVolumeControlStream(streamType);
5469 * Gets the suggested audio stream whose volume should be changed by the
5470 * hardware volume controls.
5472 * @return The suggested audio stream type whose volume should be changed by
5473 * the hardware volume controls.
5474 * @see #setVolumeControlStream(int)
5476 public final int getVolumeControlStream() {
5477 return getWindow().getVolumeControlStream();
5481 * Sets a {@link MediaController} to send media keys and volume changes to.
5483 * The controller will be tied to the window of this Activity. Media key and
5484 * volume events which are received while the Activity is in the foreground
5485 * will be forwarded to the controller and used to invoke transport controls
5486 * or adjust the volume. This may be used instead of or in addition to
5487 * {@link #setVolumeControlStream} to affect a specific session instead of a
5490 * It is not guaranteed that the hardware volume controls will always change
5491 * this session's volume (for example, if a call is in progress, its
5492 * stream's volume may be changed instead). To reset back to the default use
5493 * null as the controller.
5495 * @param controller The controller for the session which should receive
5496 * media keys and volume changes.
5498 public final void setMediaController(MediaController controller) {
5499 getWindow().setMediaController(controller);
5503 * Gets the controller which should be receiving media key and volume events
5504 * while this activity is in the foreground.
5506 * @return The controller which should receive events.
5507 * @see #setMediaController(android.media.session.MediaController)
5509 public final MediaController getMediaController() {
5510 return getWindow().getMediaController();
5514 * Runs the specified action on the UI thread. If the current thread is the UI
5515 * thread, then the action is executed immediately. If the current thread is
5516 * not the UI thread, the action is posted to the event queue of the UI thread.
5518 * @param action the action to run on the UI thread
5520 public final void runOnUiThread(Runnable action) {
5521 if (Thread.currentThread() != mUiThread) {
5522 mHandler.post(action);
5529 * Standard implementation of
5530 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
5531 * inflating with the LayoutInflater returned by {@link #getSystemService}.
5532 * This implementation does nothing and is for
5533 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
5534 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
5536 * @see android.view.LayoutInflater#createView
5537 * @see android.view.Window#getLayoutInflater
5540 public View onCreateView(String name, Context context, AttributeSet attrs) {
5545 * Standard implementation of
5546 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
5547 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
5548 * This implementation handles <fragment> tags to embed fragments inside
5551 * @see android.view.LayoutInflater#createView
5552 * @see android.view.Window#getLayoutInflater
5554 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
5555 if (!"fragment".equals(name)) {
5556 return onCreateView(name, context, attrs);
5559 return mFragments.onCreateView(parent, name, context, attrs);
5563 * Print the Activity's state into the given stream. This gets invoked if
5564 * you run "adb shell dumpsys activity <activity_component_name>".
5566 * @param prefix Desired prefix to prepend at each line of output.
5567 * @param fd The raw file descriptor that the dump is being sent to.
5568 * @param writer The PrintWriter to which you should dump your state. This will be
5569 * closed for you after you return.
5570 * @param args additional arguments to the dump request.
5572 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5573 dumpInner(prefix, fd, writer, args);
5576 void dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5577 writer.print(prefix); writer.print("Local Activity ");
5578 writer.print(Integer.toHexString(System.identityHashCode(this)));
5579 writer.println(" State:");
5580 String innerPrefix = prefix + " ";
5581 writer.print(innerPrefix); writer.print("mResumed=");
5582 writer.print(mResumed); writer.print(" mStopped=");
5583 writer.print(mStopped); writer.print(" mFinished=");
5584 writer.println(mFinished);
5585 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
5586 writer.println(mChangingConfigurations);
5587 writer.print(innerPrefix); writer.print("mCurrentConfig=");
5588 writer.println(mCurrentConfig);
5590 mFragments.dumpLoaders(innerPrefix, fd, writer, args);
5591 mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args);
5592 if (mVoiceInteractor != null) {
5593 mVoiceInteractor.dump(innerPrefix, fd, writer, args);
5596 if (getWindow() != null &&
5597 getWindow().peekDecorView() != null &&
5598 getWindow().peekDecorView().getViewRootImpl() != null) {
5599 getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args);
5602 mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix);
5606 * Bit indicating that this activity is "immersive" and should not be
5607 * interrupted by notifications if possible.
5609 * This value is initially set by the manifest property
5610 * <code>android:immersive</code> but may be changed at runtime by
5611 * {@link #setImmersive}.
5613 * @see #setImmersive(boolean)
5614 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
5616 public boolean isImmersive() {
5618 return ActivityManagerNative.getDefault().isImmersive(mToken);
5619 } catch (RemoteException e) {
5625 * Indication of whether this is the highest level activity in this task. Can be used to
5626 * determine whether an activity launched by this activity was placed in the same task or
5629 * @return true if this is the topmost, non-finishing activity in its task.
5631 private boolean isTopOfTask() {
5633 return ActivityManagerNative.getDefault().isTopOfTask(mToken);
5634 } catch (RemoteException e) {
5640 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} to a
5641 * fullscreen opaque Activity.
5643 * Call this whenever the background of a translucent Activity has changed to become opaque.
5644 * Doing so will allow the {@link android.view.Surface} of the Activity behind to be released.
5646 * This call has no effect on non-translucent activities or on activities with the
5647 * {@link android.R.attr#windowIsFloating} attribute.
5649 * @see #convertToTranslucent(android.app.Activity.TranslucentConversionListener,
5651 * @see TranslucentConversionListener
5656 public void convertFromTranslucent() {
5658 mTranslucentCallback = null;
5659 if (ActivityManagerNative.getDefault().convertFromTranslucent(mToken)) {
5660 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true);
5662 } catch (RemoteException e) {
5668 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} back from
5669 * opaque to translucent following a call to {@link #convertFromTranslucent()}.
5671 * Calling this allows the Activity behind this one to be seen again. Once all such Activities
5672 * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
5673 * be called indicating that it is safe to make this activity translucent again. Until
5674 * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
5675 * behind the frontmost Activity will be indeterminate.
5677 * This call has no effect on non-translucent activities or on activities with the
5678 * {@link android.R.attr#windowIsFloating} attribute.
5680 * @param callback the method to call when all visible Activities behind this one have been
5681 * drawn and it is safe to make this Activity translucent again.
5682 * @param options activity options delivered to the activity below this one. The options
5683 * are retrieved using {@link #getActivityOptions}.
5684 * @return <code>true</code> if Window was opaque and will become translucent or
5685 * <code>false</code> if window was translucent and no change needed to be made.
5687 * @see #convertFromTranslucent()
5688 * @see TranslucentConversionListener
5693 public boolean convertToTranslucent(TranslucentConversionListener callback,
5694 ActivityOptions options) {
5695 boolean drawComplete;
5697 mTranslucentCallback = callback;
5698 mChangeCanvasToTranslucent =
5699 ActivityManagerNative.getDefault().convertToTranslucent(mToken, options);
5700 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
5701 drawComplete = true;
5702 } catch (RemoteException e) {
5703 // Make callback return as though it timed out.
5704 mChangeCanvasToTranslucent = false;
5705 drawComplete = false;
5707 if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) {
5708 // Window is already translucent.
5709 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
5711 return mChangeCanvasToTranslucent;
5715 void onTranslucentConversionComplete(boolean drawComplete) {
5716 if (mTranslucentCallback != null) {
5717 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
5718 mTranslucentCallback = null;
5720 if (mChangeCanvasToTranslucent) {
5721 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
5726 public void onNewActivityOptions(ActivityOptions options) {
5727 mActivityTransitionState.setEnterActivityOptions(this, options);
5729 mActivityTransitionState.enterReady(this);
5734 * Retrieve the ActivityOptions passed in from the launching activity or passed back
5735 * from an activity launched by this activity in its call to {@link
5736 * #convertToTranslucent(TranslucentConversionListener, ActivityOptions)}
5738 * @return The ActivityOptions passed to {@link #convertToTranslucent}.
5741 ActivityOptions getActivityOptions() {
5743 return ActivityManagerNative.getDefault().getActivityOptions(mToken);
5744 } catch (RemoteException e) {
5750 * Activities that want to remain visible behind a translucent activity above them must call
5751 * this method anytime between the start of {@link #onResume()} and the return from
5752 * {@link #onPause()}. If this call is successful then the activity will remain visible after
5753 * {@link #onPause()} is called, and is allowed to continue playing media in the background.
5755 * <p>The actions of this call are reset each time that this activity is brought to the
5756 * front. That is, every time {@link #onResume()} is called the activity will be assumed
5757 * to not have requested visible behind. Therefore, if you want this activity to continue to
5758 * be visible in the background you must call this method again.
5760 * <p>Only fullscreen opaque activities may make this call. I.e. this call is a nop
5761 * for dialog and translucent activities.
5763 * <p>Under all circumstances, the activity must stop playing and release resources prior to or
5764 * within a call to {@link #onVisibleBehindCanceled()} or if this call returns false.
5766 * <p>False will be returned any time this method is called between the return of onPause and
5767 * the next call to onResume.
5769 * @param visible true to notify the system that the activity wishes to be visible behind other
5770 * translucent activities, false to indicate otherwise. Resources must be
5771 * released when passing false to this method.
5772 * @return the resulting visibiity state. If true the activity will remain visible beyond
5773 * {@link #onPause()} if the next activity is translucent or not fullscreen. If false
5774 * then the activity may not count on being visible behind other translucent activities,
5775 * and must stop any media playback and release resources.
5776 * Returning false may occur in lieu of a call to {@link #onVisibleBehindCanceled()} so
5777 * the return value must be checked.
5779 * @see #onVisibleBehindCanceled()
5780 * @see #onBackgroundVisibleBehindChanged(boolean)
5782 public boolean requestVisibleBehind(boolean visible) {
5784 // Do not permit paused or stopped activities to do this.
5788 mVisibleBehind = ActivityManagerNative.getDefault()
5789 .requestVisibleBehind(mToken, visible) && visible;
5790 } catch (RemoteException e) {
5791 mVisibleBehind = false;
5793 return mVisibleBehind;
5797 * Called when a translucent activity over this activity is becoming opaque or another
5798 * activity is being launched. Activities that override this method must call
5799 * <code>super.onVisibleBehindCanceled()</code> or a SuperNotCalledException will be thrown.
5801 * <p>When this method is called the activity has 500 msec to release any resources it may be
5802 * using while visible in the background.
5803 * If the activity has not returned from this method in 500 msec the system will destroy
5804 * the activity and kill the process in order to recover the resources for another
5805 * process. Otherwise {@link #onStop()} will be called following return.
5807 * @see #requestVisibleBehind(boolean)
5808 * @see #onBackgroundVisibleBehindChanged(boolean)
5811 public void onVisibleBehindCanceled() {
5816 * Translucent activities may call this to determine if there is an activity below them that
5817 * is currently set to be visible in the background.
5819 * @return true if an activity below is set to visible according to the most recent call to
5820 * {@link #requestVisibleBehind(boolean)}, false otherwise.
5822 * @see #requestVisibleBehind(boolean)
5823 * @see #onVisibleBehindCanceled()
5824 * @see #onBackgroundVisibleBehindChanged(boolean)
5828 public boolean isBackgroundVisibleBehind() {
5830 return ActivityManagerNative.getDefault().isBackgroundVisibleBehind(mToken);
5831 } catch (RemoteException e) {
5837 * The topmost foreground activity will receive this call when the background visibility state
5838 * of the activity below it changes.
5840 * This call may be a consequence of {@link #requestVisibleBehind(boolean)} or might be
5841 * due to a background activity finishing itself.
5843 * @param visible true if a background activity is visible, false otherwise.
5845 * @see #requestVisibleBehind(boolean)
5846 * @see #onVisibleBehindCanceled()
5850 public void onBackgroundVisibleBehindChanged(boolean visible) {
5854 * Activities cannot draw during the period that their windows are animating in. In order
5855 * to know when it is safe to begin drawing they can override this method which will be
5856 * called when the entering animation has completed.
5858 public void onEnterAnimationComplete() {
5864 public void dispatchEnterAnimationComplete() {
5865 onEnterAnimationComplete();
5866 if (getWindow() != null && getWindow().getDecorView() != null) {
5867 getWindow().getDecorView().getViewTreeObserver().dispatchOnEnterAnimationComplete();
5872 * Adjust the current immersive mode setting.
5874 * Note that changing this value will have no effect on the activity's
5875 * {@link android.content.pm.ActivityInfo} structure; that is, if
5876 * <code>android:immersive</code> is set to <code>true</code>
5877 * in the application's manifest entry for this activity, the {@link
5878 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
5879 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
5880 * FLAG_IMMERSIVE} bit set.
5882 * @see #isImmersive()
5883 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
5885 public void setImmersive(boolean i) {
5887 ActivityManagerNative.getDefault().setImmersive(mToken, i);
5888 } catch (RemoteException e) {
5894 * Start an action mode of the default type {@link ActionMode#TYPE_PRIMARY}.
5896 * @param callback Callback that will manage lifecycle events for this action mode
5897 * @return The ActionMode that was started, or null if it was canceled
5902 public ActionMode startActionMode(ActionMode.Callback callback) {
5903 return mWindow.getDecorView().startActionMode(callback);
5907 * Start an action mode of the given type.
5909 * @param callback Callback that will manage lifecycle events for this action mode
5910 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5911 * @return The ActionMode that was started, or null if it was canceled
5916 public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5917 return mWindow.getDecorView().startActionMode(callback, type);
5921 * Give the Activity a chance to control the UI for an action mode requested
5924 * <p>Note: If you are looking for a notification callback that an action mode
5925 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
5927 * @param callback The callback that should control the new action mode
5928 * @return The new action mode, or <code>null</code> if the activity does not want to
5929 * provide special handling for this action mode. (It will be handled by the system.)
5933 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
5934 // Only Primary ActionModes are represented in the ActionBar.
5935 if (mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
5936 initWindowDecorActionBar();
5937 if (mActionBar != null) {
5938 return mActionBar.startActionMode(callback);
5949 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
5951 mActionModeTypeStarting = type;
5952 return onWindowStartingActionMode(callback);
5954 mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
5959 * Notifies the Activity that an action mode has been started.
5960 * Activity subclasses overriding this method should call the superclass implementation.
5962 * @param mode The new action mode.
5966 public void onActionModeStarted(ActionMode mode) {
5970 * Notifies the activity that an action mode has finished.
5971 * Activity subclasses overriding this method should call the superclass implementation.
5973 * @param mode The action mode that just finished.
5977 public void onActionModeFinished(ActionMode mode) {
5981 * Returns true if the app should recreate the task when navigating 'up' from this activity
5982 * by using targetIntent.
5984 * <p>If this method returns false the app can trivially call
5985 * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
5986 * up navigation. If this method returns false, the app should synthesize a new task stack
5987 * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
5989 * @param targetIntent An intent representing the target destination for up navigation
5990 * @return true if navigating up should recreate a new task stack, false if the same task
5991 * should be used for the destination
5993 public boolean shouldUpRecreateTask(Intent targetIntent) {
5995 PackageManager pm = getPackageManager();
5996 ComponentName cn = targetIntent.getComponent();
5998 cn = targetIntent.resolveActivity(pm);
6000 ActivityInfo info = pm.getActivityInfo(cn, 0);
6001 if (info.taskAffinity == null) {
6004 return ActivityManagerNative.getDefault()
6005 .shouldUpRecreateTask(mToken, info.taskAffinity);
6006 } catch (RemoteException e) {
6008 } catch (NameNotFoundException e) {
6014 * Navigate from this activity to the activity specified by upIntent, finishing this activity
6015 * in the process. If the activity indicated by upIntent already exists in the task's history,
6016 * this activity and all others before the indicated activity in the history stack will be
6019 * <p>If the indicated activity does not appear in the history stack, this will finish
6020 * each activity in this task until the root activity of the task is reached, resulting in
6021 * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
6022 * when an activity may be reached by a path not passing through a canonical parent
6025 * <p>This method should be used when performing up navigation from within the same task
6026 * as the destination. If up navigation should cross tasks in some cases, see
6027 * {@link #shouldUpRecreateTask(Intent)}.</p>
6029 * @param upIntent An intent representing the target destination for up navigation
6031 * @return true if up navigation successfully reached the activity indicated by upIntent and
6032 * upIntent was delivered to it. false if an instance of the indicated activity could
6033 * not be found and this activity was simply finished normally.
6035 public boolean navigateUpTo(Intent upIntent) {
6036 if (mParent == null) {
6037 ComponentName destInfo = upIntent.getComponent();
6038 if (destInfo == null) {
6039 destInfo = upIntent.resolveActivity(getPackageManager());
6040 if (destInfo == null) {
6043 upIntent = new Intent(upIntent);
6044 upIntent.setComponent(destInfo);
6048 synchronized (this) {
6049 resultCode = mResultCode;
6050 resultData = mResultData;
6052 if (resultData != null) {
6053 resultData.prepareToLeaveProcess();
6056 upIntent.prepareToLeaveProcess();
6057 return ActivityManagerNative.getDefault().navigateUpTo(mToken, upIntent,
6058 resultCode, resultData);
6059 } catch (RemoteException e) {
6063 return mParent.navigateUpToFromChild(this, upIntent);
6068 * This is called when a child activity of this one calls its
6069 * {@link #navigateUpTo} method. The default implementation simply calls
6070 * navigateUpTo(upIntent) on this activity (the parent).
6072 * @param child The activity making the call.
6073 * @param upIntent An intent representing the target destination for up navigation
6075 * @return true if up navigation successfully reached the activity indicated by upIntent and
6076 * upIntent was delivered to it. false if an instance of the indicated activity could
6077 * not be found and this activity was simply finished normally.
6079 public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
6080 return navigateUpTo(upIntent);
6084 * Obtain an {@link Intent} that will launch an explicit target activity specified by
6085 * this activity's logical parent. The logical parent is named in the application's manifest
6086 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
6087 * Activity subclasses may override this method to modify the Intent returned by
6088 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
6089 * the parent intent entirely.
6091 * @return a new Intent targeting the defined parent of this activity or null if
6092 * there is no valid parent.
6095 public Intent getParentActivityIntent() {
6096 final String parentName = mActivityInfo.parentActivityName;
6097 if (TextUtils.isEmpty(parentName)) {
6101 // If the parent itself has no parent, generate a main activity intent.
6102 final ComponentName target = new ComponentName(this, parentName);
6104 final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
6105 final String parentActivity = parentInfo.parentActivityName;
6106 final Intent parentIntent = parentActivity == null
6107 ? Intent.makeMainActivity(target)
6108 : new Intent().setComponent(target);
6109 return parentIntent;
6110 } catch (NameNotFoundException e) {
6111 Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
6118 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6119 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6120 * will be called to handle shared elements on the <i>launched</i> Activity. This requires
6121 * {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6123 * @param callback Used to manipulate shared element transitions on the launched Activity.
6125 public void setEnterSharedElementCallback(SharedElementCallback callback) {
6126 if (callback == null) {
6127 callback = SharedElementCallback.NULL_CALLBACK;
6129 mEnterTransitionListener = callback;
6133 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6134 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6135 * will be called to handle shared elements on the <i>launching</i> Activity. Most
6136 * calls will only come when returning from the started Activity.
6137 * This requires {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6139 * @param callback Used to manipulate shared element transitions on the launching Activity.
6141 public void setExitSharedElementCallback(SharedElementCallback callback) {
6142 if (callback == null) {
6143 callback = SharedElementCallback.NULL_CALLBACK;
6145 mExitTransitionListener = callback;
6149 * Postpone the entering activity transition when Activity was started with
6150 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6151 * android.util.Pair[])}.
6152 * <p>This method gives the Activity the ability to delay starting the entering and
6153 * shared element transitions until all data is loaded. Until then, the Activity won't
6154 * draw into its window, leaving the window transparent. This may also cause the
6155 * returning animation to be delayed until data is ready. This method should be
6156 * called in {@link #onCreate(android.os.Bundle)} or in
6157 * {@link #onActivityReenter(int, android.content.Intent)}.
6158 * {@link #startPostponedEnterTransition()} must be called to allow the Activity to
6159 * start the transitions. If the Activity did not use
6160 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6161 * android.util.Pair[])}, then this method does nothing.</p>
6163 public void postponeEnterTransition() {
6164 mActivityTransitionState.postponeEnterTransition();
6168 * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
6169 * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
6170 * to have your Activity start drawing.
6172 public void startPostponedEnterTransition() {
6173 mActivityTransitionState.startPostponedEnterTransition();
6176 // ------------------ Internal API ------------------
6178 final void setParent(Activity parent) {
6182 final void attach(Context context, ActivityThread aThread,
6183 Instrumentation instr, IBinder token, int ident,
6184 Application application, Intent intent, ActivityInfo info,
6185 CharSequence title, Activity parent, String id,
6186 NonConfigurationInstances lastNonConfigurationInstances,
6187 Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
6188 attachBaseContext(context);
6190 mFragments.attachHost(null /*parent*/);
6192 mWindow = new PhoneWindow(this);
6193 mWindow.setCallback(this);
6194 mWindow.setOnWindowDismissedCallback(this);
6195 mWindow.getLayoutInflater().setPrivateFactory(this);
6196 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
6197 mWindow.setSoftInputMode(info.softInputMode);
6199 if (info.uiOptions != 0) {
6200 mWindow.setUiOptions(info.uiOptions);
6202 mUiThread = Thread.currentThread();
6204 mMainThread = aThread;
6205 mInstrumentation = instr;
6208 mApplication = application;
6210 mReferrer = referrer;
6211 mComponent = intent.getComponent();
6212 mActivityInfo = info;
6216 mLastNonConfigurationInstances = lastNonConfigurationInstances;
6217 if (voiceInteractor != null) {
6218 if (lastNonConfigurationInstances != null) {
6219 mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
6221 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
6226 mWindow.setWindowManager(
6227 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
6228 mToken, mComponent.flattenToString(),
6229 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
6230 if (mParent != null) {
6231 mWindow.setContainer(mParent.getWindow());
6233 mWindowManager = mWindow.getWindowManager();
6234 mCurrentConfig = config;
6238 public final IBinder getActivityToken() {
6239 return mParent != null ? mParent.getActivityToken() : mToken;
6242 final void performCreateCommon() {
6243 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
6244 com.android.internal.R.styleable.Window_windowNoDisplay, false);
6245 mFragments.dispatchActivityCreated();
6246 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
6249 final void performCreate(Bundle icicle) {
6250 restoreHasCurrentPermissionRequest(icicle);
6252 mActivityTransitionState.readState(icicle);
6253 performCreateCommon();
6256 final void performCreate(Bundle icicle, PersistableBundle persistentState) {
6257 restoreHasCurrentPermissionRequest(icicle);
6258 onCreate(icicle, persistentState);
6259 mActivityTransitionState.readState(icicle);
6260 performCreateCommon();
6263 final void performStart() {
6264 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
6265 mFragments.noteStateNotSaved();
6267 mFragments.execPendingActions();
6268 mInstrumentation.callActivityOnStart(this);
6270 throw new SuperNotCalledException(
6271 "Activity " + mComponent.toShortString() +
6272 " did not call through to super.onStart()");
6274 mFragments.dispatchStart();
6275 mFragments.reportLoaderStart();
6276 mActivityTransitionState.enterReady(this);
6279 final void performRestart() {
6280 mFragments.noteStateNotSaved();
6284 if (mToken != null && mParent == null) {
6285 WindowManagerGlobal.getInstance().setStoppedState(mToken, false);
6288 synchronized (mManagedCursors) {
6289 final int N = mManagedCursors.size();
6290 for (int i=0; i<N; i++) {
6291 ManagedCursor mc = mManagedCursors.get(i);
6292 if (mc.mReleased || mc.mUpdated) {
6293 if (!mc.mCursor.requery()) {
6294 if (getApplicationInfo().targetSdkVersion
6295 >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
6296 throw new IllegalStateException(
6297 "trying to requery an already closed cursor "
6301 mc.mReleased = false;
6302 mc.mUpdated = false;
6308 mInstrumentation.callActivityOnRestart(this);
6310 throw new SuperNotCalledException(
6311 "Activity " + mComponent.toShortString() +
6312 " did not call through to super.onRestart()");
6318 final void performResume() {
6321 mFragments.execPendingActions();
6323 mLastNonConfigurationInstances = null;
6326 // mResumed is set by the instrumentation
6327 mInstrumentation.callActivityOnResume(this);
6329 throw new SuperNotCalledException(
6330 "Activity " + mComponent.toShortString() +
6331 " did not call through to super.onResume()");
6334 // invisible activities must be finished before onResume() completes
6335 if (!mVisibleFromClient && !mFinished) {
6336 Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
6337 if (getApplicationInfo().targetSdkVersion
6338 > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
6339 throw new IllegalStateException(
6340 "Activity " + mComponent.toShortString() +
6341 " did not call finish() prior to onResume() completing");
6345 // Now really resume, and install the current status bar and menu.
6348 mFragments.dispatchResume();
6349 mFragments.execPendingActions();
6353 throw new SuperNotCalledException(
6354 "Activity " + mComponent.toShortString() +
6355 " did not call through to super.onPostResume()");
6359 final void performPause() {
6360 mDoReportFullyDrawn = false;
6361 mFragments.dispatchPause();
6365 if (!mCalled && getApplicationInfo().targetSdkVersion
6366 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
6367 throw new SuperNotCalledException(
6368 "Activity " + mComponent.toShortString() +
6369 " did not call through to super.onPause()");
6374 final void performUserLeaving() {
6375 onUserInteraction();
6379 final void performStop() {
6380 mDoReportFullyDrawn = false;
6381 mFragments.doLoaderStop(mChangingConfigurations /*retain*/);
6384 if (mWindow != null) {
6385 mWindow.closeAllPanels();
6388 if (mToken != null && mParent == null) {
6389 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
6392 mFragments.dispatchStop();
6395 mInstrumentation.callActivityOnStop(this);
6397 throw new SuperNotCalledException(
6398 "Activity " + mComponent.toShortString() +
6399 " did not call through to super.onStop()");
6402 synchronized (mManagedCursors) {
6403 final int N = mManagedCursors.size();
6404 for (int i=0; i<N; i++) {
6405 ManagedCursor mc = mManagedCursors.get(i);
6406 if (!mc.mReleased) {
6407 mc.mCursor.deactivate();
6408 mc.mReleased = true;
6418 final void performDestroy() {
6421 mFragments.dispatchDestroy();
6423 mFragments.doLoaderDestroy();
6424 if (mVoiceInteractor != null) {
6425 mVoiceInteractor.detachActivity();
6432 public final boolean isResumed() {
6436 private void storeHasCurrentPermissionRequest(Bundle bundle) {
6437 if (bundle != null && mHasCurrentPermissionsRequest) {
6438 bundle.putBoolean(HAS_CURENT_PERMISSIONS_REQUEST_KEY, true);
6442 private void restoreHasCurrentPermissionRequest(Bundle bundle) {
6443 if (bundle != null) {
6444 mHasCurrentPermissionsRequest = bundle.getBoolean(
6445 HAS_CURENT_PERMISSIONS_REQUEST_KEY, false);
6449 void dispatchActivityResult(String who, int requestCode,
6450 int resultCode, Intent data) {
6452 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
6453 + ", resCode=" + resultCode + ", data=" + data);
6454 mFragments.noteStateNotSaved();
6456 onActivityResult(requestCode, resultCode, data);
6457 } else if (who.startsWith(REQUEST_PERMISSIONS_WHO_PREFIX)) {
6458 who = who.substring(REQUEST_PERMISSIONS_WHO_PREFIX.length());
6459 if (TextUtils.isEmpty(who)) {
6460 dispatchRequestPermissionsResult(requestCode, data);
6462 Fragment frag = mFragments.findFragmentByWho(who);
6464 dispatchRequestPermissionsResultToFragment(requestCode, data, frag);
6467 } else if (who.startsWith("@android:view:")) {
6468 ArrayList<ViewRootImpl> views = WindowManagerGlobal.getInstance().getRootViews(
6469 getActivityToken());
6470 for (ViewRootImpl viewRoot : views) {
6471 if (viewRoot.getView() != null
6472 && viewRoot.getView().dispatchActivityResult(
6473 who, requestCode, resultCode, data)) {
6478 Fragment frag = mFragments.findFragmentByWho(who);
6480 frag.onActivityResult(requestCode, resultCode, data);
6486 * Request to put this Activity in a mode where the user is locked to the
6489 * This will prevent the user from launching other apps, going to settings, or reaching the
6490 * home screen. This does not include those apps whose {@link android.R.attr#lockTaskMode}
6491 * values permit launching while locked.
6493 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns true or
6494 * lockTaskMode=lockTaskModeAlways for this component then the app will go directly into
6495 * Lock Task mode. The user will not be able to exit this mode until
6496 * {@link Activity#stopLockTask()} is called.
6498 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns false
6499 * then the system will prompt the user with a dialog requesting permission to enter
6500 * this mode. When entered through this method the user can exit at any time through
6501 * an action described by the request dialog. Calling stopLockTask will also exit the
6504 * @see android.R.attr#lockTaskMode
6506 public void startLockTask() {
6508 ActivityManagerNative.getDefault().startLockTaskMode(mToken);
6509 } catch (RemoteException e) {
6514 * Allow the user to switch away from the current task.
6516 * Called to end the mode started by {@link Activity#startLockTask}. This
6517 * can only be called by activities that have successfully called
6518 * startLockTask previously.
6520 * This will allow the user to exit this app and move onto other activities.
6521 * <p>Note: This method should only be called when the activity is user-facing. That is,
6522 * between onResume() and onPause().
6523 * <p>Note: If there are other tasks below this one that are also locked then calling this
6524 * method will immediately finish this task and resume the previous locked one, remaining in
6527 * @see android.R.attr#lockTaskMode
6528 * @see ActivityManager#getLockTaskModeState()
6530 public void stopLockTask() {
6532 ActivityManagerNative.getDefault().stopLockTaskMode();
6533 } catch (RemoteException e) {
6538 * Shows the user the system defined message for telling the user how to exit
6539 * lock task mode. The task containing this activity must be in lock task mode at the time
6540 * of this call for the message to be displayed.
6542 public void showLockTaskEscapeMessage() {
6544 ActivityManagerNative.getDefault().showLockTaskEscapeMessage(mToken);
6545 } catch (RemoteException e) {
6550 * Interface for informing a translucent {@link Activity} once all visible activities below it
6551 * have completed drawing. This is necessary only after an {@link Activity} has been made
6552 * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
6553 * translucent again following a call to {@link
6554 * Activity#convertToTranslucent(android.app.Activity.TranslucentConversionListener,
6560 public interface TranslucentConversionListener {
6562 * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
6563 * below the top one have been redrawn. Following this callback it is safe to make the top
6564 * Activity translucent because the underlying Activity has been drawn.
6566 * @param drawComplete True if the background Activity has drawn itself. False if a timeout
6567 * occurred waiting for the Activity to complete drawing.
6569 * @see Activity#convertFromTranslucent()
6570 * @see Activity#convertToTranslucent(TranslucentConversionListener, ActivityOptions)
6572 public void onTranslucentConversionComplete(boolean drawComplete);
6575 private void dispatchRequestPermissionsResult(int requestCode, Intent data) {
6576 mHasCurrentPermissionsRequest = false;
6577 // If the package installer crashed we may have not data - best effort.
6578 String[] permissions = (data != null) ? data.getStringArrayExtra(
6579 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
6580 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
6581 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
6582 onRequestPermissionsResult(requestCode, permissions, grantResults);
6585 private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data,
6586 Fragment fragment) {
6587 // If the package installer crashed we may have not data - best effort.
6588 String[] permissions = (data != null) ? data.getStringArrayExtra(
6589 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
6590 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
6591 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
6592 fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
6595 class HostCallbacks extends FragmentHostCallback<Activity> {
6596 public HostCallbacks() {
6597 super(Activity.this /*activity*/);
6601 public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
6602 Activity.this.dump(prefix, fd, writer, args);
6606 public boolean onShouldSaveFragmentState(Fragment fragment) {
6607 return !isFinishing();
6611 public LayoutInflater onGetLayoutInflater() {
6612 final LayoutInflater result = Activity.this.getLayoutInflater();
6613 if (onUseFragmentManagerInflaterFactory()) {
6614 return result.cloneInContext(Activity.this);
6620 public boolean onUseFragmentManagerInflaterFactory() {
6621 // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
6622 return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
6626 public Activity onGetHost() {
6627 return Activity.this;
6631 public void onInvalidateOptionsMenu() {
6632 Activity.this.invalidateOptionsMenu();
6636 public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
6638 Activity.this.startActivityFromFragment(fragment, intent, requestCode, options);
6642 public void onRequestPermissionsFromFragment(Fragment fragment, String[] permissions,
6644 String who = REQUEST_PERMISSIONS_WHO_PREFIX + fragment.mWho;
6645 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
6646 startActivityForResult(who, intent, requestCode, null);
6650 public boolean onHasWindowAnimations() {
6651 return getWindow() != null;
6655 public int onGetWindowAnimations() {
6656 final Window w = getWindow();
6657 return (w == null) ? 0 : w.getAttributes().windowAnimations;
6661 public void onAttachFragment(Fragment fragment) {
6662 Activity.this.onAttachFragment(fragment);
6667 public View onFindViewById(int id) {
6668 return Activity.this.findViewById(id);
6672 public boolean onHasView() {
6673 final Window w = getWindow();
6674 return (w != null && w.peekDecorView() != null);