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_";
693 private static final String REQUEST_PERMISSIONS_WHO_PREFIX = "@android:requestPermissions:";
695 private static class ManagedDialog {
699 private SparseArray<ManagedDialog> mManagedDialogs;
701 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
702 private Instrumentation mInstrumentation;
703 private IBinder mToken;
705 /*package*/ String mEmbeddedID;
706 private Application mApplication;
707 /*package*/ Intent mIntent;
708 /*package*/ String mReferrer;
709 private ComponentName mComponent;
710 /*package*/ ActivityInfo mActivityInfo;
711 /*package*/ ActivityThread mMainThread;
714 /*package*/ boolean mResumed;
715 private boolean mStopped;
717 boolean mStartedActivity;
718 private boolean mDestroyed;
719 private boolean mDoReportFullyDrawn = true;
720 /** true if the activity is going through a transient pause */
721 /*package*/ boolean mTemporaryPause = false;
722 /** true if the activity is being destroyed in order to recreate it with a new configuration */
723 /*package*/ boolean mChangingConfigurations = false;
724 /*package*/ int mConfigChangeFlags;
725 /*package*/ Configuration mCurrentConfig;
726 private SearchManager mSearchManager;
727 private MenuInflater mMenuInflater;
729 static final class NonConfigurationInstances {
731 HashMap<String, Object> children;
732 List<Fragment> fragments;
733 ArrayMap<String, LoaderManager> loaders;
734 VoiceInteractor voiceInteractor;
736 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
738 private Window mWindow;
740 private WindowManager mWindowManager;
741 /*package*/ View mDecor = null;
742 /*package*/ boolean mWindowAdded = false;
743 /*package*/ boolean mVisibleFromServer = false;
744 /*package*/ boolean mVisibleFromClient = true;
745 /*package*/ ActionBar mActionBar = null;
746 private boolean mEnableDefaultActionBarUp;
748 private VoiceInteractor mVoiceInteractor;
750 private CharSequence mTitle;
751 private int mTitleColor = 0;
753 // we must have a handler before the FragmentController is constructed
754 final Handler mHandler = new Handler();
755 final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
757 // Most recent call to requestVisibleBehind().
758 boolean mVisibleBehind;
760 private static final class ManagedCursor {
761 ManagedCursor(Cursor cursor) {
767 private final Cursor mCursor;
768 private boolean mReleased;
769 private boolean mUpdated;
771 private final ArrayList<ManagedCursor> mManagedCursors =
772 new ArrayList<ManagedCursor>();
774 // protected by synchronized (this)
775 int mResultCode = RESULT_CANCELED;
776 Intent mResultData = null;
778 private TranslucentConversionListener mTranslucentCallback;
779 private boolean mChangeCanvasToTranslucent;
781 private SearchEvent mSearchEvent;
783 private boolean mTitleReady = false;
784 private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
786 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
787 private SpannableStringBuilder mDefaultKeySsb = null;
789 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
791 @SuppressWarnings("unused")
792 private final Object mInstanceTracker = StrictMode.trackActivity(this);
794 private Thread mUiThread;
796 ActivityTransitionState mActivityTransitionState = new ActivityTransitionState();
797 SharedElementCallback mEnterTransitionListener = SharedElementCallback.NULL_CALLBACK;
798 SharedElementCallback mExitTransitionListener = SharedElementCallback.NULL_CALLBACK;
800 /** Return the intent that started this activity. */
801 public Intent getIntent() {
806 * Change the intent returned by {@link #getIntent}. This holds a
807 * reference to the given intent; it does not copy it. Often used in
808 * conjunction with {@link #onNewIntent}.
810 * @param newIntent The new Intent object to return from getIntent
815 public void setIntent(Intent newIntent) {
819 /** Return the application that owns this activity. */
820 public final Application getApplication() {
824 /** Is this activity embedded inside of another activity? */
825 public final boolean isChild() {
826 return mParent != null;
829 /** Return the parent activity if this view is an embedded child. */
830 public final Activity getParent() {
834 /** Retrieve the window manager for showing custom windows. */
835 public WindowManager getWindowManager() {
836 return mWindowManager;
840 * Retrieve the current {@link android.view.Window} for the activity.
841 * This can be used to directly access parts of the Window API that
842 * are not available through Activity/Screen.
844 * @return Window The current window, or null if the activity is not
847 public Window getWindow() {
852 * Return the LoaderManager for this activity, creating it if needed.
854 public LoaderManager getLoaderManager() {
855 return mFragments.getLoaderManager();
859 * Calls {@link android.view.Window#getCurrentFocus} on the
860 * Window of this Activity to return the currently focused view.
862 * @return View The current View with focus or null.
865 * @see android.view.Window#getCurrentFocus
868 public View getCurrentFocus() {
869 return mWindow != null ? mWindow.getCurrentFocus() : null;
873 * Called when the activity is starting. This is where most initialization
874 * should go: calling {@link #setContentView(int)} to inflate the
875 * activity's UI, using {@link #findViewById} to programmatically interact
876 * with widgets in the UI, calling
877 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
878 * cursors for data being displayed, etc.
880 * <p>You can call {@link #finish} from within this function, in
881 * which case onDestroy() will be immediately called without any of the rest
882 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
883 * {@link #onPause}, etc) executing.
885 * <p><em>Derived classes must call through to the super class's
886 * implementation of this method. If they do not, an exception will be
889 * @param savedInstanceState If the activity is being re-initialized after
890 * previously being shut down then this Bundle contains the data it most
891 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
894 * @see #onSaveInstanceState
895 * @see #onRestoreInstanceState
900 protected void onCreate(@Nullable Bundle savedInstanceState) {
901 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
902 if (mLastNonConfigurationInstances != null) {
903 mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
905 if (mActivityInfo.parentActivityName != null) {
906 if (mActionBar == null) {
907 mEnableDefaultActionBarUp = true;
909 mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
912 if (savedInstanceState != null) {
913 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
914 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
915 ? mLastNonConfigurationInstances.fragments : null);
917 mFragments.dispatchCreate();
918 getApplication().dispatchActivityCreated(this, savedInstanceState);
919 if (mVoiceInteractor != null) {
920 mVoiceInteractor.attachActivity(this);
926 * Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
927 * the attribute {@link android.R.attr#persistableMode} set to
928 * <code>persistAcrossReboots</code>.
930 * @param savedInstanceState if the activity is being re-initialized after
931 * previously being shut down then this Bundle contains the data it most
932 * recently supplied in {@link #onSaveInstanceState}.
933 * <b><i>Note: Otherwise it is null.</i></b>
934 * @param persistentState if the activity is being re-initialized after
935 * previously being shut down or powered off then this Bundle contains the data it most
936 * recently supplied to outPersistentState in {@link #onSaveInstanceState}.
937 * <b><i>Note: Otherwise it is null.</i></b>
939 * @see #onCreate(android.os.Bundle)
941 * @see #onSaveInstanceState
942 * @see #onRestoreInstanceState
945 public void onCreate(@Nullable Bundle savedInstanceState,
946 @Nullable PersistableBundle persistentState) {
947 onCreate(savedInstanceState);
951 * The hook for {@link ActivityThread} to restore the state of this activity.
953 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
954 * {@link #restoreManagedDialogs(android.os.Bundle)}.
956 * @param savedInstanceState contains the saved state
958 final void performRestoreInstanceState(Bundle savedInstanceState) {
959 onRestoreInstanceState(savedInstanceState);
960 restoreManagedDialogs(savedInstanceState);
964 * The hook for {@link ActivityThread} to restore the state of this activity.
966 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
967 * {@link #restoreManagedDialogs(android.os.Bundle)}.
969 * @param savedInstanceState contains the saved state
970 * @param persistentState contains the persistable saved state
972 final void performRestoreInstanceState(Bundle savedInstanceState,
973 PersistableBundle persistentState) {
974 onRestoreInstanceState(savedInstanceState, persistentState);
975 if (savedInstanceState != null) {
976 restoreManagedDialogs(savedInstanceState);
981 * This method is called after {@link #onStart} when the activity is
982 * being re-initialized from a previously saved state, given here in
983 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
984 * to restore their state, but it is sometimes convenient to do it here
985 * after all of the initialization has been done or to allow subclasses to
986 * decide whether to use your default implementation. The default
987 * implementation of this method performs a restore of any view state that
988 * had previously been frozen by {@link #onSaveInstanceState}.
990 * <p>This method is called between {@link #onStart} and
991 * {@link #onPostCreate}.
993 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
998 * @see #onSaveInstanceState
1000 protected void onRestoreInstanceState(Bundle savedInstanceState) {
1001 if (mWindow != null) {
1002 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
1003 if (windowState != null) {
1004 mWindow.restoreHierarchyState(windowState);
1010 * This is the same as {@link #onRestoreInstanceState(Bundle)} but is called for activities
1011 * created with the attribute {@link android.R.attr#persistableMode} set to
1012 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1013 * came from the restored PersistableBundle first
1014 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1016 * <p>This method is called between {@link #onStart} and
1017 * {@link #onPostCreate}.
1019 * <p>If this method is called {@link #onRestoreInstanceState(Bundle)} will not be called.
1021 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1022 * @param persistentState the data most recently supplied in {@link #onSaveInstanceState}.
1024 * @see #onRestoreInstanceState(Bundle)
1026 * @see #onPostCreate
1028 * @see #onSaveInstanceState
1030 public void onRestoreInstanceState(Bundle savedInstanceState,
1031 PersistableBundle persistentState) {
1032 if (savedInstanceState != null) {
1033 onRestoreInstanceState(savedInstanceState);
1038 * Restore the state of any saved managed dialogs.
1040 * @param savedInstanceState The bundle to restore from.
1042 private void restoreManagedDialogs(Bundle savedInstanceState) {
1043 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
1048 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
1049 final int numDialogs = ids.length;
1050 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
1051 for (int i = 0; i < numDialogs; i++) {
1052 final Integer dialogId = ids[i];
1053 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
1054 if (dialogState != null) {
1055 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
1056 // so tell createDialog() not to do it, otherwise we get an exception
1057 final ManagedDialog md = new ManagedDialog();
1058 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
1059 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
1060 if (md.mDialog != null) {
1061 mManagedDialogs.put(dialogId, md);
1062 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
1063 md.mDialog.onRestoreInstanceState(dialogState);
1069 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
1070 final Dialog dialog = onCreateDialog(dialogId, args);
1071 if (dialog == null) {
1074 dialog.dispatchOnCreate(state);
1078 private static String savedDialogKeyFor(int key) {
1079 return SAVED_DIALOG_KEY_PREFIX + key;
1082 private static String savedDialogArgsKeyFor(int key) {
1083 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
1087 * Called when activity start-up is complete (after {@link #onStart}
1088 * and {@link #onRestoreInstanceState} have been called). Applications will
1089 * generally not implement this method; it is intended for system
1090 * classes to do final initialization after application code has run.
1092 * <p><em>Derived classes must call through to the super class's
1093 * implementation of this method. If they do not, an exception will be
1096 * @param savedInstanceState If the activity is being re-initialized after
1097 * previously being shut down then this Bundle contains the data it most
1098 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
1102 protected void onPostCreate(@Nullable Bundle savedInstanceState) {
1105 onTitleChanged(getTitle(), getTitleColor());
1111 * This is the same as {@link #onPostCreate(Bundle)} but is called for activities
1112 * created with the attribute {@link android.R.attr#persistableMode} set to
1113 * <code>persistAcrossReboots</code>.
1115 * @param savedInstanceState The data most recently supplied in {@link #onSaveInstanceState}
1116 * @param persistentState The data caming from the PersistableBundle first
1117 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1121 public void onPostCreate(@Nullable Bundle savedInstanceState,
1122 @Nullable PersistableBundle persistentState) {
1123 onPostCreate(savedInstanceState);
1127 * Called after {@link #onCreate} — or after {@link #onRestart} when
1128 * the activity had been stopped, but is now again being displayed to the
1129 * user. It will be followed by {@link #onResume}.
1131 * <p><em>Derived classes must call through to the super class's
1132 * implementation of this method. If they do not, an exception will be
1140 protected void onStart() {
1141 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
1144 mFragments.doLoaderStart();
1146 getApplication().dispatchActivityStarted(this);
1150 * Called after {@link #onStop} when the current activity is being
1151 * re-displayed to the user (the user has navigated back to it). It will
1152 * be followed by {@link #onStart} and then {@link #onResume}.
1154 * <p>For activities that are using raw {@link Cursor} objects (instead of
1155 * creating them through
1156 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1157 * this is usually the place
1158 * where the cursor should be requeried (because you had deactivated it in
1161 * <p><em>Derived classes must call through to the super class's
1162 * implementation of this method. If they do not, an exception will be
1170 protected void onRestart() {
1175 * Called when an {@link #onResume} is coming up, prior to other pre-resume callbacks
1176 * such as {@link #onNewIntent} and {@link #onActivityResult}. This is primarily intended
1177 * to give the activity a hint that its state is no longer saved -- it will generally
1178 * be called after {@link #onSaveInstanceState} and prior to the activity being
1179 * resumed/started again.
1181 public void onStateNotSaved() {
1185 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1186 * {@link #onPause}, for your activity to start interacting with the user.
1187 * This is a good place to begin animations, open exclusive-access devices
1188 * (such as the camera), etc.
1190 * <p>Keep in mind that onResume is not the best indicator that your activity
1191 * is visible to the user; a system window such as the keyguard may be in
1192 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1193 * activity is visible to the user (for example, to resume a game).
1195 * <p><em>Derived classes must call through to the super class's
1196 * implementation of this method. If they do not, an exception will be
1199 * @see #onRestoreInstanceState
1201 * @see #onPostResume
1205 protected void onResume() {
1206 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this);
1207 getApplication().dispatchActivityResumed(this);
1208 mActivityTransitionState.onResume();
1213 * Called when activity resume is complete (after {@link #onResume} has
1214 * been called). Applications will generally not implement this method;
1215 * it is intended for system classes to do final setup after application
1216 * resume code has run.
1218 * <p><em>Derived classes must call through to the super class's
1219 * implementation of this method. If they do not, an exception will be
1225 protected void onPostResume() {
1226 final Window win = getWindow();
1227 if (win != null) win.makeActive();
1228 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
1233 * Check whether this activity is running as part of a voice interaction with the user.
1234 * If true, it should perform its interaction with the user through the
1235 * {@link VoiceInteractor} returned by {@link #getVoiceInteractor}.
1237 public boolean isVoiceInteraction() {
1238 return mVoiceInteractor != null;
1242 * Like {@link #isVoiceInteraction}, but only returns true if this is also the root
1243 * of a voice interaction. That is, returns true if this activity was directly
1244 * started by the voice interaction service as the initiation of a voice interaction.
1245 * Otherwise, for example if it was started by another activity while under voice
1246 * interaction, returns false.
1248 public boolean isVoiceInteractionRoot() {
1250 return mVoiceInteractor != null
1251 && ActivityManagerNative.getDefault().isRootVoiceInteraction(mToken);
1252 } catch (RemoteException e) {
1258 * Retrieve the active {@link VoiceInteractor} that the user is going through to
1259 * interact with this activity.
1261 public VoiceInteractor getVoiceInteractor() {
1262 return mVoiceInteractor;
1266 * This is called for activities that set launchMode to "singleTop" in
1267 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1268 * flag when calling {@link #startActivity}. In either case, when the
1269 * activity is re-launched while at the top of the activity stack instead
1270 * of a new instance of the activity being started, onNewIntent() will be
1271 * called on the existing instance with the Intent that was used to
1274 * <p>An activity will always be paused before receiving a new intent, so
1275 * you can count on {@link #onResume} being called after this method.
1277 * <p>Note that {@link #getIntent} still returns the original Intent. You
1278 * can use {@link #setIntent} to update it to this new Intent.
1280 * @param intent The new intent that was started for the activity.
1286 protected void onNewIntent(Intent intent) {
1290 * The hook for {@link ActivityThread} to save the state of this activity.
1292 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1293 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1295 * @param outState The bundle to save the state to.
1297 final void performSaveInstanceState(Bundle outState) {
1298 onSaveInstanceState(outState);
1299 saveManagedDialogs(outState);
1300 mActivityTransitionState.saveState(outState);
1301 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState);
1305 * The hook for {@link ActivityThread} to save the state of this activity.
1307 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1308 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1310 * @param outState The bundle to save the state to.
1311 * @param outPersistentState The bundle to save persistent state to.
1313 final void performSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1314 onSaveInstanceState(outState, outPersistentState);
1315 saveManagedDialogs(outState);
1316 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState +
1317 ", " + outPersistentState);
1321 * Called to retrieve per-instance state from an activity before being killed
1322 * so that the state can be restored in {@link #onCreate} or
1323 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1324 * will be passed to both).
1326 * <p>This method is called before an activity may be killed so that when it
1327 * comes back some time in the future it can restore its state. For example,
1328 * if activity B is launched in front of activity A, and at some point activity
1329 * A is killed to reclaim resources, activity A will have a chance to save the
1330 * current state of its user interface via this method so that when the user
1331 * returns to activity A, the state of the user interface can be restored
1332 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1334 * <p>Do not confuse this method with activity lifecycle callbacks such as
1335 * {@link #onPause}, which is always called when an activity is being placed
1336 * in the background or on its way to destruction, or {@link #onStop} which
1337 * is called before destruction. One example of when {@link #onPause} and
1338 * {@link #onStop} is called and not this method is when a user navigates back
1339 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1340 * on B because that particular instance will never be restored, so the
1341 * system avoids calling it. An example when {@link #onPause} is called and
1342 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1343 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1344 * killed during the lifetime of B since the state of the user interface of
1345 * A will stay intact.
1347 * <p>The default implementation takes care of most of the UI per-instance
1348 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1349 * view in the hierarchy that has an id, and by saving the id of the currently
1350 * focused view (all of which is restored by the default implementation of
1351 * {@link #onRestoreInstanceState}). If you override this method to save additional
1352 * information not captured by each individual view, you will likely want to
1353 * call through to the default implementation, otherwise be prepared to save
1354 * all of the state of each view yourself.
1356 * <p>If called, this method will occur before {@link #onStop}. There are
1357 * no guarantees about whether it will occur before or after {@link #onPause}.
1359 * @param outState Bundle in which to place your saved state.
1362 * @see #onRestoreInstanceState
1365 protected void onSaveInstanceState(Bundle outState) {
1366 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
1367 Parcelable p = mFragments.saveAllState();
1369 outState.putParcelable(FRAGMENTS_TAG, p);
1371 getApplication().dispatchActivitySaveInstanceState(this, outState);
1375 * This is the same as {@link #onSaveInstanceState} but is called for activities
1376 * created with the attribute {@link android.R.attr#persistableMode} set to
1377 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1378 * in will be saved and presented in {@link #onCreate(Bundle, PersistableBundle)}
1379 * the first time that this activity is restarted following the next device reboot.
1381 * @param outState Bundle in which to place your saved state.
1382 * @param outPersistentState State which will be saved across reboots.
1384 * @see #onSaveInstanceState(Bundle)
1386 * @see #onRestoreInstanceState(Bundle, PersistableBundle)
1389 public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1390 onSaveInstanceState(outState);
1394 * Save the state of any managed dialogs.
1396 * @param outState place to store the saved state.
1398 private void saveManagedDialogs(Bundle outState) {
1399 if (mManagedDialogs == null) {
1403 final int numDialogs = mManagedDialogs.size();
1404 if (numDialogs == 0) {
1408 Bundle dialogState = new Bundle();
1410 int[] ids = new int[mManagedDialogs.size()];
1412 // save each dialog's bundle, gather the ids
1413 for (int i = 0; i < numDialogs; i++) {
1414 final int key = mManagedDialogs.keyAt(i);
1416 final ManagedDialog md = mManagedDialogs.valueAt(i);
1417 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1418 if (md.mArgs != null) {
1419 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1423 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1424 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1429 * Called as part of the activity lifecycle when an activity is going into
1430 * the background, but has not (yet) been killed. The counterpart to
1431 * {@link #onResume}.
1433 * <p>When activity B is launched in front of activity A, this callback will
1434 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1435 * so be sure to not do anything lengthy here.
1437 * <p>This callback is mostly used for saving any persistent state the
1438 * activity is editing, to present a "edit in place" model to the user and
1439 * making sure nothing is lost if there are not enough resources to start
1440 * the new activity without first killing this one. This is also a good
1441 * place to do things like stop animations and other things that consume a
1442 * noticeable amount of CPU in order to make the switch to the next activity
1443 * as fast as possible, or to close resources that are exclusive access
1444 * such as the camera.
1446 * <p>In situations where the system needs more memory it may kill paused
1447 * processes to reclaim resources. Because of this, you should be sure
1448 * that all of your state is saved by the time you return from
1449 * this function. In general {@link #onSaveInstanceState} is used to save
1450 * per-instance state in the activity and this method is used to store
1451 * global persistent data (in content providers, files, etc.)
1453 * <p>After receiving this call you will usually receive a following call
1454 * to {@link #onStop} (after the next activity has been resumed and
1455 * displayed), however in some cases there will be a direct call back to
1456 * {@link #onResume} without going through the stopped state.
1458 * <p><em>Derived classes must call through to the super class's
1459 * implementation of this method. If they do not, an exception will be
1463 * @see #onSaveInstanceState
1467 protected void onPause() {
1468 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this);
1469 getApplication().dispatchActivityPaused(this);
1474 * Called as part of the activity lifecycle when an activity is about to go
1475 * into the background as the result of user choice. For example, when the
1476 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1477 * when an incoming phone call causes the in-call Activity to be automatically
1478 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1479 * the activity being interrupted. In cases when it is invoked, this method
1480 * is called right before the activity's {@link #onPause} callback.
1482 * <p>This callback and {@link #onUserInteraction} are intended to help
1483 * activities manage status bar notifications intelligently; specifically,
1484 * for helping activities determine the proper time to cancel a notfication.
1486 * @see #onUserInteraction()
1488 protected void onUserLeaveHint() {
1492 * Generate a new thumbnail for this activity. This method is called before
1493 * pausing the activity, and should draw into <var>outBitmap</var> the
1494 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1495 * can use the given <var>canvas</var>, which is configured to draw into the
1496 * bitmap, for rendering if desired.
1498 * <p>The default implementation returns fails and does not draw a thumbnail;
1499 * this will result in the platform creating its own thumbnail if needed.
1501 * @param outBitmap The bitmap to contain the thumbnail.
1502 * @param canvas Can be used to render into the bitmap.
1504 * @return Return true if you have drawn into the bitmap; otherwise after
1505 * you return it will be filled with a default thumbnail.
1507 * @see #onCreateDescription
1508 * @see #onSaveInstanceState
1511 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
1516 * Generate a new description for this activity. This method is called
1517 * before pausing the activity and can, if desired, return some textual
1518 * description of its current state to be displayed to the user.
1520 * <p>The default implementation returns null, which will cause you to
1521 * inherit the description from the previous activity. If all activities
1522 * return null, generally the label of the top activity will be used as the
1525 * @return A description of what the user is doing. It should be short and
1526 * sweet (only a few words).
1528 * @see #onCreateThumbnail
1529 * @see #onSaveInstanceState
1533 public CharSequence onCreateDescription() {
1538 * This is called when the user is requesting an assist, to build a full
1539 * {@link Intent#ACTION_ASSIST} Intent with all of the context of the current
1540 * application. You can override this method to place into the bundle anything
1541 * you would like to appear in the {@link Intent#EXTRA_ASSIST_CONTEXT} part
1542 * of the assist Intent.
1544 * <p>This function will be called after any global assist callbacks that had
1545 * been registered with {@link Application#registerOnProvideAssistDataListener
1546 * Application.registerOnProvideAssistDataListener}.
1548 public void onProvideAssistData(Bundle data) {
1552 * This is called when the user is requesting an assist, to provide references
1553 * to content related to the current activity. Before being called, the
1554 * {@code outContent} Intent is filled with the base Intent of the activity (the Intent
1555 * returned by {@link #getIntent()}). The Intent's extras are stripped of any types
1556 * that are not valid for {@link PersistableBundle} or non-framework Parcelables, and
1557 * the flags {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} and
1558 * {@link Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION} are cleared from the Intent.
1560 * <p>Custom implementation may adjust the content intent to better reflect the top-level
1561 * context of the activity, and fill in its ClipData with additional content of
1562 * interest that the user is currently viewing. For example, an image gallery application
1563 * that has launched in to an activity allowing the user to swipe through pictures should
1564 * modify the intent to reference the current image they are looking it; such an
1565 * application when showing a list of pictures should add a ClipData that has
1566 * references to all of the pictures currently visible on screen.</p>
1568 * @param outContent The assist content to return.
1570 public void onProvideAssistContent(AssistContent outContent) {
1574 * Ask to have the current assistant shown to the user. This only works if the calling
1575 * activity is the current foreground activity. It is the same as calling
1576 * {@link android.service.voice.VoiceInteractionService#showSession
1577 * VoiceInteractionService.showSession} and requesting all of the possible context.
1578 * The receiver will always see
1579 * {@link android.service.voice.VoiceInteractionSession#SHOW_SOURCE_APPLICATION} set.
1580 * @return Returns true if the assistant was successfully invoked, else false. For example
1581 * false will be returned if the caller is not the current top activity.
1583 public boolean showAssist(Bundle args) {
1585 return ActivityManagerNative.getDefault().showAssistFromActivity(mToken, args);
1586 } catch (RemoteException e) {
1592 * Called when you are no longer visible to the user. You will next
1593 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1594 * depending on later user activity.
1596 * <p>Note that this method may never be called, in low memory situations
1597 * where the system does not have enough memory to keep your activity's
1598 * process running after its {@link #onPause} method is called.
1600 * <p><em>Derived classes must call through to the super class's
1601 * implementation of this method. If they do not, an exception will be
1606 * @see #onSaveInstanceState
1610 protected void onStop() {
1611 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
1612 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
1613 mActivityTransitionState.onStop();
1614 getApplication().dispatchActivityStopped(this);
1615 mTranslucentCallback = null;
1620 * Perform any final cleanup before an activity is destroyed. This can
1621 * happen either because the activity is finishing (someone called
1622 * {@link #finish} on it, or because the system is temporarily destroying
1623 * this instance of the activity to save space. You can distinguish
1624 * between these two scenarios with the {@link #isFinishing} method.
1626 * <p><em>Note: do not count on this method being called as a place for
1627 * saving data! For example, if an activity is editing data in a content
1628 * provider, those edits should be committed in either {@link #onPause} or
1629 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1630 * free resources like threads that are associated with an activity, so
1631 * that a destroyed activity does not leave such things around while the
1632 * rest of its application is still running. There are situations where
1633 * the system will simply kill the activity's hosting process without
1634 * calling this method (or any others) in it, so it should not be used to
1635 * do things that are intended to remain around after the process goes
1638 * <p><em>Derived classes must call through to the super class's
1639 * implementation of this method. If they do not, an exception will be
1648 protected void onDestroy() {
1649 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
1652 // dismiss any dialogs we are managing.
1653 if (mManagedDialogs != null) {
1654 final int numDialogs = mManagedDialogs.size();
1655 for (int i = 0; i < numDialogs; i++) {
1656 final ManagedDialog md = mManagedDialogs.valueAt(i);
1657 if (md.mDialog.isShowing()) {
1658 md.mDialog.dismiss();
1661 mManagedDialogs = null;
1664 // close any cursors we are managing.
1665 synchronized (mManagedCursors) {
1666 int numCursors = mManagedCursors.size();
1667 for (int i = 0; i < numCursors; i++) {
1668 ManagedCursor c = mManagedCursors.get(i);
1673 mManagedCursors.clear();
1676 // Close any open search dialog
1677 if (mSearchManager != null) {
1678 mSearchManager.stopSearch();
1681 getApplication().dispatchActivityDestroyed(this);
1685 * Report to the system that your app is now fully drawn, purely for diagnostic
1686 * purposes (calling it does not impact the visible behavior of the activity).
1687 * This is only used to help instrument application launch times, so that the
1688 * app can report when it is fully in a usable state; without this, the only thing
1689 * the system itself can determine is the point at which the activity's window
1690 * is <em>first</em> drawn and displayed. To participate in app launch time
1691 * measurement, you should always call this method after first launch (when
1692 * {@link #onCreate(android.os.Bundle)} is called), at the point where you have
1693 * entirely drawn your UI and populated with all of the significant data. You
1694 * can safely call this method any time after first launch as well, in which case
1695 * it will simply be ignored.
1697 public void reportFullyDrawn() {
1698 if (mDoReportFullyDrawn) {
1699 mDoReportFullyDrawn = false;
1701 ActivityManagerNative.getDefault().reportActivityFullyDrawn(mToken);
1702 } catch (RemoteException e) {
1708 * Called by the system when the device configuration changes while your
1709 * activity is running. Note that this will <em>only</em> be called if
1710 * you have selected configurations you would like to handle with the
1711 * {@link android.R.attr#configChanges} attribute in your manifest. If
1712 * any configuration change occurs that is not selected to be reported
1713 * by that attribute, then instead of reporting it the system will stop
1714 * and restart the activity (to have it launched with the new
1717 * <p>At the time that this function has been called, your Resources
1718 * object will have been updated to return resource values matching the
1719 * new configuration.
1721 * @param newConfig The new device configuration.
1723 public void onConfigurationChanged(Configuration newConfig) {
1724 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onConfigurationChanged " + this + ": " + newConfig);
1727 mFragments.dispatchConfigurationChanged(newConfig);
1729 if (mWindow != null) {
1730 // Pass the configuration changed event to the window
1731 mWindow.onConfigurationChanged(newConfig);
1734 if (mActionBar != null) {
1735 // Do this last; the action bar will need to access
1736 // view changes from above.
1737 mActionBar.onConfigurationChanged(newConfig);
1742 * If this activity is being destroyed because it can not handle a
1743 * configuration parameter being changed (and thus its
1744 * {@link #onConfigurationChanged(Configuration)} method is
1745 * <em>not</em> being called), then you can use this method to discover
1746 * the set of changes that have occurred while in the process of being
1747 * destroyed. Note that there is no guarantee that these will be
1748 * accurate (other changes could have happened at any time), so you should
1749 * only use this as an optimization hint.
1751 * @return Returns a bit field of the configuration parameters that are
1752 * changing, as defined by the {@link android.content.res.Configuration}
1755 public int getChangingConfigurations() {
1756 return mConfigChangeFlags;
1760 * Retrieve the non-configuration instance data that was previously
1761 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1762 * be available from the initial {@link #onCreate} and
1763 * {@link #onStart} calls to the new instance, allowing you to extract
1764 * any useful dynamic state from the previous instance.
1766 * <p>Note that the data you retrieve here should <em>only</em> be used
1767 * as an optimization for handling configuration changes. You should always
1768 * be able to handle getting a null pointer back, and an activity must
1769 * still be able to restore itself to its previous state (through the
1770 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1771 * function returns null.
1773 * @return Returns the object previously returned by
1774 * {@link #onRetainNonConfigurationInstance()}.
1776 * @deprecated Use the new {@link Fragment} API
1777 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
1778 * available on older platforms through the Android compatibility package.
1782 public Object getLastNonConfigurationInstance() {
1783 return mLastNonConfigurationInstances != null
1784 ? mLastNonConfigurationInstances.activity : null;
1788 * Called by the system, as part of destroying an
1789 * activity due to a configuration change, when it is known that a new
1790 * instance will immediately be created for the new configuration. You
1791 * can return any object you like here, including the activity instance
1792 * itself, which can later be retrieved by calling
1793 * {@link #getLastNonConfigurationInstance()} in the new activity
1796 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1797 * or later, consider instead using a {@link Fragment} with
1798 * {@link Fragment#setRetainInstance(boolean)
1799 * Fragment.setRetainInstance(boolean}.</em>
1801 * <p>This function is called purely as an optimization, and you must
1802 * not rely on it being called. When it is called, a number of guarantees
1803 * will be made to help optimize configuration switching:
1805 * <li> The function will be called between {@link #onStop} and
1806 * {@link #onDestroy}.
1807 * <li> A new instance of the activity will <em>always</em> be immediately
1808 * created after this one's {@link #onDestroy()} is called. In particular,
1809 * <em>no</em> messages will be dispatched during this time (when the returned
1810 * object does not have an activity to be associated with).
1811 * <li> The object you return here will <em>always</em> be available from
1812 * the {@link #getLastNonConfigurationInstance()} method of the following
1813 * activity instance as described there.
1816 * <p>These guarantees are designed so that an activity can use this API
1817 * to propagate extensive state from the old to new activity instance, from
1818 * loaded bitmaps, to network connections, to evenly actively running
1819 * threads. Note that you should <em>not</em> propagate any data that
1820 * may change based on the configuration, including any data loaded from
1821 * resources such as strings, layouts, or drawables.
1823 * <p>The guarantee of no message handling during the switch to the next
1824 * activity simplifies use with active objects. For example if your retained
1825 * state is an {@link android.os.AsyncTask} you are guaranteed that its
1826 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
1827 * not be called from the call here until you execute the next instance's
1828 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
1829 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
1830 * running in a separate thread.)
1832 * @return Return any Object holding the desired state to propagate to the
1833 * next activity instance.
1835 * @deprecated Use the new {@link Fragment} API
1836 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
1837 * available on older platforms through the Android compatibility package.
1839 public Object onRetainNonConfigurationInstance() {
1844 * Retrieve the non-configuration instance data that was previously
1845 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1846 * be available from the initial {@link #onCreate} and
1847 * {@link #onStart} calls to the new instance, allowing you to extract
1848 * any useful dynamic state from the previous instance.
1850 * <p>Note that the data you retrieve here should <em>only</em> be used
1851 * as an optimization for handling configuration changes. You should always
1852 * be able to handle getting a null pointer back, and an activity must
1853 * still be able to restore itself to its previous state (through the
1854 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1855 * function returns null.
1857 * @return Returns the object previously returned by
1858 * {@link #onRetainNonConfigurationChildInstances()}
1861 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1862 return mLastNonConfigurationInstances != null
1863 ? mLastNonConfigurationInstances.children : null;
1867 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1868 * it should return either a mapping from child activity id strings to arbitrary objects,
1869 * or null. This method is intended to be used by Activity framework subclasses that control a
1870 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1871 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1874 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1878 NonConfigurationInstances retainNonConfigurationInstances() {
1879 Object activity = onRetainNonConfigurationInstance();
1880 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1881 List<Fragment> fragments = mFragments.retainNonConfig();
1882 ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
1883 if (activity == null && children == null && fragments == null && loaders == null
1884 && mVoiceInteractor == null) {
1888 NonConfigurationInstances nci = new NonConfigurationInstances();
1889 nci.activity = activity;
1890 nci.children = children;
1891 nci.fragments = fragments;
1892 nci.loaders = loaders;
1893 if (mVoiceInteractor != null) {
1894 mVoiceInteractor.retainInstance();
1895 nci.voiceInteractor = mVoiceInteractor;
1900 public void onLowMemory() {
1901 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onLowMemory " + this);
1903 mFragments.dispatchLowMemory();
1906 public void onTrimMemory(int level) {
1907 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onTrimMemory " + this + ": " + level);
1909 mFragments.dispatchTrimMemory(level);
1913 * Return the FragmentManager for interacting with fragments associated
1914 * with this activity.
1916 public FragmentManager getFragmentManager() {
1917 return mFragments.getFragmentManager();
1921 * Called when a Fragment is being attached to this activity, immediately
1922 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1923 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1925 public void onAttachFragment(Fragment fragment) {
1930 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1931 * that gives the resulting {@link Cursor} to call
1932 * {@link #startManagingCursor} so that the activity will manage its
1933 * lifecycle for you.
1935 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1936 * or later, consider instead using {@link LoaderManager} instead, available
1937 * via {@link #getLoaderManager()}.</em>
1939 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
1940 * this method, because the activity will do that for you at the appropriate time. However, if
1941 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
1942 * not</em> automatically close the cursor and, in that case, you must call
1943 * {@link Cursor#close()}.</p>
1945 * @param uri The URI of the content provider to query.
1946 * @param projection List of columns to return.
1947 * @param selection SQL WHERE clause.
1948 * @param sortOrder SQL ORDER BY clause.
1950 * @return The Cursor that was returned by query().
1952 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1953 * @see #startManagingCursor
1956 * @deprecated Use {@link CursorLoader} instead.
1959 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1961 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1963 startManagingCursor(c);
1970 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1971 * that gives the resulting {@link Cursor} to call
1972 * {@link #startManagingCursor} so that the activity will manage its
1973 * lifecycle for you.
1975 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1976 * or later, consider instead using {@link LoaderManager} instead, available
1977 * via {@link #getLoaderManager()}.</em>
1979 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
1980 * this method, because the activity will do that for you at the appropriate time. However, if
1981 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
1982 * not</em> automatically close the cursor and, in that case, you must call
1983 * {@link Cursor#close()}.</p>
1985 * @param uri The URI of the content provider to query.
1986 * @param projection List of columns to return.
1987 * @param selection SQL WHERE clause.
1988 * @param selectionArgs The arguments to selection, if any ?s are pesent
1989 * @param sortOrder SQL ORDER BY clause.
1991 * @return The Cursor that was returned by query().
1993 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1994 * @see #startManagingCursor
1996 * @deprecated Use {@link CursorLoader} instead.
1999 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
2000 String[] selectionArgs, String sortOrder) {
2001 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
2003 startManagingCursor(c);
2009 * This method allows the activity to take care of managing the given
2010 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
2011 * That is, when the activity is stopped it will automatically call
2012 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
2013 * it will call {@link Cursor#requery} for you. When the activity is
2014 * destroyed, all managed Cursors will be closed automatically.
2016 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2017 * or later, consider instead using {@link LoaderManager} instead, available
2018 * via {@link #getLoaderManager()}.</em>
2020 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on cursor obtained from
2021 * {@link #managedQuery}, because the activity will do that for you at the appropriate time.
2022 * However, if you call {@link #stopManagingCursor} on a cursor from a managed query, the system
2023 * <em>will not</em> automatically close the cursor and, in that case, you must call
2024 * {@link Cursor#close()}.</p>
2026 * @param c The Cursor to be managed.
2028 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
2029 * @see #stopManagingCursor
2031 * @deprecated Use the new {@link android.content.CursorLoader} class with
2032 * {@link LoaderManager} instead; this is also
2033 * available on older platforms through the Android compatibility package.
2036 public void startManagingCursor(Cursor c) {
2037 synchronized (mManagedCursors) {
2038 mManagedCursors.add(new ManagedCursor(c));
2043 * Given a Cursor that was previously given to
2044 * {@link #startManagingCursor}, stop the activity's management of that
2047 * <p><strong>Warning:</strong> After calling this method on a cursor from a managed query,
2048 * the system <em>will not</em> automatically close the cursor and you must call
2049 * {@link Cursor#close()}.</p>
2051 * @param c The Cursor that was being managed.
2053 * @see #startManagingCursor
2055 * @deprecated Use the new {@link android.content.CursorLoader} class with
2056 * {@link LoaderManager} instead; this is also
2057 * available on older platforms through the Android compatibility package.
2060 public void stopManagingCursor(Cursor c) {
2061 synchronized (mManagedCursors) {
2062 final int N = mManagedCursors.size();
2063 for (int i=0; i<N; i++) {
2064 ManagedCursor mc = mManagedCursors.get(i);
2065 if (mc.mCursor == c) {
2066 mManagedCursors.remove(i);
2074 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
2079 public void setPersistent(boolean isPersistent) {
2083 * Finds a view that was identified by the id attribute from the XML that
2084 * was processed in {@link #onCreate}.
2086 * @return The view if found or null otherwise.
2089 public View findViewById(@IdRes int id) {
2090 return getWindow().findViewById(id);
2094 * Retrieve a reference to this activity's ActionBar.
2096 * @return The Activity's ActionBar, or null if it does not have one.
2099 public ActionBar getActionBar() {
2100 initWindowDecorActionBar();
2105 * Set a {@link android.widget.Toolbar Toolbar} to act as the {@link ActionBar} for this
2108 * <p>When set to a non-null value the {@link #getActionBar()} method will return
2109 * an {@link ActionBar} object that can be used to control the given toolbar as if it were
2110 * a traditional window decor action bar. The toolbar's menu will be populated with the
2111 * Activity's options menu and the navigation button will be wired through the standard
2112 * {@link android.R.id#home home} menu select action.</p>
2114 * <p>In order to use a Toolbar within the Activity's window content the application
2115 * must not request the window feature {@link Window#FEATURE_ACTION_BAR FEATURE_ACTION_BAR}.</p>
2117 * @param toolbar Toolbar to set as the Activity's action bar
2119 public void setActionBar(@Nullable Toolbar toolbar) {
2120 if (getActionBar() instanceof WindowDecorActionBar) {
2121 throw new IllegalStateException("This Activity already has an action bar supplied " +
2122 "by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " +
2123 "android:windowActionBar to false in your theme to use a Toolbar instead.");
2125 // Clear out the MenuInflater to make sure that it is valid for the new Action Bar
2126 mMenuInflater = null;
2128 ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this);
2130 mWindow.setCallback(tbab.getWrappedWindowCallback());
2131 mActionBar.invalidateOptionsMenu();
2135 * Creates a new ActionBar, locates the inflated ActionBarView,
2136 * initializes the ActionBar with the view, and sets mActionBar.
2138 private void initWindowDecorActionBar() {
2139 Window window = getWindow();
2141 // Initializing the window decor can change window feature flags.
2142 // Make sure that we have the correct set before performing the test below.
2143 window.getDecorView();
2145 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
2149 mActionBar = new WindowDecorActionBar(this);
2150 mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
2152 mWindow.setDefaultIcon(mActivityInfo.getIconResource());
2153 mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
2157 * Set the activity content from a layout resource. The resource will be
2158 * inflated, adding all top-level views to the activity.
2160 * @param layoutResID Resource ID to be inflated.
2162 * @see #setContentView(android.view.View)
2163 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2165 public void setContentView(@LayoutRes int layoutResID) {
2166 getWindow().setContentView(layoutResID);
2167 initWindowDecorActionBar();
2171 * Set the activity content to an explicit view. This view is placed
2172 * directly into the activity's view hierarchy. It can itself be a complex
2173 * view hierarchy. When calling this method, the layout parameters of the
2174 * specified view are ignored. Both the width and the height of the view are
2175 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
2176 * your own layout parameters, invoke
2177 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
2180 * @param view The desired content to display.
2182 * @see #setContentView(int)
2183 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2185 public void setContentView(View view) {
2186 getWindow().setContentView(view);
2187 initWindowDecorActionBar();
2191 * Set the activity content to an explicit view. This view is placed
2192 * directly into the activity's view hierarchy. It can itself be a complex
2195 * @param view The desired content to display.
2196 * @param params Layout parameters for the view.
2198 * @see #setContentView(android.view.View)
2199 * @see #setContentView(int)
2201 public void setContentView(View view, ViewGroup.LayoutParams params) {
2202 getWindow().setContentView(view, params);
2203 initWindowDecorActionBar();
2207 * Add an additional content view to the activity. Added after any existing
2208 * ones in the activity -- existing views are NOT removed.
2210 * @param view The desired content to display.
2211 * @param params Layout parameters for the view.
2213 public void addContentView(View view, ViewGroup.LayoutParams params) {
2214 getWindow().addContentView(view, params);
2215 initWindowDecorActionBar();
2219 * Retrieve the {@link TransitionManager} responsible for default transitions in this window.
2220 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2222 * <p>This method will return non-null after content has been initialized (e.g. by using
2223 * {@link #setContentView}) if {@link Window#FEATURE_CONTENT_TRANSITIONS} has been granted.</p>
2225 * @return This window's content TransitionManager or null if none is set.
2227 public TransitionManager getContentTransitionManager() {
2228 return getWindow().getTransitionManager();
2232 * Set the {@link TransitionManager} to use for default transitions in this window.
2233 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2235 * @param tm The TransitionManager to use for scene changes.
2237 public void setContentTransitionManager(TransitionManager tm) {
2238 getWindow().setTransitionManager(tm);
2242 * Retrieve the {@link Scene} representing this window's current content.
2243 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2245 * <p>This method will return null if the current content is not represented by a Scene.</p>
2247 * @return Current Scene being shown or null
2249 public Scene getContentScene() {
2250 return getWindow().getContentScene();
2254 * Sets whether this activity is finished when touched outside its window's
2257 public void setFinishOnTouchOutside(boolean finish) {
2258 mWindow.setCloseOnTouchOutside(finish);
2263 DEFAULT_KEYS_DISABLE,
2264 DEFAULT_KEYS_DIALER,
2265 DEFAULT_KEYS_SHORTCUT,
2266 DEFAULT_KEYS_SEARCH_LOCAL,
2267 DEFAULT_KEYS_SEARCH_GLOBAL})
2268 @Retention(RetentionPolicy.SOURCE)
2269 @interface DefaultKeyMode {}
2272 * Use with {@link #setDefaultKeyMode} to turn off default handling of
2275 * @see #setDefaultKeyMode
2277 static public final int DEFAULT_KEYS_DISABLE = 0;
2279 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
2282 * @see #setDefaultKeyMode
2284 static public final int DEFAULT_KEYS_DIALER = 1;
2286 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
2287 * default key handling.
2289 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
2291 * @see #setDefaultKeyMode
2293 static public final int DEFAULT_KEYS_SHORTCUT = 2;
2295 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2296 * will start an application-defined search. (If the application or activity does not
2297 * actually define a search, the the keys will be ignored.)
2299 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2301 * @see #setDefaultKeyMode
2303 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
2306 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2307 * will start a global search (typically web search, but some platforms may define alternate
2308 * methods for global search)
2310 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2312 * @see #setDefaultKeyMode
2314 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
2317 * Select the default key handling for this activity. This controls what
2318 * will happen to key events that are not otherwise handled. The default
2319 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
2320 * floor. Other modes allow you to launch the dialer
2321 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
2322 * menu without requiring the menu key be held down
2323 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
2324 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
2326 * <p>Note that the mode selected here does not impact the default
2327 * handling of system keys, such as the "back" and "menu" keys, and your
2328 * activity and its views always get a first chance to receive and handle
2329 * all application keys.
2331 * @param mode The desired default key mode constant.
2333 * @see #DEFAULT_KEYS_DISABLE
2334 * @see #DEFAULT_KEYS_DIALER
2335 * @see #DEFAULT_KEYS_SHORTCUT
2336 * @see #DEFAULT_KEYS_SEARCH_LOCAL
2337 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
2340 public final void setDefaultKeyMode(@DefaultKeyMode int mode) {
2341 mDefaultKeyMode = mode;
2343 // Some modes use a SpannableStringBuilder to track & dispatch input events
2344 // This list must remain in sync with the switch in onKeyDown()
2346 case DEFAULT_KEYS_DISABLE:
2347 case DEFAULT_KEYS_SHORTCUT:
2348 mDefaultKeySsb = null; // not used in these modes
2350 case DEFAULT_KEYS_DIALER:
2351 case DEFAULT_KEYS_SEARCH_LOCAL:
2352 case DEFAULT_KEYS_SEARCH_GLOBAL:
2353 mDefaultKeySsb = new SpannableStringBuilder();
2354 Selection.setSelection(mDefaultKeySsb,0);
2357 throw new IllegalArgumentException();
2362 * Called when a key was pressed down and not handled by any of the views
2363 * inside of the activity. So, for example, key presses while the cursor
2364 * is inside a TextView will not trigger the event (unless it is a navigation
2365 * to another object) because TextView handles its own key presses.
2367 * <p>If the focused view didn't want this event, this method is called.
2369 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
2370 * by calling {@link #onBackPressed()}, though the behavior varies based
2371 * on the application compatibility mode: for
2372 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
2373 * it will set up the dispatch to call {@link #onKeyUp} where the action
2374 * will be performed; for earlier applications, it will perform the
2375 * action immediately in on-down, as those versions of the platform
2378 * <p>Other additional default key handling may be performed
2379 * if configured with {@link #setDefaultKeyMode}.
2381 * @return Return <code>true</code> to prevent this event from being propagated
2382 * further, or <code>false</code> to indicate that you have not handled
2383 * this event and it should continue to be propagated.
2385 * @see android.view.KeyEvent
2387 public boolean onKeyDown(int keyCode, KeyEvent event) {
2388 if (keyCode == KeyEvent.KEYCODE_BACK) {
2389 if (getApplicationInfo().targetSdkVersion
2390 >= Build.VERSION_CODES.ECLAIR) {
2391 event.startTracking();
2398 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
2400 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
2401 Window w = getWindow();
2402 if (w.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
2403 w.performPanelShortcut(Window.FEATURE_OPTIONS_PANEL, keyCode, event,
2404 Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
2409 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
2410 boolean clearSpannable = false;
2412 if ((event.getRepeatCount() != 0) || event.isSystem()) {
2413 clearSpannable = true;
2416 handled = TextKeyListener.getInstance().onKeyDown(
2417 null, mDefaultKeySsb, keyCode, event);
2418 if (handled && mDefaultKeySsb.length() > 0) {
2419 // something useable has been typed - dispatch it now.
2421 final String str = mDefaultKeySsb.toString();
2422 clearSpannable = true;
2424 switch (mDefaultKeyMode) {
2425 case DEFAULT_KEYS_DIALER:
2426 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
2427 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2428 startActivity(intent);
2430 case DEFAULT_KEYS_SEARCH_LOCAL:
2431 startSearch(str, false, null, false);
2433 case DEFAULT_KEYS_SEARCH_GLOBAL:
2434 startSearch(str, false, null, true);
2439 if (clearSpannable) {
2440 mDefaultKeySsb.clear();
2441 mDefaultKeySsb.clearSpans();
2442 Selection.setSelection(mDefaultKeySsb,0);
2449 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2450 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2453 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2458 * Called when a key was released and not handled by any of the views
2459 * inside of the activity. So, for example, key presses while the cursor
2460 * is inside a TextView will not trigger the event (unless it is a navigation
2461 * to another object) because TextView handles its own key presses.
2463 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2466 * @return Return <code>true</code> to prevent this event from being propagated
2467 * further, or <code>false</code> to indicate that you have not handled
2468 * this event and it should continue to be propagated.
2472 public boolean onKeyUp(int keyCode, KeyEvent event) {
2473 if (getApplicationInfo().targetSdkVersion
2474 >= Build.VERSION_CODES.ECLAIR) {
2475 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2476 && !event.isCanceled()) {
2485 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2486 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2489 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2494 * Called when the activity has detected the user's press of the back
2495 * key. The default implementation simply finishes the current activity,
2496 * but you can override this to do whatever you want.
2498 public void onBackPressed() {
2499 if (mActionBar != null && mActionBar.collapseActionView()) {
2503 if (!mFragments.getFragmentManager().popBackStackImmediate()) {
2504 finishAfterTransition();
2509 * Called when a key shortcut event is not handled by any of the views in the Activity.
2510 * Override this method to implement global key shortcuts for the Activity.
2511 * Key shortcuts can also be implemented by setting the
2512 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
2514 * @param keyCode The value in event.getKeyCode().
2515 * @param event Description of the key event.
2516 * @return True if the key shortcut was handled.
2518 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2519 // Let the Action Bar have a chance at handling the shortcut.
2520 ActionBar actionBar = getActionBar();
2521 return (actionBar != null && actionBar.onKeyShortcut(keyCode, event));
2525 * Called when a touch screen event was not handled by any of the views
2526 * under it. This is most useful to process touch events that happen
2527 * outside of your window bounds, where there is no view to receive it.
2529 * @param event The touch screen event being processed.
2531 * @return Return true if you have consumed the event, false if you haven't.
2532 * The default implementation always returns false.
2534 public boolean onTouchEvent(MotionEvent event) {
2535 if (mWindow.shouldCloseOnTouch(this, event)) {
2544 * Called when the trackball was moved and not handled by any of the
2545 * views inside of the activity. So, for example, if the trackball moves
2546 * while focus is on a button, you will receive a call here because
2547 * buttons do not normally do anything with trackball events. The call
2548 * here happens <em>before</em> trackball movements are converted to
2549 * DPAD key events, which then get sent back to the view hierarchy, and
2550 * will be processed at the point for things like focus navigation.
2552 * @param event The trackball event being processed.
2554 * @return Return true if you have consumed the event, false if you haven't.
2555 * The default implementation always returns false.
2557 public boolean onTrackballEvent(MotionEvent event) {
2562 * Called when a generic motion event was not handled by any of the
2563 * views inside of the activity.
2565 * Generic motion events describe joystick movements, mouse hovers, track pad
2566 * touches, scroll wheel movements and other input events. The
2567 * {@link MotionEvent#getSource() source} of the motion event specifies
2568 * the class of input that was received. Implementations of this method
2569 * must examine the bits in the source before processing the event.
2570 * The following code example shows how this is done.
2572 * Generic motion events with source class
2573 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
2574 * are delivered to the view under the pointer. All other generic motion events are
2575 * delivered to the focused view.
2577 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
2578 * handle this event.
2581 * @param event The generic motion event being processed.
2583 * @return Return true if you have consumed the event, false if you haven't.
2584 * The default implementation always returns false.
2586 public boolean onGenericMotionEvent(MotionEvent event) {
2591 * Called whenever a key, touch, or trackball event is dispatched to the
2592 * activity. Implement this method if you wish to know that the user has
2593 * interacted with the device in some way while your activity is running.
2594 * This callback and {@link #onUserLeaveHint} are intended to help
2595 * activities manage status bar notifications intelligently; specifically,
2596 * for helping activities determine the proper time to cancel a notfication.
2598 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2599 * be accompanied by calls to {@link #onUserInteraction}. This
2600 * ensures that your activity will be told of relevant user activity such
2601 * as pulling down the notification pane and touching an item there.
2603 * <p>Note that this callback will be invoked for the touch down action
2604 * that begins a touch gesture, but may not be invoked for the touch-moved
2605 * and touch-up actions that follow.
2607 * @see #onUserLeaveHint()
2609 public void onUserInteraction() {
2612 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2613 // Update window manager if: we have a view, that view is
2614 // attached to its parent (which will be a RootView), and
2615 // this activity is not embedded.
2616 if (mParent == null) {
2617 View decor = mDecor;
2618 if (decor != null && decor.getParent() != null) {
2619 getWindowManager().updateViewLayout(decor, params);
2624 public void onContentChanged() {
2628 * Called when the current {@link Window} of the activity gains or loses
2629 * focus. This is the best indicator of whether this activity is visible
2630 * to the user. The default implementation clears the key tracking
2631 * state, so should always be called.
2633 * <p>Note that this provides information about global focus state, which
2634 * is managed independently of activity lifecycles. As such, while focus
2635 * changes will generally have some relation to lifecycle changes (an
2636 * activity that is stopped will not generally get window focus), you
2637 * should not rely on any particular order between the callbacks here and
2638 * those in the other lifecycle methods such as {@link #onResume}.
2640 * <p>As a general rule, however, a resumed activity will have window
2641 * focus... unless it has displayed other dialogs or popups that take
2642 * input focus, in which case the activity itself will not have focus
2643 * when the other windows have it. Likewise, the system may display
2644 * system-level windows (such as the status bar notification panel or
2645 * a system alert) which will temporarily take window input focus without
2646 * pausing the foreground activity.
2648 * @param hasFocus Whether the window of this activity has focus.
2650 * @see #hasWindowFocus()
2652 * @see View#onWindowFocusChanged(boolean)
2654 public void onWindowFocusChanged(boolean hasFocus) {
2658 * Called when the main window associated with the activity has been
2659 * attached to the window manager.
2660 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2661 * for more information.
2662 * @see View#onAttachedToWindow
2664 public void onAttachedToWindow() {
2668 * Called when the main window associated with the activity has been
2669 * detached from the window manager.
2670 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2671 * for more information.
2672 * @see View#onDetachedFromWindow
2674 public void onDetachedFromWindow() {
2678 * Returns true if this activity's <em>main</em> window currently has window focus.
2679 * Note that this is not the same as the view itself having focus.
2681 * @return True if this activity's main window currently has window focus.
2683 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2685 public boolean hasWindowFocus() {
2686 Window w = getWindow();
2688 View d = w.getDecorView();
2690 return d.hasWindowFocus();
2697 * Called when the main window associated with the activity has been dismissed.
2701 public void onWindowDismissed() {
2706 * Called to process key events. You can override this to intercept all
2707 * key events before they are dispatched to the window. Be sure to call
2708 * this implementation for key events that should be handled normally.
2710 * @param event The key event.
2712 * @return boolean Return true if this event was consumed.
2714 public boolean dispatchKeyEvent(KeyEvent event) {
2715 onUserInteraction();
2717 // Let action bars open menus in response to the menu key prioritized over
2718 // the window handling it
2719 if (event.getKeyCode() == KeyEvent.KEYCODE_MENU &&
2720 mActionBar != null && mActionBar.onMenuKeyEvent(event)) {
2724 Window win = getWindow();
2725 if (win.superDispatchKeyEvent(event)) {
2728 View decor = mDecor;
2729 if (decor == null) decor = win.getDecorView();
2730 return event.dispatch(this, decor != null
2731 ? decor.getKeyDispatcherState() : null, this);
2735 * Called to process a key shortcut event.
2736 * You can override this to intercept all key shortcut events before they are
2737 * dispatched to the window. Be sure to call this implementation for key shortcut
2738 * events that should be handled normally.
2740 * @param event The key shortcut event.
2741 * @return True if this event was consumed.
2743 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
2744 onUserInteraction();
2745 if (getWindow().superDispatchKeyShortcutEvent(event)) {
2748 return onKeyShortcut(event.getKeyCode(), event);
2752 * Called to process touch screen events. You can override this to
2753 * intercept all touch screen events before they are dispatched to the
2754 * window. Be sure to call this implementation for touch screen events
2755 * that should be handled normally.
2757 * @param ev The touch screen event.
2759 * @return boolean Return true if this event was consumed.
2761 public boolean dispatchTouchEvent(MotionEvent ev) {
2762 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2763 onUserInteraction();
2765 if (getWindow().superDispatchTouchEvent(ev)) {
2768 return onTouchEvent(ev);
2772 * Called to process trackball events. You can override this to
2773 * intercept all trackball events before they are dispatched to the
2774 * window. Be sure to call this implementation for trackball events
2775 * that should be handled normally.
2777 * @param ev The trackball event.
2779 * @return boolean Return true if this event was consumed.
2781 public boolean dispatchTrackballEvent(MotionEvent ev) {
2782 onUserInteraction();
2783 if (getWindow().superDispatchTrackballEvent(ev)) {
2786 return onTrackballEvent(ev);
2790 * Called to process generic motion events. You can override this to
2791 * intercept all generic motion events before they are dispatched to the
2792 * window. Be sure to call this implementation for generic motion events
2793 * that should be handled normally.
2795 * @param ev The generic motion event.
2797 * @return boolean Return true if this event was consumed.
2799 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
2800 onUserInteraction();
2801 if (getWindow().superDispatchGenericMotionEvent(ev)) {
2804 return onGenericMotionEvent(ev);
2807 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2808 event.setClassName(getClass().getName());
2809 event.setPackageName(getPackageName());
2811 LayoutParams params = getWindow().getAttributes();
2812 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2813 (params.height == LayoutParams.MATCH_PARENT);
2814 event.setFullScreen(isFullScreen);
2816 CharSequence title = getTitle();
2817 if (!TextUtils.isEmpty(title)) {
2818 event.getText().add(title);
2825 * Default implementation of
2826 * {@link android.view.Window.Callback#onCreatePanelView}
2827 * for activities. This
2828 * simply returns null so that all panel sub-windows will have the default
2832 public View onCreatePanelView(int featureId) {
2837 * Default implementation of
2838 * {@link android.view.Window.Callback#onCreatePanelMenu}
2839 * for activities. This calls through to the new
2840 * {@link #onCreateOptionsMenu} method for the
2841 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2842 * so that subclasses of Activity don't need to deal with feature codes.
2844 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2845 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
2846 boolean show = onCreateOptionsMenu(menu);
2847 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2854 * Default implementation of
2855 * {@link android.view.Window.Callback#onPreparePanel}
2856 * for activities. This
2857 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2858 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2859 * panel, so that subclasses of
2860 * Activity don't need to deal with feature codes.
2862 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2863 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2864 boolean goforit = onPrepareOptionsMenu(menu);
2865 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
2874 * @return The default implementation returns true.
2876 public boolean onMenuOpened(int featureId, Menu menu) {
2877 if (featureId == Window.FEATURE_ACTION_BAR) {
2878 initWindowDecorActionBar();
2879 if (mActionBar != null) {
2880 mActionBar.dispatchMenuVisibilityChanged(true);
2882 Log.e(TAG, "Tried to open action bar menu with no action bar");
2889 * Default implementation of
2890 * {@link android.view.Window.Callback#onMenuItemSelected}
2891 * for activities. This calls through to the new
2892 * {@link #onOptionsItemSelected} method for the
2893 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2894 * panel, so that subclasses of
2895 * Activity don't need to deal with feature codes.
2897 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2898 CharSequence titleCondensed = item.getTitleCondensed();
2900 switch (featureId) {
2901 case Window.FEATURE_OPTIONS_PANEL:
2902 // Put event logging here so it gets called even if subclass
2903 // doesn't call through to superclass's implmeentation of each
2904 // of these methods below
2905 if(titleCondensed != null) {
2906 EventLog.writeEvent(50000, 0, titleCondensed.toString());
2908 if (onOptionsItemSelected(item)) {
2911 if (mFragments.dispatchOptionsItemSelected(item)) {
2914 if (item.getItemId() == android.R.id.home && mActionBar != null &&
2915 (mActionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
2916 if (mParent == null) {
2917 return onNavigateUp();
2919 return mParent.onNavigateUpFromChild(this);
2924 case Window.FEATURE_CONTEXT_MENU:
2925 if(titleCondensed != null) {
2926 EventLog.writeEvent(50000, 1, titleCondensed.toString());
2928 if (onContextItemSelected(item)) {
2931 return mFragments.dispatchContextItemSelected(item);
2939 * Default implementation of
2940 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2941 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2942 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2943 * so that subclasses of Activity don't need to deal with feature codes.
2944 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2945 * {@link #onContextMenuClosed(Menu)} will be called.
2947 public void onPanelClosed(int featureId, Menu menu) {
2948 switch (featureId) {
2949 case Window.FEATURE_OPTIONS_PANEL:
2950 mFragments.dispatchOptionsMenuClosed(menu);
2951 onOptionsMenuClosed(menu);
2954 case Window.FEATURE_CONTEXT_MENU:
2955 onContextMenuClosed(menu);
2958 case Window.FEATURE_ACTION_BAR:
2959 initWindowDecorActionBar();
2960 mActionBar.dispatchMenuVisibilityChanged(false);
2966 * Declare that the options menu has changed, so should be recreated.
2967 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2968 * time it needs to be displayed.
2970 public void invalidateOptionsMenu() {
2971 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
2972 (mActionBar == null || !mActionBar.invalidateOptionsMenu())) {
2973 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2978 * Initialize the contents of the Activity's standard options menu. You
2979 * should place your menu items in to <var>menu</var>.
2981 * <p>This is only called once, the first time the options menu is
2982 * displayed. To update the menu every time it is displayed, see
2983 * {@link #onPrepareOptionsMenu}.
2985 * <p>The default implementation populates the menu with standard system
2986 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2987 * they will be correctly ordered with application-defined menu items.
2988 * Deriving classes should always call through to the base implementation.
2990 * <p>You can safely hold on to <var>menu</var> (and any items created
2991 * from it), making modifications to it as desired, until the next
2992 * time onCreateOptionsMenu() is called.
2994 * <p>When you add items to the menu, you can implement the Activity's
2995 * {@link #onOptionsItemSelected} method to handle them there.
2997 * @param menu The options menu in which you place your items.
2999 * @return You must return true for the menu to be displayed;
3000 * if you return false it will not be shown.
3002 * @see #onPrepareOptionsMenu
3003 * @see #onOptionsItemSelected
3005 public boolean onCreateOptionsMenu(Menu menu) {
3006 if (mParent != null) {
3007 return mParent.onCreateOptionsMenu(menu);
3013 * Prepare the Screen's standard options menu to be displayed. This is
3014 * called right before the menu is shown, every time it is shown. You can
3015 * use this method to efficiently enable/disable items or otherwise
3016 * dynamically modify the contents.
3018 * <p>The default implementation updates the system menu items based on the
3019 * activity's state. Deriving classes should always call through to the
3020 * base class implementation.
3022 * @param menu The options menu as last shown or first initialized by
3023 * onCreateOptionsMenu().
3025 * @return You must return true for the menu to be displayed;
3026 * if you return false it will not be shown.
3028 * @see #onCreateOptionsMenu
3030 public boolean onPrepareOptionsMenu(Menu menu) {
3031 if (mParent != null) {
3032 return mParent.onPrepareOptionsMenu(menu);
3038 * This hook is called whenever an item in your options menu is selected.
3039 * The default implementation simply returns false to have the normal
3040 * processing happen (calling the item's Runnable or sending a message to
3041 * its Handler as appropriate). You can use this method for any items
3042 * for which you would like to do processing without those other
3045 * <p>Derived classes should call through to the base class for it to
3046 * perform the default menu handling.</p>
3048 * @param item The menu item that was selected.
3050 * @return boolean Return false to allow normal menu processing to
3051 * proceed, true to consume it here.
3053 * @see #onCreateOptionsMenu
3055 public boolean onOptionsItemSelected(MenuItem item) {
3056 if (mParent != null) {
3057 return mParent.onOptionsItemSelected(item);
3063 * This method is called whenever the user chooses to navigate Up within your application's
3064 * activity hierarchy from the action bar.
3066 * <p>If the attribute {@link android.R.attr#parentActivityName parentActivityName}
3067 * was specified in the manifest for this activity or an activity-alias to it,
3068 * default Up navigation will be handled automatically. If any activity
3069 * along the parent chain requires extra Intent arguments, the Activity subclass
3070 * should override the method {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}
3071 * to supply those arguments.</p>
3073 * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
3074 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
3075 * from the design guide for more information about navigating within your app.</p>
3077 * <p>See the {@link TaskStackBuilder} class and the Activity methods
3078 * {@link #getParentActivityIntent()}, {@link #shouldUpRecreateTask(Intent)}, and
3079 * {@link #navigateUpTo(Intent)} for help implementing custom Up navigation.
3080 * The AppNavigation sample application in the Android SDK is also available for reference.</p>
3082 * @return true if Up navigation completed successfully and this Activity was finished,
3085 public boolean onNavigateUp() {
3086 // Automatically handle hierarchical Up navigation if the proper
3087 // metadata is available.
3088 Intent upIntent = getParentActivityIntent();
3089 if (upIntent != null) {
3090 if (mActivityInfo.taskAffinity == null) {
3091 // Activities with a null affinity are special; they really shouldn't
3092 // specify a parent activity intent in the first place. Just finish
3093 // the current activity and call it a day.
3095 } else if (shouldUpRecreateTask(upIntent)) {
3096 TaskStackBuilder b = TaskStackBuilder.create(this);
3097 onCreateNavigateUpTaskStack(b);
3098 onPrepareNavigateUpTaskStack(b);
3099 b.startActivities();
3101 // We can't finishAffinity if we have a result.
3102 // Fall back and simply finish the current activity instead.
3103 if (mResultCode != RESULT_CANCELED || mResultData != null) {
3104 // Tell the developer what's going on to avoid hair-pulling.
3105 Log.i(TAG, "onNavigateUp only finishing topmost activity to return a result");
3111 navigateUpTo(upIntent);
3119 * This is called when a child activity of this one attempts to navigate up.
3120 * The default implementation simply calls onNavigateUp() on this activity (the parent).
3122 * @param child The activity making the call.
3124 public boolean onNavigateUpFromChild(Activity child) {
3125 return onNavigateUp();
3129 * Define the synthetic task stack that will be generated during Up navigation from
3132 * <p>The default implementation of this method adds the parent chain of this activity
3133 * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications
3134 * may choose to override this method to construct the desired task stack in a different
3137 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
3138 * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent
3139 * returned by {@link #getParentActivityIntent()}.</p>
3141 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
3142 * by the manifest should override {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}.</p>
3144 * @param builder An empty TaskStackBuilder - the application should add intents representing
3145 * the desired task stack
3147 public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) {
3148 builder.addParentStack(this);
3152 * Prepare the synthetic task stack that will be generated during Up navigation
3153 * from a different task.
3155 * <p>This method receives the {@link TaskStackBuilder} with the constructed series of
3156 * Intents as generated by {@link #onCreateNavigateUpTaskStack(TaskStackBuilder)}.
3157 * If any extra data should be added to these intents before launching the new task,
3158 * the application should override this method and add that data here.</p>
3160 * @param builder A TaskStackBuilder that has been populated with Intents by
3161 * onCreateNavigateUpTaskStack.
3163 public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) {
3167 * This hook is called whenever the options menu is being closed (either by the user canceling
3168 * the menu with the back/menu button, or when an item is selected).
3170 * @param menu The options menu as last shown or first initialized by
3171 * onCreateOptionsMenu().
3173 public void onOptionsMenuClosed(Menu menu) {
3174 if (mParent != null) {
3175 mParent.onOptionsMenuClosed(menu);
3180 * Programmatically opens the options menu. If the options menu is already
3181 * open, this method does nothing.
3183 public void openOptionsMenu() {
3184 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3185 (mActionBar == null || !mActionBar.openOptionsMenu())) {
3186 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
3191 * Progammatically closes the options menu. If the options menu is already
3192 * closed, this method does nothing.
3194 public void closeOptionsMenu() {
3195 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
3196 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
3201 * Called when a context menu for the {@code view} is about to be shown.
3202 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
3203 * time the context menu is about to be shown and should be populated for
3204 * the view (or item inside the view for {@link AdapterView} subclasses,
3205 * this can be found in the {@code menuInfo})).
3207 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
3208 * item has been selected.
3210 * It is not safe to hold onto the context menu after this method returns.
3213 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
3217 * Registers a context menu to be shown for the given view (multiple views
3218 * can show the context menu). This method will set the
3219 * {@link OnCreateContextMenuListener} on the view to this activity, so
3220 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
3221 * called when it is time to show the context menu.
3223 * @see #unregisterForContextMenu(View)
3224 * @param view The view that should show a context menu.
3226 public void registerForContextMenu(View view) {
3227 view.setOnCreateContextMenuListener(this);
3231 * Prevents a context menu to be shown for the given view. This method will remove the
3232 * {@link OnCreateContextMenuListener} on the view.
3234 * @see #registerForContextMenu(View)
3235 * @param view The view that should stop showing a context menu.
3237 public void unregisterForContextMenu(View view) {
3238 view.setOnCreateContextMenuListener(null);
3242 * Programmatically opens the context menu for a particular {@code view}.
3243 * The {@code view} should have been added via
3244 * {@link #registerForContextMenu(View)}.
3246 * @param view The view to show the context menu for.
3248 public void openContextMenu(View view) {
3249 view.showContextMenu();
3253 * Programmatically closes the most recently opened context menu, if showing.
3255 public void closeContextMenu() {
3256 if (mWindow.hasFeature(Window.FEATURE_CONTEXT_MENU)) {
3257 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
3262 * This hook is called whenever an item in a context menu is selected. The
3263 * default implementation simply returns false to have the normal processing
3264 * happen (calling the item's Runnable or sending a message to its Handler
3265 * as appropriate). You can use this method for any items for which you
3266 * would like to do processing without those other facilities.
3268 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
3269 * View that added this menu item.
3271 * Derived classes should call through to the base class for it to perform
3272 * the default menu handling.
3274 * @param item The context menu item that was selected.
3275 * @return boolean Return false to allow normal context menu processing to
3276 * proceed, true to consume it here.
3278 public boolean onContextItemSelected(MenuItem item) {
3279 if (mParent != null) {
3280 return mParent.onContextItemSelected(item);
3286 * This hook is called whenever the context menu is being closed (either by
3287 * the user canceling the menu with the back/menu button, or when an item is
3290 * @param menu The context menu that is being closed.
3292 public void onContextMenuClosed(Menu menu) {
3293 if (mParent != null) {
3294 mParent.onContextMenuClosed(menu);
3299 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
3302 protected Dialog onCreateDialog(int id) {
3307 * Callback for creating dialogs that are managed (saved and restored) for you
3308 * by the activity. The default implementation calls through to
3309 * {@link #onCreateDialog(int)} for compatibility.
3311 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3312 * or later, consider instead using a {@link DialogFragment} instead.</em>
3314 * <p>If you use {@link #showDialog(int)}, the activity will call through to
3315 * this method the first time, and hang onto it thereafter. Any dialog
3316 * that is created by this method will automatically be saved and restored
3317 * for you, including whether it is showing.
3319 * <p>If you would like the activity to manage saving and restoring dialogs
3320 * for you, you should override this method and handle any ids that are
3321 * passed to {@link #showDialog}.
3323 * <p>If you would like an opportunity to prepare your dialog before it is shown,
3324 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
3326 * @param id The id of the dialog.
3327 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3328 * @return The dialog. If you return null, the dialog will not be created.
3330 * @see #onPrepareDialog(int, Dialog, Bundle)
3331 * @see #showDialog(int, Bundle)
3332 * @see #dismissDialog(int)
3333 * @see #removeDialog(int)
3335 * @deprecated Use the new {@link DialogFragment} class with
3336 * {@link FragmentManager} instead; this is also
3337 * available on older platforms through the Android compatibility package.
3341 protected Dialog onCreateDialog(int id, Bundle args) {
3342 return onCreateDialog(id);
3346 * @deprecated Old no-arguments version of
3347 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
3350 protected void onPrepareDialog(int id, Dialog dialog) {
3351 dialog.setOwnerActivity(this);
3355 * Provides an opportunity to prepare a managed dialog before it is being
3356 * shown. The default implementation calls through to
3357 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
3360 * Override this if you need to update a managed dialog based on the state
3361 * of the application each time it is shown. For example, a time picker
3362 * dialog might want to be updated with the current time. You should call
3363 * through to the superclass's implementation. The default implementation
3364 * will set this Activity as the owner activity on the Dialog.
3366 * @param id The id of the managed dialog.
3367 * @param dialog The dialog.
3368 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3369 * @see #onCreateDialog(int, Bundle)
3370 * @see #showDialog(int)
3371 * @see #dismissDialog(int)
3372 * @see #removeDialog(int)
3374 * @deprecated Use the new {@link DialogFragment} class with
3375 * {@link FragmentManager} instead; this is also
3376 * available on older platforms through the Android compatibility package.
3379 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
3380 onPrepareDialog(id, dialog);
3384 * Simple version of {@link #showDialog(int, Bundle)} that does not
3385 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
3386 * with null arguments.
3388 * @deprecated Use the new {@link DialogFragment} class with
3389 * {@link FragmentManager} instead; this is also
3390 * available on older platforms through the Android compatibility package.
3393 public final void showDialog(int id) {
3394 showDialog(id, null);
3398 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
3399 * will be made with the same id the first time this is called for a given
3400 * id. From thereafter, the dialog will be automatically saved and restored.
3402 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3403 * or later, consider instead using a {@link DialogFragment} instead.</em>
3405 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
3406 * be made to provide an opportunity to do any timely preparation.
3408 * @param id The id of the managed dialog.
3409 * @param args Arguments to pass through to the dialog. These will be saved
3410 * and restored for you. Note that if the dialog is already created,
3411 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
3412 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
3413 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
3414 * @return Returns true if the Dialog was created; false is returned if
3415 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
3418 * @see #onCreateDialog(int, Bundle)
3419 * @see #onPrepareDialog(int, Dialog, Bundle)
3420 * @see #dismissDialog(int)
3421 * @see #removeDialog(int)
3423 * @deprecated Use the new {@link DialogFragment} class with
3424 * {@link FragmentManager} instead; this is also
3425 * available on older platforms through the Android compatibility package.
3429 public final boolean showDialog(int id, Bundle args) {
3430 if (mManagedDialogs == null) {
3431 mManagedDialogs = new SparseArray<ManagedDialog>();
3433 ManagedDialog md = mManagedDialogs.get(id);
3435 md = new ManagedDialog();
3436 md.mDialog = createDialog(id, null, args);
3437 if (md.mDialog == null) {
3440 mManagedDialogs.put(id, md);
3444 onPrepareDialog(id, md.mDialog, args);
3450 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
3452 * @param id The id of the managed dialog.
3454 * @throws IllegalArgumentException if the id was not previously shown via
3455 * {@link #showDialog(int)}.
3457 * @see #onCreateDialog(int, Bundle)
3458 * @see #onPrepareDialog(int, Dialog, Bundle)
3459 * @see #showDialog(int)
3460 * @see #removeDialog(int)
3462 * @deprecated Use the new {@link DialogFragment} class with
3463 * {@link FragmentManager} instead; this is also
3464 * available on older platforms through the Android compatibility package.
3467 public final void dismissDialog(int id) {
3468 if (mManagedDialogs == null) {
3469 throw missingDialog(id);
3472 final ManagedDialog md = mManagedDialogs.get(id);
3474 throw missingDialog(id);
3476 md.mDialog.dismiss();
3480 * Creates an exception to throw if a user passed in a dialog id that is
3483 private IllegalArgumentException missingDialog(int id) {
3484 return new IllegalArgumentException("no dialog with id " + id + " was ever "
3485 + "shown via Activity#showDialog");
3489 * Removes any internal references to a dialog managed by this Activity.
3490 * If the dialog is showing, it will dismiss it as part of the clean up.
3492 * <p>This can be useful if you know that you will never show a dialog again and
3493 * want to avoid the overhead of saving and restoring it in the future.
3495 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
3496 * will not throw an exception if you try to remove an ID that does not
3497 * currently have an associated dialog.</p>
3499 * @param id The id of the managed dialog.
3501 * @see #onCreateDialog(int, Bundle)
3502 * @see #onPrepareDialog(int, Dialog, Bundle)
3503 * @see #showDialog(int)
3504 * @see #dismissDialog(int)
3506 * @deprecated Use the new {@link DialogFragment} class with
3507 * {@link FragmentManager} instead; this is also
3508 * available on older platforms through the Android compatibility package.
3511 public final void removeDialog(int id) {
3512 if (mManagedDialogs != null) {
3513 final ManagedDialog md = mManagedDialogs.get(id);
3515 md.mDialog.dismiss();
3516 mManagedDialogs.remove(id);
3522 * This hook is called when the user signals the desire to start a search.
3524 * <p>You can use this function as a simple way to launch the search UI, in response to a
3525 * menu item, search button, or other widgets within your activity. Unless overidden,
3526 * calling this function is the same as calling
3527 * {@link #startSearch startSearch(null, false, null, false)}, which launches
3528 * search for the current activity as specified in its manifest, see {@link SearchManager}.
3530 * <p>You can override this function to force global search, e.g. in response to a dedicated
3531 * search key, or to block search entirely (by simply returning false).
3533 * <p>Note: when running in a {@link Configuration#UI_MODE_TYPE_TELEVISION}, the default
3534 * implementation changes to simply return false and you must supply your own custom
3535 * implementation if you want to support search.</p>
3537 * @param searchEvent The {@link SearchEvent} that signaled this search.
3538 * @return Returns {@code true} if search launched, and {@code false} if the activity does
3539 * not respond to search. The default implementation always returns {@code true}, except
3540 * when in {@link Configuration#UI_MODE_TYPE_TELEVISION} mode where it returns false.
3542 * @see android.app.SearchManager
3544 public boolean onSearchRequested(@Nullable SearchEvent searchEvent) {
3545 mSearchEvent = searchEvent;
3546 boolean result = onSearchRequested();
3547 mSearchEvent = null;
3552 * @see #onSearchRequested(SearchEvent)
3554 public boolean onSearchRequested() {
3555 if ((getResources().getConfiguration().uiMode&Configuration.UI_MODE_TYPE_MASK)
3556 != Configuration.UI_MODE_TYPE_TELEVISION) {
3557 startSearch(null, false, null, false);
3565 * During the onSearchRequested() callbacks, this function will return the
3566 * {@link SearchEvent} that triggered the callback, if it exists.
3568 * @return SearchEvent The SearchEvent that triggered the {@link
3569 * #onSearchRequested} callback.
3571 public final SearchEvent getSearchEvent() {
3572 return mSearchEvent;
3576 * This hook is called to launch the search UI.
3578 * <p>It is typically called from onSearchRequested(), either directly from
3579 * Activity.onSearchRequested() or from an overridden version in any given
3580 * Activity. If your goal is simply to activate search, it is preferred to call
3581 * onSearchRequested(), which may have been overridden elsewhere in your Activity. If your goal
3582 * is to inject specific data such as context data, it is preferred to <i>override</i>
3583 * onSearchRequested(), so that any callers to it will benefit from the override.
3585 * @param initialQuery Any non-null non-empty string will be inserted as
3586 * pre-entered text in the search query box.
3587 * @param selectInitialQuery If true, the initial query will be preselected, which means that
3588 * any further typing will replace it. This is useful for cases where an entire pre-formed
3589 * query is being inserted. If false, the selection point will be placed at the end of the
3590 * inserted query. This is useful when the inserted query is text that the user entered,
3591 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
3592 * if initialQuery is a non-empty string.</i>
3593 * @param appSearchData An application can insert application-specific
3594 * context here, in order to improve quality or specificity of its own
3595 * searches. This data will be returned with SEARCH intent(s). Null if
3596 * no extra data is required.
3597 * @param globalSearch If false, this will only launch the search that has been specifically
3598 * defined by the application (which is usually defined as a local search). If no default
3599 * search is defined in the current application or activity, global search will be launched.
3600 * If true, this will always launch a platform-global (e.g. web-based) search instead.
3602 * @see android.app.SearchManager
3603 * @see #onSearchRequested
3605 public void startSearch(@Nullable String initialQuery, boolean selectInitialQuery,
3606 @Nullable Bundle appSearchData, boolean globalSearch) {
3607 ensureSearchManager();
3608 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
3609 appSearchData, globalSearch);
3613 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
3614 * the search dialog. Made available for testing purposes.
3616 * @param query The query to trigger. If empty, the request will be ignored.
3617 * @param appSearchData An application can insert application-specific
3618 * context here, in order to improve quality or specificity of its own
3619 * searches. This data will be returned with SEARCH intent(s). Null if
3620 * no extra data is required.
3622 public void triggerSearch(String query, @Nullable Bundle appSearchData) {
3623 ensureSearchManager();
3624 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
3628 * Request that key events come to this activity. Use this if your
3629 * activity has no views with focus, but the activity still wants
3630 * a chance to process key events.
3632 * @see android.view.Window#takeKeyEvents
3634 public void takeKeyEvents(boolean get) {
3635 getWindow().takeKeyEvents(get);
3639 * Enable extended window features. This is a convenience for calling
3640 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
3642 * @param featureId The desired feature as defined in
3643 * {@link android.view.Window}.
3644 * @return Returns true if the requested feature is supported and now
3647 * @see android.view.Window#requestFeature
3649 public final boolean requestWindowFeature(int featureId) {
3650 return getWindow().requestFeature(featureId);
3654 * Convenience for calling
3655 * {@link android.view.Window#setFeatureDrawableResource}.
3657 public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) {
3658 getWindow().setFeatureDrawableResource(featureId, resId);
3662 * Convenience for calling
3663 * {@link android.view.Window#setFeatureDrawableUri}.
3665 public final void setFeatureDrawableUri(int featureId, Uri uri) {
3666 getWindow().setFeatureDrawableUri(featureId, uri);
3670 * Convenience for calling
3671 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
3673 public final void setFeatureDrawable(int featureId, Drawable drawable) {
3674 getWindow().setFeatureDrawable(featureId, drawable);
3678 * Convenience for calling
3679 * {@link android.view.Window#setFeatureDrawableAlpha}.
3681 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
3682 getWindow().setFeatureDrawableAlpha(featureId, alpha);
3686 * Convenience for calling
3687 * {@link android.view.Window#getLayoutInflater}.
3690 public LayoutInflater getLayoutInflater() {
3691 return getWindow().getLayoutInflater();
3695 * Returns a {@link MenuInflater} with this context.
3698 public MenuInflater getMenuInflater() {
3699 // Make sure that action views can get an appropriate theme.
3700 if (mMenuInflater == null) {
3701 initWindowDecorActionBar();
3702 if (mActionBar != null) {
3703 mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this);
3705 mMenuInflater = new MenuInflater(this);
3708 return mMenuInflater;
3712 protected void onApplyThemeResource(Resources.Theme theme, @StyleRes int resid,
3714 if (mParent == null) {
3715 super.onApplyThemeResource(theme, resid, first);
3718 theme.setTo(mParent.getTheme());
3719 } catch (Exception e) {
3722 theme.applyStyle(resid, false);
3725 // Get the primary color and update the TaskDescription for this activity
3726 if (theme != null) {
3727 TypedArray a = theme.obtainStyledAttributes(com.android.internal.R.styleable.Theme);
3728 int colorPrimary = a.getColor(com.android.internal.R.styleable.Theme_colorPrimary, 0);
3730 if (colorPrimary != 0) {
3731 ActivityManager.TaskDescription v = new ActivityManager.TaskDescription(null, null,
3733 setTaskDescription(v);
3739 * Requests permissions to be granted to this application. These permissions
3740 * must be requested in your manifest, they should not be granted to your app,
3741 * and they should have protection level {@link android.content.pm.PermissionInfo
3742 * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by
3743 * the platform or a third-party app.
3745 * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
3746 * are granted at install time if requested in the manifest. Signature permissions
3747 * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
3748 * install time if requested in the manifest and the signature of your app matches
3749 * the signature of the app declaring the permissions.
3752 * If your app does not have the requested permissions the user will be presented
3753 * with UI for accepting them. After the user has accepted or rejected the
3754 * requested permissions you will receive a callback on {@link
3755 * #onRequestPermissionsResult(int, String[], int[])} reporting whether the
3756 * permissions were granted or not.
3759 * Note that requesting a permission does not guarantee it will be granted and
3760 * your app should be able to run without having this permission.
3763 * This method may start an activity allowing the user to choose which permissions
3764 * to grant and which to reject. Hence, you should be prepared that your activity
3765 * may be paused and resumed. Further, granting some permissions may require
3766 * a restart of you application. In such a case, the system will recreate the
3767 * activity stack before delivering the result to {@link
3768 * #onRequestPermissionsResult(int, String[], int[])}.
3771 * When checking whether you have a permission you should use {@link
3772 * #checkSelfPermission(String)}.
3775 * You cannot request a permission if your activity sets {@link
3776 * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
3777 * <code>true</code> because in this case the activity would not receive
3778 * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}.
3781 * A sample permissions request looks like this:
3784 * private void showContacts() {
3785 * if (checkSelfPermission(Manifest.permission.READ_CONTACTS)
3786 * != PackageManager.PERMISSION_GRANTED) {
3787 * requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
3788 * PERMISSIONS_REQUEST_READ_CONTACTS);
3794 * {@literal @}Override
3795 * public void onRequestPermissionsResult(int requestCode, String[] permissions,
3796 * int[] grantResults) {
3797 * if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS
3798 * && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
3804 * @param permissions The requested permissions.
3805 * @param requestCode Application specific request code to match with a result
3806 * reported to {@link #onRequestPermissionsResult(int, String[], int[])}.
3809 * @see #onRequestPermissionsResult(int, String[], int[])
3810 * @see #checkSelfPermission(String)
3811 * @see #shouldShowRequestPermissionRationale(String)
3813 public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
3814 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
3815 startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
3819 * Callback for the result from requesting permissions. This method
3820 * is invoked for every call on {@link #requestPermissions(String[], int)}.
3822 * <strong>Note:</strong> It is possible that the permissions request interaction
3823 * with the user is interrupted. In this case you will receive empty permissions
3824 * and results arrays which should be treated as a cancellation.
3827 * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
3828 * @param permissions The requested permissions. Never null.
3829 * @param grantResults The grant results for the corresponding permissions
3830 * which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
3831 * or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
3833 * @see #requestPermissions(String[], int)
3835 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
3836 @NonNull int[] grantResults) {
3837 /* callback - no nothing */
3841 * Gets whether you should show UI with rationale for requesting a permission.
3842 * You should do this only if you do not have the permission and the context in
3843 * which the permission is requested does not clearly communicate to the user
3844 * what would be the benefit from granting this permission.
3846 * For example, if you write a camera app, requesting the camera permission
3847 * would be expected by the user and no rationale for why it is requested is
3848 * needed. If however, the app needs location for tagging photos then a non-tech
3849 * savvy user may wonder how location is related to taking photos. In this case
3850 * you may choose to show UI with rationale of requesting this permission.
3853 * @param permission A permission your app wants to request.
3854 * @return Whether you can show permission rationale UI.
3856 * @see #checkSelfPermission(String)
3857 * @see #requestPermissions(String[], int)
3858 * @see #onRequestPermissionsResult(int, String[], int[])
3860 public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
3861 return getPackageManager().shouldShowRequestPermissionRationale(permission);
3865 * Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
3868 * @param intent The intent to start.
3869 * @param requestCode If >= 0, this code will be returned in
3870 * onActivityResult() when the activity exits.
3872 * @throws android.content.ActivityNotFoundException
3874 * @see #startActivity
3876 public void startActivityForResult(Intent intent, int requestCode) {
3877 startActivityForResult(intent, requestCode, null);
3881 * Launch an activity for which you would like a result when it finished.
3882 * When this activity exits, your
3883 * onActivityResult() method will be called with the given requestCode.
3884 * Using a negative requestCode is the same as calling
3885 * {@link #startActivity} (the activity is not launched as a sub-activity).
3887 * <p>Note that this method should only be used with Intent protocols
3888 * that are defined to return a result. In other protocols (such as
3889 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3890 * not get the result when you expect. For example, if the activity you
3891 * are launching uses the singleTask launch mode, it will not run in your
3892 * task and thus you will immediately receive a cancel result.
3894 * <p>As a special case, if you call startActivityForResult() with a requestCode
3895 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3896 * activity, then your window will not be displayed until a result is
3897 * returned back from the started activity. This is to avoid visible
3898 * flickering when redirecting to another activity.
3900 * <p>This method throws {@link android.content.ActivityNotFoundException}
3901 * if there was no Activity found to run the given Intent.
3903 * @param intent The intent to start.
3904 * @param requestCode If >= 0, this code will be returned in
3905 * onActivityResult() when the activity exits.
3906 * @param options Additional options for how the Activity should be started.
3907 * See {@link android.content.Context#startActivity(Intent, Bundle)
3908 * Context.startActivity(Intent, Bundle)} for more details.
3910 * @throws android.content.ActivityNotFoundException
3912 * @see #startActivity
3914 public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
3915 if (mParent == null) {
3916 Instrumentation.ActivityResult ar =
3917 mInstrumentation.execStartActivity(
3918 this, mMainThread.getApplicationThread(), mToken, this,
3919 intent, requestCode, options);
3921 mMainThread.sendActivityResult(
3922 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3923 ar.getResultData());
3925 if (requestCode >= 0) {
3926 // If this start is requesting a result, we can avoid making
3927 // the activity visible until the result is received. Setting
3928 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3929 // activity hidden during this time, to avoid flickering.
3930 // This can only be done when a result is requested because
3931 // that guarantees we will get information back when the
3932 // activity is finished, no matter what happens to it.
3933 mStartedActivity = true;
3936 cancelInputsAndStartExitTransition(options);
3937 // TODO Consider clearing/flushing other event sources and events for child windows.
3939 if (options != null) {
3940 mParent.startActivityFromChild(this, intent, requestCode, options);
3942 // Note we want to go through this method for compatibility with
3943 // existing applications that may have overridden it.
3944 mParent.startActivityFromChild(this, intent, requestCode);
3950 * Cancels pending inputs and if an Activity Transition is to be run, starts the transition.
3952 * @param options The ActivityOptions bundle used to start an Activity.
3954 private void cancelInputsAndStartExitTransition(Bundle options) {
3955 final View decor = mWindow != null ? mWindow.peekDecorView() : null;
3956 if (decor != null) {
3957 decor.cancelPendingInputEvents();
3959 if (options != null && !isTopOfTask()) {
3960 mActivityTransitionState.startExitOutTransition(this, options);
3965 * @hide Implement to provide correct calling token.
3967 public void startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user) {
3968 startActivityForResultAsUser(intent, requestCode, null, user);
3972 * @hide Implement to provide correct calling token.
3974 public void startActivityForResultAsUser(Intent intent, int requestCode,
3975 @Nullable Bundle options, UserHandle user) {
3976 if (mParent != null) {
3977 throw new RuntimeException("Can't be called from a child");
3979 Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
3980 this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode,
3983 mMainThread.sendActivityResult(
3984 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
3986 if (requestCode >= 0) {
3987 // If this start is requesting a result, we can avoid making
3988 // the activity visible until the result is received. Setting
3989 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3990 // activity hidden during this time, to avoid flickering.
3991 // This can only be done when a result is requested because
3992 // that guarantees we will get information back when the
3993 // activity is finished, no matter what happens to it.
3994 mStartedActivity = true;
3997 cancelInputsAndStartExitTransition(options);
4001 * @hide Implement to provide correct calling token.
4003 public void startActivityAsUser(Intent intent, UserHandle user) {
4004 startActivityAsUser(intent, null, user);
4008 * @hide Implement to provide correct calling token.
4010 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
4011 if (mParent != null) {
4012 throw new RuntimeException("Can't be called from a child");
4014 Instrumentation.ActivityResult ar =
4015 mInstrumentation.execStartActivity(
4016 this, mMainThread.getApplicationThread(), mToken, this,
4017 intent, -1, options, user);
4019 mMainThread.sendActivityResult(
4020 mToken, mEmbeddedID, -1, ar.getResultCode(),
4021 ar.getResultData());
4023 cancelInputsAndStartExitTransition(options);
4027 * Start a new activity as if it was started by the activity that started our
4028 * current activity. This is for the resolver and chooser activities, which operate
4029 * as intermediaries that dispatch their intent to the target the user selects -- to
4030 * do this, they must perform all security checks including permission grants as if
4031 * their launch had come from the original activity.
4032 * @param intent The Intent to start.
4033 * @param options ActivityOptions or null.
4034 * @param ignoreTargetSecurity If true, the activity manager will not check whether the
4035 * caller it is doing the start is, is actually allowed to start the target activity.
4036 * If you set this to true, you must set an explicit component in the Intent and do any
4037 * appropriate security checks yourself.
4038 * @param userId The user the new activity should run as.
4041 public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
4042 boolean ignoreTargetSecurity, int userId) {
4043 if (mParent != null) {
4044 throw new RuntimeException("Can't be called from a child");
4046 Instrumentation.ActivityResult ar =
4047 mInstrumentation.execStartActivityAsCaller(
4048 this, mMainThread.getApplicationThread(), mToken, this,
4049 intent, -1, options, ignoreTargetSecurity, userId);
4051 mMainThread.sendActivityResult(
4052 mToken, mEmbeddedID, -1, ar.getResultCode(),
4053 ar.getResultData());
4055 cancelInputsAndStartExitTransition(options);
4059 * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
4060 * Intent, int, int, int, Bundle)} with no options.
4062 * @param intent The IntentSender to launch.
4063 * @param requestCode If >= 0, this code will be returned in
4064 * onActivityResult() when the activity exits.
4065 * @param fillInIntent If non-null, this will be provided as the
4066 * intent parameter to {@link IntentSender#sendIntent}.
4067 * @param flagsMask Intent flags in the original IntentSender that you
4068 * would like to change.
4069 * @param flagsValues Desired values for any bits set in
4070 * <var>flagsMask</var>
4071 * @param extraFlags Always set to 0.
4073 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4074 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4075 throws IntentSender.SendIntentException {
4076 startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
4077 flagsValues, extraFlags, null);
4081 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
4082 * to use a IntentSender to describe the activity to be started. If
4083 * the IntentSender is for an activity, that activity will be started
4084 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
4085 * here; otherwise, its associated action will be executed (such as
4086 * sending a broadcast) as if you had called
4087 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
4089 * @param intent The IntentSender to launch.
4090 * @param requestCode If >= 0, this code will be returned in
4091 * onActivityResult() when the activity exits.
4092 * @param fillInIntent If non-null, this will be provided as the
4093 * intent parameter to {@link IntentSender#sendIntent}.
4094 * @param flagsMask Intent flags in the original IntentSender that you
4095 * would like to change.
4096 * @param flagsValues Desired values for any bits set in
4097 * <var>flagsMask</var>
4098 * @param extraFlags Always set to 0.
4099 * @param options Additional options for how the Activity should be started.
4100 * See {@link android.content.Context#startActivity(Intent, Bundle)
4101 * Context.startActivity(Intent, Bundle)} for more details. If options
4102 * have also been supplied by the IntentSender, options given here will
4103 * override any that conflict with those given by the IntentSender.
4105 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4106 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4107 Bundle options) throws IntentSender.SendIntentException {
4108 if (mParent == null) {
4109 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
4110 flagsMask, flagsValues, this, options);
4111 } else if (options != null) {
4112 mParent.startIntentSenderFromChild(this, intent, requestCode,
4113 fillInIntent, flagsMask, flagsValues, extraFlags, options);
4115 // Note we want to go through this call for compatibility with
4116 // existing applications that may have overridden the method.
4117 mParent.startIntentSenderFromChild(this, intent, requestCode,
4118 fillInIntent, flagsMask, flagsValues, extraFlags);
4122 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
4123 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity,
4125 throws IntentSender.SendIntentException {
4127 String resolvedType = null;
4128 if (fillInIntent != null) {
4129 fillInIntent.migrateExtraStreamToClipData();
4130 fillInIntent.prepareToLeaveProcess();
4131 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
4133 int result = ActivityManagerNative.getDefault()
4134 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
4135 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
4136 requestCode, flagsMask, flagsValues, options);
4137 if (result == ActivityManager.START_CANCELED) {
4138 throw new IntentSender.SendIntentException();
4140 Instrumentation.checkStartActivityResult(result, null);
4141 } catch (RemoteException e) {
4143 if (requestCode >= 0) {
4144 // If this start is requesting a result, we can avoid making
4145 // the activity visible until the result is received. Setting
4146 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4147 // activity hidden during this time, to avoid flickering.
4148 // This can only be done when a result is requested because
4149 // that guarantees we will get information back when the
4150 // activity is finished, no matter what happens to it.
4151 mStartedActivity = true;
4156 * Same as {@link #startActivity(Intent, Bundle)} with no options
4159 * @param intent The intent to start.
4161 * @throws android.content.ActivityNotFoundException
4163 * @see {@link #startActivity(Intent, Bundle)}
4164 * @see #startActivityForResult
4167 public void startActivity(Intent intent) {
4168 this.startActivity(intent, null);
4172 * Launch a new activity. You will not receive any information about when
4173 * the activity exits. This implementation overrides the base version,
4174 * providing information about
4175 * the activity performing the launch. Because of this additional
4176 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4177 * required; if not specified, the new activity will be added to the
4178 * task of the caller.
4180 * <p>This method throws {@link android.content.ActivityNotFoundException}
4181 * if there was no Activity found to run the given Intent.
4183 * @param intent The intent to start.
4184 * @param options Additional options for how the Activity should be started.
4185 * See {@link android.content.Context#startActivity(Intent, Bundle)
4186 * Context.startActivity(Intent, Bundle)} for more details.
4188 * @throws android.content.ActivityNotFoundException
4190 * @see {@link #startActivity(Intent)}
4191 * @see #startActivityForResult
4194 public void startActivity(Intent intent, @Nullable Bundle options) {
4195 if (options != null) {
4196 startActivityForResult(intent, -1, options);
4198 // Note we want to go through this call for compatibility with
4199 // applications that may have overridden the method.
4200 startActivityForResult(intent, -1);
4205 * Same as {@link #startActivities(Intent[], Bundle)} with no options
4208 * @param intents The intents to start.
4210 * @throws android.content.ActivityNotFoundException
4212 * @see {@link #startActivities(Intent[], Bundle)}
4213 * @see #startActivityForResult
4216 public void startActivities(Intent[] intents) {
4217 startActivities(intents, null);
4221 * Launch a new activity. You will not receive any information about when
4222 * the activity exits. This implementation overrides the base version,
4223 * providing information about
4224 * the activity performing the launch. Because of this additional
4225 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4226 * required; if not specified, the new activity will be added to the
4227 * task of the caller.
4229 * <p>This method throws {@link android.content.ActivityNotFoundException}
4230 * if there was no Activity found to run the given Intent.
4232 * @param intents The intents to start.
4233 * @param options Additional options for how the Activity should be started.
4234 * See {@link android.content.Context#startActivity(Intent, Bundle)
4235 * Context.startActivity(Intent, Bundle)} for more details.
4237 * @throws android.content.ActivityNotFoundException
4239 * @see {@link #startActivities(Intent[])}
4240 * @see #startActivityForResult
4243 public void startActivities(Intent[] intents, @Nullable Bundle options) {
4244 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
4245 mToken, this, intents, options);
4249 * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
4252 * @param intent The IntentSender to launch.
4253 * @param fillInIntent If non-null, this will be provided as the
4254 * intent parameter to {@link IntentSender#sendIntent}.
4255 * @param flagsMask Intent flags in the original IntentSender that you
4256 * would like to change.
4257 * @param flagsValues Desired values for any bits set in
4258 * <var>flagsMask</var>
4259 * @param extraFlags Always set to 0.
4261 public void startIntentSender(IntentSender intent,
4262 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4263 throws IntentSender.SendIntentException {
4264 startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
4269 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
4271 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
4272 * for more information.
4274 * @param intent The IntentSender to launch.
4275 * @param fillInIntent If non-null, this will be provided as the
4276 * intent parameter to {@link IntentSender#sendIntent}.
4277 * @param flagsMask Intent flags in the original IntentSender that you
4278 * would like to change.
4279 * @param flagsValues Desired values for any bits set in
4280 * <var>flagsMask</var>
4281 * @param extraFlags Always set to 0.
4282 * @param options Additional options for how the Activity should be started.
4283 * See {@link android.content.Context#startActivity(Intent, Bundle)
4284 * Context.startActivity(Intent, Bundle)} for more details. If options
4285 * have also been supplied by the IntentSender, options given here will
4286 * override any that conflict with those given by the IntentSender.
4288 public void startIntentSender(IntentSender intent,
4289 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4290 Bundle options) throws IntentSender.SendIntentException {
4291 if (options != null) {
4292 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4293 flagsValues, extraFlags, options);
4295 // Note we want to go through this call for compatibility with
4296 // applications that may have overridden the method.
4297 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4298 flagsValues, extraFlags);
4303 * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
4306 * @param intent The intent to start.
4307 * @param requestCode If >= 0, this code will be returned in
4308 * onActivityResult() when the activity exits, as described in
4309 * {@link #startActivityForResult}.
4311 * @return If a new activity was launched then true is returned; otherwise
4312 * false is returned and you must handle the Intent yourself.
4314 * @see #startActivity
4315 * @see #startActivityForResult
4317 public boolean startActivityIfNeeded(@NonNull Intent intent, int requestCode) {
4318 return startActivityIfNeeded(intent, requestCode, null);
4322 * A special variation to launch an activity only if a new activity
4323 * instance is needed to handle the given Intent. In other words, this is
4324 * just like {@link #startActivityForResult(Intent, int)} except: if you are
4325 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
4326 * singleTask or singleTop
4327 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
4329 * that handles <var>intent</var> is the same as your currently running
4330 * activity, then a new instance is not needed. In this case, instead of
4331 * the normal behavior of calling {@link #onNewIntent} this function will
4332 * return and you can handle the Intent yourself.
4334 * <p>This function can only be called from a top-level activity; if it is
4335 * called from a child activity, a runtime exception will be thrown.
4337 * @param intent The intent to start.
4338 * @param requestCode If >= 0, this code will be returned in
4339 * onActivityResult() when the activity exits, as described in
4340 * {@link #startActivityForResult}.
4341 * @param options Additional options for how the Activity should be started.
4342 * See {@link android.content.Context#startActivity(Intent, Bundle)
4343 * Context.startActivity(Intent, Bundle)} for more details.
4345 * @return If a new activity was launched then true is returned; otherwise
4346 * false is returned and you must handle the Intent yourself.
4348 * @see #startActivity
4349 * @see #startActivityForResult
4351 public boolean startActivityIfNeeded(@NonNull Intent intent, int requestCode,
4352 @Nullable Bundle options) {
4353 if (mParent == null) {
4354 int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
4356 Uri referrer = onProvideReferrer();
4357 if (referrer != null) {
4358 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4360 intent.migrateExtraStreamToClipData();
4361 intent.prepareToLeaveProcess();
4362 result = ActivityManagerNative.getDefault()
4363 .startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
4364 intent, intent.resolveTypeIfNeeded(getContentResolver()), mToken,
4365 mEmbeddedID, requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4367 } catch (RemoteException e) {
4371 Instrumentation.checkStartActivityResult(result, intent);
4373 if (requestCode >= 0) {
4374 // If this start is requesting a result, we can avoid making
4375 // the activity visible until the result is received. Setting
4376 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4377 // activity hidden during this time, to avoid flickering.
4378 // This can only be done when a result is requested because
4379 // that guarantees we will get information back when the
4380 // activity is finished, no matter what happens to it.
4381 mStartedActivity = true;
4383 return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
4386 throw new UnsupportedOperationException(
4387 "startActivityIfNeeded can only be called from a top-level activity");
4391 * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
4394 * @param intent The intent to dispatch to the next activity. For
4395 * correct behavior, this must be the same as the Intent that started
4396 * your own activity; the only changes you can make are to the extras
4399 * @return Returns a boolean indicating whether there was another Activity
4400 * to start: true if there was a next activity to start, false if there
4401 * wasn't. In general, if true is returned you will then want to call
4402 * finish() on yourself.
4404 public boolean startNextMatchingActivity(@NonNull Intent intent) {
4405 return startNextMatchingActivity(intent, null);
4409 * Special version of starting an activity, for use when you are replacing
4410 * other activity components. You can use this to hand the Intent off
4411 * to the next Activity that can handle it. You typically call this in
4412 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
4414 * @param intent The intent to dispatch to the next activity. For
4415 * correct behavior, this must be the same as the Intent that started
4416 * your own activity; the only changes you can make are to the extras
4418 * @param options Additional options for how the Activity should be started.
4419 * See {@link android.content.Context#startActivity(Intent, Bundle)
4420 * Context.startActivity(Intent, Bundle)} for more details.
4422 * @return Returns a boolean indicating whether there was another Activity
4423 * to start: true if there was a next activity to start, false if there
4424 * wasn't. In general, if true is returned you will then want to call
4425 * finish() on yourself.
4427 public boolean startNextMatchingActivity(@NonNull Intent intent, @Nullable Bundle options) {
4428 if (mParent == null) {
4430 intent.migrateExtraStreamToClipData();
4431 intent.prepareToLeaveProcess();
4432 return ActivityManagerNative.getDefault()
4433 .startNextMatchingActivity(mToken, intent, options);
4434 } catch (RemoteException e) {
4440 throw new UnsupportedOperationException(
4441 "startNextMatchingActivity can only be called from a top-level activity");
4445 * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
4448 * @param child The activity making the call.
4449 * @param intent The intent to start.
4450 * @param requestCode Reply request code. < 0 if reply is not requested.
4452 * @throws android.content.ActivityNotFoundException
4454 * @see #startActivity
4455 * @see #startActivityForResult
4457 public void startActivityFromChild(@NonNull Activity child, Intent intent,
4459 startActivityFromChild(child, intent, requestCode, null);
4463 * This is called when a child activity of this one calls its
4464 * {@link #startActivity} or {@link #startActivityForResult} method.
4466 * <p>This method throws {@link android.content.ActivityNotFoundException}
4467 * if there was no Activity found to run the given Intent.
4469 * @param child The activity making the call.
4470 * @param intent The intent to start.
4471 * @param requestCode Reply request code. < 0 if reply is not requested.
4472 * @param options Additional options for how the Activity should be started.
4473 * See {@link android.content.Context#startActivity(Intent, Bundle)
4474 * Context.startActivity(Intent, Bundle)} for more details.
4476 * @throws android.content.ActivityNotFoundException
4478 * @see #startActivity
4479 * @see #startActivityForResult
4481 public void startActivityFromChild(@NonNull Activity child, Intent intent,
4482 int requestCode, @Nullable Bundle options) {
4483 Instrumentation.ActivityResult ar =
4484 mInstrumentation.execStartActivity(
4485 this, mMainThread.getApplicationThread(), mToken, child,
4486 intent, requestCode, options);
4488 mMainThread.sendActivityResult(
4489 mToken, child.mEmbeddedID, requestCode,
4490 ar.getResultCode(), ar.getResultData());
4492 cancelInputsAndStartExitTransition(options);
4496 * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
4499 * @param fragment The fragment making the call.
4500 * @param intent The intent to start.
4501 * @param requestCode Reply request code. < 0 if reply is not requested.
4503 * @throws android.content.ActivityNotFoundException
4505 * @see Fragment#startActivity
4506 * @see Fragment#startActivityForResult
4508 public void startActivityFromFragment(@NonNull Fragment fragment, Intent intent,
4510 startActivityFromFragment(fragment, intent, requestCode, null);
4514 * This is called when a Fragment in this activity calls its
4515 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
4518 * <p>This method throws {@link android.content.ActivityNotFoundException}
4519 * if there was no Activity found to run the given Intent.
4521 * @param fragment The fragment making the call.
4522 * @param intent The intent to start.
4523 * @param requestCode Reply request code. < 0 if reply is not requested.
4524 * @param options Additional options for how the Activity should be started.
4525 * See {@link android.content.Context#startActivity(Intent, Bundle)
4526 * Context.startActivity(Intent, Bundle)} for more details.
4528 * @throws android.content.ActivityNotFoundException
4530 * @see Fragment#startActivity
4531 * @see Fragment#startActivityForResult
4533 public void startActivityFromFragment(@NonNull Fragment fragment, Intent intent,
4534 int requestCode, @Nullable Bundle options) {
4535 startActivityForResult(fragment.mWho, intent, requestCode, options);
4542 public void startActivityForResult(
4543 String who, Intent intent, int requestCode, @Nullable Bundle options) {
4544 Uri referrer = onProvideReferrer();
4545 if (referrer != null) {
4546 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4548 Instrumentation.ActivityResult ar =
4549 mInstrumentation.execStartActivity(
4550 this, mMainThread.getApplicationThread(), mToken, who,
4551 intent, requestCode, options);
4553 mMainThread.sendActivityResult(
4554 mToken, who, requestCode,
4555 ar.getResultCode(), ar.getResultData());
4557 cancelInputsAndStartExitTransition(options);
4564 public boolean canStartActivityForResult() {
4569 * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
4570 * int, Intent, int, int, int, Bundle)} with no options.
4572 public void startIntentSenderFromChild(Activity child, IntentSender intent,
4573 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
4575 throws IntentSender.SendIntentException {
4576 startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
4577 flagsMask, flagsValues, extraFlags, null);
4581 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
4582 * taking a IntentSender; see
4583 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
4584 * for more information.
4586 public void startIntentSenderFromChild(Activity child, IntentSender intent,
4587 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
4588 int extraFlags, @Nullable Bundle options)
4589 throws IntentSender.SendIntentException {
4590 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
4591 flagsMask, flagsValues, child, options);
4595 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
4596 * or {@link #finish} to specify an explicit transition animation to
4599 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
4600 * to using this with starting activities is to supply the desired animation
4601 * information through a {@link ActivityOptions} bundle to
4602 * {@link #startActivity(Intent, Bundle) or a related function. This allows
4603 * you to specify a custom animation even when starting an activity from
4604 * outside the context of the current top activity.
4606 * @param enterAnim A resource ID of the animation resource to use for
4607 * the incoming activity. Use 0 for no animation.
4608 * @param exitAnim A resource ID of the animation resource to use for
4609 * the outgoing activity. Use 0 for no animation.
4611 public void overridePendingTransition(int enterAnim, int exitAnim) {
4613 ActivityManagerNative.getDefault().overridePendingTransition(
4614 mToken, getPackageName(), enterAnim, exitAnim);
4615 } catch (RemoteException e) {
4620 * Call this to set the result that your activity will return to its
4623 * @param resultCode The result code to propagate back to the originating
4624 * activity, often RESULT_CANCELED or RESULT_OK
4626 * @see #RESULT_CANCELED
4628 * @see #RESULT_FIRST_USER
4629 * @see #setResult(int, Intent)
4631 public final void setResult(int resultCode) {
4632 synchronized (this) {
4633 mResultCode = resultCode;
4639 * Call this to set the result that your activity will return to its
4642 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
4643 * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
4644 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4645 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the
4646 * Activity receiving the result access to the specific URIs in the Intent.
4647 * Access will remain until the Activity has finished (it will remain across the hosting
4648 * process being killed and other temporary destruction) and will be added
4649 * to any existing set of URI permissions it already holds.
4651 * @param resultCode The result code to propagate back to the originating
4652 * activity, often RESULT_CANCELED or RESULT_OK
4653 * @param data The data to propagate back to the originating activity.
4655 * @see #RESULT_CANCELED
4657 * @see #RESULT_FIRST_USER
4658 * @see #setResult(int)
4660 public final void setResult(int resultCode, Intent data) {
4661 synchronized (this) {
4662 mResultCode = resultCode;
4668 * Return information about who launched this activity. If the launching Intent
4669 * contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
4670 * that will be returned as-is; otherwise, if known, an
4671 * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
4672 * package name that started the Intent will be returned. This may return null if no
4673 * referrer can be identified -- it is neither explicitly specified, nor is it known which
4674 * application package was involved.
4676 * <p>If called while inside the handling of {@link #onNewIntent}, this function will
4677 * return the referrer that submitted that new intent to the activity. Otherwise, it
4678 * always returns the referrer of the original Intent.</p>
4680 * <p>Note that this is <em>not</em> a security feature -- you can not trust the
4681 * referrer information, applications can spoof it.</p>
4684 public Uri getReferrer() {
4685 Intent intent = getIntent();
4686 Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
4687 if (referrer != null) {
4690 String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
4691 if (referrerName != null) {
4692 return Uri.parse(referrerName);
4694 if (mReferrer != null) {
4695 return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
4701 * Override to generate the desired referrer for the content currently being shown
4702 * by the app. The default implementation returns null, meaning the referrer will simply
4703 * be the android-app: of the package name of this activity. Return a non-null Uri to
4704 * have that supplied as the {@link Intent#EXTRA_REFERRER} of any activities started from it.
4706 public Uri onProvideReferrer() {
4711 * Return the name of the package that invoked this activity. This is who
4712 * the data in {@link #setResult setResult()} will be sent to. You can
4713 * use this information to validate that the recipient is allowed to
4716 * <p class="note">Note: if the calling activity is not expecting a result (that is it
4717 * did not use the {@link #startActivityForResult}
4718 * form that includes a request code), then the calling package will be
4721 * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
4722 * the result from this method was unstable. If the process hosting the calling
4723 * package was no longer running, it would return null instead of the proper package
4724 * name. You can use {@link #getCallingActivity()} and retrieve the package name
4725 * from that instead.</p>
4727 * @return The package of the activity that will receive your
4728 * reply, or null if none.
4731 public String getCallingPackage() {
4733 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
4734 } catch (RemoteException e) {
4740 * Return the name of the activity that invoked this activity. This is
4741 * who the data in {@link #setResult setResult()} will be sent to. You
4742 * can use this information to validate that the recipient is allowed to
4745 * <p class="note">Note: if the calling activity is not expecting a result (that is it
4746 * did not use the {@link #startActivityForResult}
4747 * form that includes a request code), then the calling package will be
4750 * @return The ComponentName of the activity that will receive your
4751 * reply, or null if none.
4754 public ComponentName getCallingActivity() {
4756 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
4757 } catch (RemoteException e) {
4763 * Control whether this activity's main window is visible. This is intended
4764 * only for the special case of an activity that is not going to show a
4765 * UI itself, but can't just finish prior to onResume() because it needs
4766 * to wait for a service binding or such. Setting this to false allows
4767 * you to prevent your UI from being shown during that time.
4769 * <p>The default value for this is taken from the
4770 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
4772 public void setVisible(boolean visible) {
4773 if (mVisibleFromClient != visible) {
4774 mVisibleFromClient = visible;
4775 if (mVisibleFromServer) {
4776 if (visible) makeVisible();
4777 else mDecor.setVisibility(View.INVISIBLE);
4782 void makeVisible() {
4783 if (!mWindowAdded) {
4784 ViewManager wm = getWindowManager();
4785 wm.addView(mDecor, getWindow().getAttributes());
4786 mWindowAdded = true;
4788 mDecor.setVisibility(View.VISIBLE);
4792 * Check to see whether this activity is in the process of finishing,
4793 * either because you called {@link #finish} on it or someone else
4794 * has requested that it finished. This is often used in
4795 * {@link #onPause} to determine whether the activity is simply pausing or
4796 * completely finishing.
4798 * @return If the activity is finishing, returns true; else returns false.
4802 public boolean isFinishing() {
4807 * Returns true if the final {@link #onDestroy()} call has been made
4808 * on the Activity, so this instance is now dead.
4810 public boolean isDestroyed() {
4815 * Check to see whether this activity is in the process of being destroyed in order to be
4816 * recreated with a new configuration. This is often used in
4817 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
4818 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
4820 * @return If the activity is being torn down in order to be recreated with a new configuration,
4821 * returns true; else returns false.
4823 public boolean isChangingConfigurations() {
4824 return mChangingConfigurations;
4828 * Cause this Activity to be recreated with a new instance. This results
4829 * in essentially the same flow as when the Activity is created due to
4830 * a configuration change -- the current instance will go through its
4831 * lifecycle to {@link #onDestroy} and a new instance then created after it.
4833 public void recreate() {
4834 if (mParent != null) {
4835 throw new IllegalStateException("Can only be called on top-level activity");
4837 if (Looper.myLooper() != mMainThread.getLooper()) {
4838 throw new IllegalStateException("Must be called from main thread");
4840 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, null, false);
4844 * Finishes the current activity and specifies whether to remove the task associated with this
4847 private void finish(boolean finishTask) {
4848 if (mParent == null) {
4851 synchronized (this) {
4852 resultCode = mResultCode;
4853 resultData = mResultData;
4855 if (false) Log.v(TAG, "Finishing self: token=" + mToken);
4857 if (resultData != null) {
4858 resultData.prepareToLeaveProcess();
4860 if (ActivityManagerNative.getDefault()
4861 .finishActivity(mToken, resultCode, resultData, finishTask)) {
4864 } catch (RemoteException e) {
4868 mParent.finishFromChild(this);
4873 * Call this when your activity is done and should be closed. The
4874 * ActivityResult is propagated back to whoever launched you via
4875 * onActivityResult().
4877 public void finish() {
4882 * Finish this activity as well as all activities immediately below it
4883 * in the current task that have the same affinity. This is typically
4884 * used when an application can be launched on to another task (such as
4885 * from an ACTION_VIEW of a content type it understands) and the user
4886 * has used the up navigation to switch out of the current task and in
4887 * to its own task. In this case, if the user has navigated down into
4888 * any other activities of the second application, all of those should
4889 * be removed from the original task as part of the task switch.
4891 * <p>Note that this finish does <em>not</em> allow you to deliver results
4892 * to the previous activity, and an exception will be thrown if you are trying
4895 public void finishAffinity() {
4896 if (mParent != null) {
4897 throw new IllegalStateException("Can not be called from an embedded activity");
4899 if (mResultCode != RESULT_CANCELED || mResultData != null) {
4900 throw new IllegalStateException("Can not be called to deliver a result");
4903 if (ActivityManagerNative.getDefault().finishActivityAffinity(mToken)) {
4906 } catch (RemoteException e) {
4912 * This is called when a child activity of this one calls its
4913 * {@link #finish} method. The default implementation simply calls
4914 * finish() on this activity (the parent), finishing the entire group.
4916 * @param child The activity making the call.
4920 public void finishFromChild(Activity child) {
4925 * Reverses the Activity Scene entry Transition and triggers the calling Activity
4926 * to reverse its exit Transition. When the exit Transition completes,
4927 * {@link #finish()} is called. If no entry Transition was used, finish() is called
4928 * immediately and the Activity exit Transition is run.
4929 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, android.util.Pair[])
4931 public void finishAfterTransition() {
4932 if (!mActivityTransitionState.startExitBackTransition(this)) {
4938 * Force finish another activity that you had previously started with
4939 * {@link #startActivityForResult}.
4941 * @param requestCode The request code of the activity that you had
4942 * given to startActivityForResult(). If there are multiple
4943 * activities started with this request code, they
4944 * will all be finished.
4946 public void finishActivity(int requestCode) {
4947 if (mParent == null) {
4949 ActivityManagerNative.getDefault()
4950 .finishSubActivity(mToken, mEmbeddedID, requestCode);
4951 } catch (RemoteException e) {
4955 mParent.finishActivityFromChild(this, requestCode);
4960 * This is called when a child activity of this one calls its
4963 * @param child The activity making the call.
4964 * @param requestCode Request code that had been used to start the
4967 public void finishActivityFromChild(@NonNull Activity child, int requestCode) {
4969 ActivityManagerNative.getDefault()
4970 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
4971 } catch (RemoteException e) {
4977 * Call this when your activity is done and should be closed and the task should be completely
4978 * removed as a part of finishing the Activity.
4980 public void finishAndRemoveTask() {
4985 * Ask that the local app instance of this activity be released to free up its memory.
4986 * This is asking for the activity to be destroyed, but does <b>not</b> finish the activity --
4987 * a new instance of the activity will later be re-created if needed due to the user
4988 * navigating back to it.
4990 * @return Returns true if the activity was in a state that it has started the process
4991 * of destroying its current instance; returns false if for any reason this could not
4992 * be done: it is currently visible to the user, it is already being destroyed, it is
4993 * being finished, it hasn't yet saved its state, etc.
4995 public boolean releaseInstance() {
4997 return ActivityManagerNative.getDefault().releaseActivityInstance(mToken);
4998 } catch (RemoteException e) {
5005 * Called when an activity you launched exits, giving you the requestCode
5006 * you started it with, the resultCode it returned, and any additional
5007 * data from it. The <var>resultCode</var> will be
5008 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
5009 * didn't return any result, or crashed during its operation.
5011 * <p>You will receive this call immediately before onResume() when your
5012 * activity is re-starting.
5014 * <p>This method is never invoked if your activity sets
5015 * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
5016 * <code>true</code>.
5018 * @param requestCode The integer request code originally supplied to
5019 * startActivityForResult(), allowing you to identify who this
5021 * @param resultCode The integer result code returned by the child activity
5022 * through its setResult().
5023 * @param data An Intent, which can return result data to the caller
5024 * (various data can be attached to Intent "extras").
5026 * @see #startActivityForResult
5027 * @see #createPendingResult
5028 * @see #setResult(int)
5030 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
5034 * Called when an activity you launched with an activity transition exposes this
5035 * Activity through a returning activity transition, giving you the resultCode
5036 * and any additional data from it. This method will only be called if the activity
5037 * set a result code other than {@link #RESULT_CANCELED} and it supports activity
5038 * transitions with {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
5040 * <p>The purpose of this function is to let the called Activity send a hint about
5041 * its state so that this underlying Activity can prepare to be exposed. A call to
5042 * this method does not guarantee that the called Activity has or will be exiting soon.
5043 * It only indicates that it will expose this Activity's Window and it has
5044 * some data to pass to prepare it.</p>
5046 * @param resultCode The integer result code returned by the child activity
5047 * through its setResult().
5048 * @param data An Intent, which can return result data to the caller
5049 * (various data can be attached to Intent "extras").
5051 public void onActivityReenter(int resultCode, Intent data) {
5055 * Create a new PendingIntent object which you can hand to others
5056 * for them to use to send result data back to your
5057 * {@link #onActivityResult} callback. The created object will be either
5058 * one-shot (becoming invalid after a result is sent back) or multiple
5059 * (allowing any number of results to be sent through it).
5061 * @param requestCode Private request code for the sender that will be
5062 * associated with the result data when it is returned. The sender can not
5063 * modify this value, allowing you to identify incoming results.
5064 * @param data Default data to supply in the result, which may be modified
5066 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
5067 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
5068 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
5069 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
5070 * or any of the flags as supported by
5071 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
5072 * of the intent that can be supplied when the actual send happens.
5074 * @return Returns an existing or new PendingIntent matching the given
5075 * parameters. May return null only if
5076 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
5079 * @see PendingIntent
5081 public PendingIntent createPendingResult(int requestCode, @NonNull Intent data,
5082 @PendingIntent.Flags int flags) {
5083 String packageName = getPackageName();
5085 data.prepareToLeaveProcess();
5086 IIntentSender target =
5087 ActivityManagerNative.getDefault().getIntentSender(
5088 ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
5089 mParent == null ? mToken : mParent.mToken,
5090 mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null,
5091 UserHandle.myUserId());
5092 return target != null ? new PendingIntent(target) : null;
5093 } catch (RemoteException e) {
5100 * Change the desired orientation of this activity. If the activity
5101 * is currently in the foreground or otherwise impacting the screen
5102 * orientation, the screen will immediately be changed (possibly causing
5103 * the activity to be restarted). Otherwise, this will be used the next
5104 * time the activity is visible.
5106 * @param requestedOrientation An orientation constant as used in
5107 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5109 public void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) {
5110 if (mParent == null) {
5112 ActivityManagerNative.getDefault().setRequestedOrientation(
5113 mToken, requestedOrientation);
5114 } catch (RemoteException e) {
5118 mParent.setRequestedOrientation(requestedOrientation);
5123 * Return the current requested orientation of the activity. This will
5124 * either be the orientation requested in its component's manifest, or
5125 * the last requested orientation given to
5126 * {@link #setRequestedOrientation(int)}.
5128 * @return Returns an orientation constant as used in
5129 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5131 @ActivityInfo.ScreenOrientation
5132 public int getRequestedOrientation() {
5133 if (mParent == null) {
5135 return ActivityManagerNative.getDefault()
5136 .getRequestedOrientation(mToken);
5137 } catch (RemoteException e) {
5141 return mParent.getRequestedOrientation();
5143 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
5147 * Return the identifier of the task this activity is in. This identifier
5148 * will remain the same for the lifetime of the activity.
5150 * @return Task identifier, an opaque integer.
5152 public int getTaskId() {
5154 return ActivityManagerNative.getDefault()
5155 .getTaskForActivity(mToken, false);
5156 } catch (RemoteException e) {
5162 * Return whether this activity is the root of a task. The root is the
5163 * first activity in a task.
5165 * @return True if this is the root activity, else false.
5167 public boolean isTaskRoot() {
5169 return ActivityManagerNative.getDefault()
5170 .getTaskForActivity(mToken, true) >= 0;
5171 } catch (RemoteException e) {
5177 * Move the task containing this activity to the back of the activity
5178 * stack. The activity's order within the task is unchanged.
5180 * @param nonRoot If false then this only works if the activity is the root
5181 * of a task; if true it will work for any activity in
5184 * @return If the task was moved (or it was already at the
5185 * back) true is returned, else false.
5187 public boolean moveTaskToBack(boolean nonRoot) {
5189 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
5191 } catch (RemoteException e) {
5198 * Returns class name for this activity with the package prefix removed.
5199 * This is the default name used to read and write settings.
5201 * @return The local class name.
5204 public String getLocalClassName() {
5205 final String pkg = getPackageName();
5206 final String cls = mComponent.getClassName();
5207 int packageLen = pkg.length();
5208 if (!cls.startsWith(pkg) || cls.length() <= packageLen
5209 || cls.charAt(packageLen) != '.') {
5212 return cls.substring(packageLen+1);
5216 * Returns complete component name of this activity.
5218 * @return Returns the complete component name for this activity
5220 public ComponentName getComponentName()
5226 * Retrieve a {@link SharedPreferences} object for accessing preferences
5227 * that are private to this activity. This simply calls the underlying
5228 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
5229 * class name as the preferences name.
5231 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
5232 * operation, {@link #MODE_WORLD_READABLE} and
5233 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
5235 * @return Returns the single SharedPreferences instance that can be used
5236 * to retrieve and modify the preference values.
5238 public SharedPreferences getPreferences(int mode) {
5239 return getSharedPreferences(getLocalClassName(), mode);
5242 private void ensureSearchManager() {
5243 if (mSearchManager != null) {
5247 mSearchManager = new SearchManager(this, null);
5251 public Object getSystemService(@ServiceName @NonNull String name) {
5252 if (getBaseContext() == null) {
5253 throw new IllegalStateException(
5254 "System services not available to Activities before onCreate()");
5257 if (WINDOW_SERVICE.equals(name)) {
5258 return mWindowManager;
5259 } else if (SEARCH_SERVICE.equals(name)) {
5260 ensureSearchManager();
5261 return mSearchManager;
5263 return super.getSystemService(name);
5267 * Change the title associated with this activity. If this is a
5268 * top-level activity, the title for its window will change. If it
5269 * is an embedded activity, the parent can do whatever it wants
5272 public void setTitle(CharSequence title) {
5274 onTitleChanged(title, mTitleColor);
5276 if (mParent != null) {
5277 mParent.onChildTitleChanged(this, title);
5282 * Change the title associated with this activity. If this is a
5283 * top-level activity, the title for its window will change. If it
5284 * is an embedded activity, the parent can do whatever it wants
5287 public void setTitle(int titleId) {
5288 setTitle(getText(titleId));
5292 * Change the color of the title associated with this activity.
5294 * This method is deprecated starting in API Level 11 and replaced by action
5295 * bar styles. For information on styling the Action Bar, read the <a
5296 * href="{@docRoot} guide/topics/ui/actionbar.html">Action Bar</a> developer
5299 * @deprecated Use action bar styles instead.
5302 public void setTitleColor(int textColor) {
5303 mTitleColor = textColor;
5304 onTitleChanged(mTitle, textColor);
5307 public final CharSequence getTitle() {
5311 public final int getTitleColor() {
5315 protected void onTitleChanged(CharSequence title, int color) {
5317 final Window win = getWindow();
5319 win.setTitle(title);
5321 win.setTitleColor(color);
5324 if (mActionBar != null) {
5325 mActionBar.setWindowTitle(title);
5330 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
5334 * Sets information describing the task with this activity for presentation inside the Recents
5335 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
5336 * are traversed in order from the topmost activity to the bottommost. The traversal continues
5337 * for each property until a suitable value is found. For each task the taskDescription will be
5338 * returned in {@link android.app.ActivityManager.TaskDescription}.
5340 * @see ActivityManager#getRecentTasks
5341 * @see android.app.ActivityManager.TaskDescription
5343 * @param taskDescription The TaskDescription properties that describe the task with this activity
5345 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
5346 ActivityManager.TaskDescription td;
5347 // Scale the icon down to something reasonable if it is provided
5348 if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
5349 final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
5350 final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size, true);
5351 td = new ActivityManager.TaskDescription(taskDescription.getLabel(), icon,
5352 taskDescription.getPrimaryColor());
5354 td = taskDescription;
5357 ActivityManagerNative.getDefault().setTaskDescription(mToken, td);
5358 } catch (RemoteException e) {
5363 * Sets the visibility of the progress bar in the title.
5365 * In order for the progress bar to be shown, the feature must be requested
5366 * via {@link #requestWindowFeature(int)}.
5368 * @param visible Whether to show the progress bars in the title.
5370 public final void setProgressBarVisibility(boolean visible) {
5371 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
5372 Window.PROGRESS_VISIBILITY_OFF);
5376 * Sets the visibility of the indeterminate 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 setProgressBarIndeterminateVisibility(boolean visible) {
5384 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
5385 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
5389 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
5390 * is always indeterminate).
5392 * In order for the progress bar to be shown, the feature must be requested
5393 * via {@link #requestWindowFeature(int)}.
5395 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
5397 public final void setProgressBarIndeterminate(boolean indeterminate) {
5398 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
5399 indeterminate ? Window.PROGRESS_INDETERMINATE_ON
5400 : Window.PROGRESS_INDETERMINATE_OFF);
5404 * Sets the progress for the progress bars in the title.
5406 * In order for the progress bar to be shown, the feature must be requested
5407 * via {@link #requestWindowFeature(int)}.
5409 * @param progress The progress for the progress bar. Valid ranges are from
5410 * 0 to 10000 (both inclusive). If 10000 is given, the progress
5411 * bar will be completely filled and will fade out.
5413 public final void setProgress(int progress) {
5414 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
5418 * Sets the secondary progress for the progress bar in the title. This
5419 * progress is drawn between the primary progress (set via
5420 * {@link #setProgress(int)} and the background. It can be ideal for media
5421 * scenarios such as showing the buffering progress while the default
5422 * progress shows the play progress.
5424 * In order for the progress bar to be shown, the feature must be requested
5425 * via {@link #requestWindowFeature(int)}.
5427 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
5428 * 0 to 10000 (both inclusive).
5430 public final void setSecondaryProgress(int secondaryProgress) {
5431 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
5432 secondaryProgress + Window.PROGRESS_SECONDARY_START);
5436 * Suggests an audio stream whose volume should be changed by the hardware
5439 * The suggested audio stream will be tied to the window of this Activity.
5440 * Volume requests which are received while the Activity is in the
5441 * foreground will affect this stream.
5443 * It is not guaranteed that the hardware volume controls will always change
5444 * this stream's volume (for example, if a call is in progress, its stream's
5445 * volume may be changed instead). To reset back to the default, use
5446 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
5448 * @param streamType The type of the audio stream whose volume should be
5449 * changed by the hardware volume controls.
5451 public final void setVolumeControlStream(int streamType) {
5452 getWindow().setVolumeControlStream(streamType);
5456 * Gets the suggested audio stream whose volume should be changed by the
5457 * hardware volume controls.
5459 * @return The suggested audio stream type whose volume should be changed by
5460 * the hardware volume controls.
5461 * @see #setVolumeControlStream(int)
5463 public final int getVolumeControlStream() {
5464 return getWindow().getVolumeControlStream();
5468 * Sets a {@link MediaController} to send media keys and volume changes to.
5470 * The controller will be tied to the window of this Activity. Media key and
5471 * volume events which are received while the Activity is in the foreground
5472 * will be forwarded to the controller and used to invoke transport controls
5473 * or adjust the volume. This may be used instead of or in addition to
5474 * {@link #setVolumeControlStream} to affect a specific session instead of a
5477 * It is not guaranteed that the hardware volume controls will always change
5478 * this session's volume (for example, if a call is in progress, its
5479 * stream's volume may be changed instead). To reset back to the default use
5480 * null as the controller.
5482 * @param controller The controller for the session which should receive
5483 * media keys and volume changes.
5485 public final void setMediaController(MediaController controller) {
5486 getWindow().setMediaController(controller);
5490 * Gets the controller which should be receiving media key and volume events
5491 * while this activity is in the foreground.
5493 * @return The controller which should receive events.
5494 * @see #setMediaController(android.media.session.MediaController)
5496 public final MediaController getMediaController() {
5497 return getWindow().getMediaController();
5501 * Runs the specified action on the UI thread. If the current thread is the UI
5502 * thread, then the action is executed immediately. If the current thread is
5503 * not the UI thread, the action is posted to the event queue of the UI thread.
5505 * @param action the action to run on the UI thread
5507 public final void runOnUiThread(Runnable action) {
5508 if (Thread.currentThread() != mUiThread) {
5509 mHandler.post(action);
5516 * Standard implementation of
5517 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
5518 * inflating with the LayoutInflater returned by {@link #getSystemService}.
5519 * This implementation does nothing and is for
5520 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
5521 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
5523 * @see android.view.LayoutInflater#createView
5524 * @see android.view.Window#getLayoutInflater
5527 public View onCreateView(String name, Context context, AttributeSet attrs) {
5532 * Standard implementation of
5533 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
5534 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
5535 * This implementation handles <fragment> tags to embed fragments inside
5538 * @see android.view.LayoutInflater#createView
5539 * @see android.view.Window#getLayoutInflater
5541 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
5542 if (!"fragment".equals(name)) {
5543 return onCreateView(name, context, attrs);
5546 return mFragments.onCreateView(parent, name, context, attrs);
5550 * Print the Activity's state into the given stream. This gets invoked if
5551 * you run "adb shell dumpsys activity <activity_component_name>".
5553 * @param prefix Desired prefix to prepend at each line of output.
5554 * @param fd The raw file descriptor that the dump is being sent to.
5555 * @param writer The PrintWriter to which you should dump your state. This will be
5556 * closed for you after you return.
5557 * @param args additional arguments to the dump request.
5559 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5560 dumpInner(prefix, fd, writer, args);
5563 void dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5564 writer.print(prefix); writer.print("Local Activity ");
5565 writer.print(Integer.toHexString(System.identityHashCode(this)));
5566 writer.println(" State:");
5567 String innerPrefix = prefix + " ";
5568 writer.print(innerPrefix); writer.print("mResumed=");
5569 writer.print(mResumed); writer.print(" mStopped=");
5570 writer.print(mStopped); writer.print(" mFinished=");
5571 writer.println(mFinished);
5572 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
5573 writer.println(mChangingConfigurations);
5574 writer.print(innerPrefix); writer.print("mCurrentConfig=");
5575 writer.println(mCurrentConfig);
5577 mFragments.dumpLoaders(innerPrefix, fd, writer, args);
5578 mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args);
5579 if (mVoiceInteractor != null) {
5580 mVoiceInteractor.dump(innerPrefix, fd, writer, args);
5583 if (getWindow() != null &&
5584 getWindow().peekDecorView() != null &&
5585 getWindow().peekDecorView().getViewRootImpl() != null) {
5586 getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args);
5589 mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix);
5593 * Bit indicating that this activity is "immersive" and should not be
5594 * interrupted by notifications if possible.
5596 * This value is initially set by the manifest property
5597 * <code>android:immersive</code> but may be changed at runtime by
5598 * {@link #setImmersive}.
5600 * @see #setImmersive(boolean)
5601 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
5603 public boolean isImmersive() {
5605 return ActivityManagerNative.getDefault().isImmersive(mToken);
5606 } catch (RemoteException e) {
5612 * Indication of whether this is the highest level activity in this task. Can be used to
5613 * determine whether an activity launched by this activity was placed in the same task or
5616 * @return true if this is the topmost, non-finishing activity in its task.
5618 private boolean isTopOfTask() {
5620 return ActivityManagerNative.getDefault().isTopOfTask(mToken);
5621 } catch (RemoteException e) {
5627 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} to a
5628 * fullscreen opaque Activity.
5630 * Call this whenever the background of a translucent Activity has changed to become opaque.
5631 * Doing so will allow the {@link android.view.Surface} of the Activity behind to be released.
5633 * This call has no effect on non-translucent activities or on activities with the
5634 * {@link android.R.attr#windowIsFloating} attribute.
5636 * @see #convertToTranslucent(android.app.Activity.TranslucentConversionListener,
5638 * @see TranslucentConversionListener
5643 public void convertFromTranslucent() {
5645 mTranslucentCallback = null;
5646 if (ActivityManagerNative.getDefault().convertFromTranslucent(mToken)) {
5647 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true);
5649 } catch (RemoteException e) {
5655 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} back from
5656 * opaque to translucent following a call to {@link #convertFromTranslucent()}.
5658 * Calling this allows the Activity behind this one to be seen again. Once all such Activities
5659 * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
5660 * be called indicating that it is safe to make this activity translucent again. Until
5661 * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
5662 * behind the frontmost Activity will be indeterminate.
5664 * This call has no effect on non-translucent activities or on activities with the
5665 * {@link android.R.attr#windowIsFloating} attribute.
5667 * @param callback the method to call when all visible Activities behind this one have been
5668 * drawn and it is safe to make this Activity translucent again.
5669 * @param options activity options delivered to the activity below this one. The options
5670 * are retrieved using {@link #getActivityOptions}.
5671 * @return <code>true</code> if Window was opaque and will become translucent or
5672 * <code>false</code> if window was translucent and no change needed to be made.
5674 * @see #convertFromTranslucent()
5675 * @see TranslucentConversionListener
5680 public boolean convertToTranslucent(TranslucentConversionListener callback,
5681 ActivityOptions options) {
5682 boolean drawComplete;
5684 mTranslucentCallback = callback;
5685 mChangeCanvasToTranslucent =
5686 ActivityManagerNative.getDefault().convertToTranslucent(mToken, options);
5687 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
5688 drawComplete = true;
5689 } catch (RemoteException e) {
5690 // Make callback return as though it timed out.
5691 mChangeCanvasToTranslucent = false;
5692 drawComplete = false;
5694 if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) {
5695 // Window is already translucent.
5696 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
5698 return mChangeCanvasToTranslucent;
5702 void onTranslucentConversionComplete(boolean drawComplete) {
5703 if (mTranslucentCallback != null) {
5704 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
5705 mTranslucentCallback = null;
5707 if (mChangeCanvasToTranslucent) {
5708 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
5713 public void onNewActivityOptions(ActivityOptions options) {
5714 mActivityTransitionState.setEnterActivityOptions(this, options);
5716 mActivityTransitionState.enterReady(this);
5721 * Retrieve the ActivityOptions passed in from the launching activity or passed back
5722 * from an activity launched by this activity in its call to {@link
5723 * #convertToTranslucent(TranslucentConversionListener, ActivityOptions)}
5725 * @return The ActivityOptions passed to {@link #convertToTranslucent}.
5728 ActivityOptions getActivityOptions() {
5730 return ActivityManagerNative.getDefault().getActivityOptions(mToken);
5731 } catch (RemoteException e) {
5737 * Activities that want to remain visible behind a translucent activity above them must call
5738 * this method anytime between the start of {@link #onResume()} and the return from
5739 * {@link #onPause()}. If this call is successful then the activity will remain visible after
5740 * {@link #onPause()} is called, and is allowed to continue playing media in the background.
5742 * <p>The actions of this call are reset each time that this activity is brought to the
5743 * front. That is, every time {@link #onResume()} is called the activity will be assumed
5744 * to not have requested visible behind. Therefore, if you want this activity to continue to
5745 * be visible in the background you must call this method again.
5747 * <p>Only fullscreen opaque activities may make this call. I.e. this call is a nop
5748 * for dialog and translucent activities.
5750 * <p>Under all circumstances, the activity must stop playing and release resources prior to or
5751 * within a call to {@link #onVisibleBehindCanceled()} or if this call returns false.
5753 * <p>False will be returned any time this method is called between the return of onPause and
5754 * the next call to onResume.
5756 * @param visible true to notify the system that the activity wishes to be visible behind other
5757 * translucent activities, false to indicate otherwise. Resources must be
5758 * released when passing false to this method.
5759 * @return the resulting visibiity state. If true the activity will remain visible beyond
5760 * {@link #onPause()} if the next activity is translucent or not fullscreen. If false
5761 * then the activity may not count on being visible behind other translucent activities,
5762 * and must stop any media playback and release resources.
5763 * Returning false may occur in lieu of a call to {@link #onVisibleBehindCanceled()} so
5764 * the return value must be checked.
5766 * @see #onVisibleBehindCanceled()
5767 * @see #onBackgroundVisibleBehindChanged(boolean)
5769 public boolean requestVisibleBehind(boolean visible) {
5771 // Do not permit paused or stopped activities to do this.
5775 mVisibleBehind = ActivityManagerNative.getDefault()
5776 .requestVisibleBehind(mToken, visible) && visible;
5777 } catch (RemoteException e) {
5778 mVisibleBehind = false;
5780 return mVisibleBehind;
5784 * Called when a translucent activity over this activity is becoming opaque or another
5785 * activity is being launched. Activities that override this method must call
5786 * <code>super.onVisibleBehindCanceled()</code> or a SuperNotCalledException will be thrown.
5788 * <p>When this method is called the activity has 500 msec to release any resources it may be
5789 * using while visible in the background.
5790 * If the activity has not returned from this method in 500 msec the system will destroy
5791 * the activity and kill the process in order to recover the resources for another
5792 * process. Otherwise {@link #onStop()} will be called following return.
5794 * @see #requestVisibleBehind(boolean)
5795 * @see #onBackgroundVisibleBehindChanged(boolean)
5798 public void onVisibleBehindCanceled() {
5803 * Translucent activities may call this to determine if there is an activity below them that
5804 * is currently set to be visible in the background.
5806 * @return true if an activity below is set to visible according to the most recent call to
5807 * {@link #requestVisibleBehind(boolean)}, false otherwise.
5809 * @see #requestVisibleBehind(boolean)
5810 * @see #onVisibleBehindCanceled()
5811 * @see #onBackgroundVisibleBehindChanged(boolean)
5815 public boolean isBackgroundVisibleBehind() {
5817 return ActivityManagerNative.getDefault().isBackgroundVisibleBehind(mToken);
5818 } catch (RemoteException e) {
5824 * The topmost foreground activity will receive this call when the background visibility state
5825 * of the activity below it changes.
5827 * This call may be a consequence of {@link #requestVisibleBehind(boolean)} or might be
5828 * due to a background activity finishing itself.
5830 * @param visible true if a background activity is visible, false otherwise.
5832 * @see #requestVisibleBehind(boolean)
5833 * @see #onVisibleBehindCanceled()
5837 public void onBackgroundVisibleBehindChanged(boolean visible) {
5841 * Activities cannot draw during the period that their windows are animating in. In order
5842 * to know when it is safe to begin drawing they can override this method which will be
5843 * called when the entering animation has completed.
5845 public void onEnterAnimationComplete() {
5851 public void dispatchEnterAnimationComplete() {
5852 onEnterAnimationComplete();
5853 if (getWindow() != null && getWindow().getDecorView() != null) {
5854 getWindow().getDecorView().getViewTreeObserver().dispatchOnEnterAnimationComplete();
5859 * Adjust the current immersive mode setting.
5861 * Note that changing this value will have no effect on the activity's
5862 * {@link android.content.pm.ActivityInfo} structure; that is, if
5863 * <code>android:immersive</code> is set to <code>true</code>
5864 * in the application's manifest entry for this activity, the {@link
5865 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
5866 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
5867 * FLAG_IMMERSIVE} bit set.
5869 * @see #isImmersive()
5870 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
5872 public void setImmersive(boolean i) {
5874 ActivityManagerNative.getDefault().setImmersive(mToken, i);
5875 } catch (RemoteException e) {
5881 * Start an action mode of the default type {@link ActionMode#TYPE_PRIMARY}.
5883 * @param callback Callback that will manage lifecycle events for this action mode
5884 * @return The ActionMode that was started, or null if it was canceled
5889 public ActionMode startActionMode(ActionMode.Callback callback) {
5890 return mWindow.getDecorView().startActionMode(callback);
5894 * Start an action mode of the given type.
5896 * @param callback Callback that will manage lifecycle events for this action mode
5897 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5898 * @return The ActionMode that was started, or null if it was canceled
5903 public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5904 return mWindow.getDecorView().startActionMode(callback, type);
5908 * Give the Activity a chance to control the UI for an action mode requested
5911 * <p>Note: If you are looking for a notification callback that an action mode
5912 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
5914 * @param callback The callback that should control the new action mode
5915 * @return The new action mode, or <code>null</code> if the activity does not want to
5916 * provide special handling for this action mode. (It will be handled by the system.)
5920 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
5921 // Only Primary ActionModes are represented in the ActionBar.
5922 if (mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
5923 initWindowDecorActionBar();
5924 if (mActionBar != null) {
5925 return mActionBar.startActionMode(callback);
5936 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
5938 mActionModeTypeStarting = type;
5939 return onWindowStartingActionMode(callback);
5941 mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
5946 * Notifies the Activity that an action mode has been started.
5947 * Activity subclasses overriding this method should call the superclass implementation.
5949 * @param mode The new action mode.
5953 public void onActionModeStarted(ActionMode mode) {
5957 * Notifies the activity that an action mode has finished.
5958 * Activity subclasses overriding this method should call the superclass implementation.
5960 * @param mode The action mode that just finished.
5964 public void onActionModeFinished(ActionMode mode) {
5968 * Returns true if the app should recreate the task when navigating 'up' from this activity
5969 * by using targetIntent.
5971 * <p>If this method returns false the app can trivially call
5972 * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
5973 * up navigation. If this method returns false, the app should synthesize a new task stack
5974 * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
5976 * @param targetIntent An intent representing the target destination for up navigation
5977 * @return true if navigating up should recreate a new task stack, false if the same task
5978 * should be used for the destination
5980 public boolean shouldUpRecreateTask(Intent targetIntent) {
5982 PackageManager pm = getPackageManager();
5983 ComponentName cn = targetIntent.getComponent();
5985 cn = targetIntent.resolveActivity(pm);
5987 ActivityInfo info = pm.getActivityInfo(cn, 0);
5988 if (info.taskAffinity == null) {
5991 return ActivityManagerNative.getDefault()
5992 .shouldUpRecreateTask(mToken, info.taskAffinity);
5993 } catch (RemoteException e) {
5995 } catch (NameNotFoundException e) {
6001 * Navigate from this activity to the activity specified by upIntent, finishing this activity
6002 * in the process. If the activity indicated by upIntent already exists in the task's history,
6003 * this activity and all others before the indicated activity in the history stack will be
6006 * <p>If the indicated activity does not appear in the history stack, this will finish
6007 * each activity in this task until the root activity of the task is reached, resulting in
6008 * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
6009 * when an activity may be reached by a path not passing through a canonical parent
6012 * <p>This method should be used when performing up navigation from within the same task
6013 * as the destination. If up navigation should cross tasks in some cases, see
6014 * {@link #shouldUpRecreateTask(Intent)}.</p>
6016 * @param upIntent An intent representing the target destination for up navigation
6018 * @return true if up navigation successfully reached the activity indicated by upIntent and
6019 * upIntent was delivered to it. false if an instance of the indicated activity could
6020 * not be found and this activity was simply finished normally.
6022 public boolean navigateUpTo(Intent upIntent) {
6023 if (mParent == null) {
6024 ComponentName destInfo = upIntent.getComponent();
6025 if (destInfo == null) {
6026 destInfo = upIntent.resolveActivity(getPackageManager());
6027 if (destInfo == null) {
6030 upIntent = new Intent(upIntent);
6031 upIntent.setComponent(destInfo);
6035 synchronized (this) {
6036 resultCode = mResultCode;
6037 resultData = mResultData;
6039 if (resultData != null) {
6040 resultData.prepareToLeaveProcess();
6043 upIntent.prepareToLeaveProcess();
6044 return ActivityManagerNative.getDefault().navigateUpTo(mToken, upIntent,
6045 resultCode, resultData);
6046 } catch (RemoteException e) {
6050 return mParent.navigateUpToFromChild(this, upIntent);
6055 * This is called when a child activity of this one calls its
6056 * {@link #navigateUpTo} method. The default implementation simply calls
6057 * navigateUpTo(upIntent) on this activity (the parent).
6059 * @param child The activity making the call.
6060 * @param upIntent An intent representing the target destination for up navigation
6062 * @return true if up navigation successfully reached the activity indicated by upIntent and
6063 * upIntent was delivered to it. false if an instance of the indicated activity could
6064 * not be found and this activity was simply finished normally.
6066 public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
6067 return navigateUpTo(upIntent);
6071 * Obtain an {@link Intent} that will launch an explicit target activity specified by
6072 * this activity's logical parent. The logical parent is named in the application's manifest
6073 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
6074 * Activity subclasses may override this method to modify the Intent returned by
6075 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
6076 * the parent intent entirely.
6078 * @return a new Intent targeting the defined parent of this activity or null if
6079 * there is no valid parent.
6082 public Intent getParentActivityIntent() {
6083 final String parentName = mActivityInfo.parentActivityName;
6084 if (TextUtils.isEmpty(parentName)) {
6088 // If the parent itself has no parent, generate a main activity intent.
6089 final ComponentName target = new ComponentName(this, parentName);
6091 final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
6092 final String parentActivity = parentInfo.parentActivityName;
6093 final Intent parentIntent = parentActivity == null
6094 ? Intent.makeMainActivity(target)
6095 : new Intent().setComponent(target);
6096 return parentIntent;
6097 } catch (NameNotFoundException e) {
6098 Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
6105 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6106 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6107 * will be called to handle shared elements on the <i>launched</i> Activity. This requires
6108 * {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6110 * @param callback Used to manipulate shared element transitions on the launched Activity.
6112 public void setEnterSharedElementCallback(SharedElementCallback callback) {
6113 if (callback == null) {
6114 callback = SharedElementCallback.NULL_CALLBACK;
6116 mEnterTransitionListener = callback;
6120 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6121 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6122 * will be called to handle shared elements on the <i>launching</i> Activity. Most
6123 * calls will only come when returning from the started Activity.
6124 * This requires {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6126 * @param callback Used to manipulate shared element transitions on the launching Activity.
6128 public void setExitSharedElementCallback(SharedElementCallback callback) {
6129 if (callback == null) {
6130 callback = SharedElementCallback.NULL_CALLBACK;
6132 mExitTransitionListener = callback;
6136 * Postpone the entering activity transition when Activity was started with
6137 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6138 * android.util.Pair[])}.
6139 * <p>This method gives the Activity the ability to delay starting the entering and
6140 * shared element transitions until all data is loaded. Until then, the Activity won't
6141 * draw into its window, leaving the window transparent. This may also cause the
6142 * returning animation to be delayed until data is ready. This method should be
6143 * called in {@link #onCreate(android.os.Bundle)} or in
6144 * {@link #onActivityReenter(int, android.content.Intent)}.
6145 * {@link #startPostponedEnterTransition()} must be called to allow the Activity to
6146 * start the transitions. If the Activity did not use
6147 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6148 * android.util.Pair[])}, then this method does nothing.</p>
6150 public void postponeEnterTransition() {
6151 mActivityTransitionState.postponeEnterTransition();
6155 * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
6156 * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
6157 * to have your Activity start drawing.
6159 public void startPostponedEnterTransition() {
6160 mActivityTransitionState.startPostponedEnterTransition();
6163 // ------------------ Internal API ------------------
6165 final void setParent(Activity parent) {
6169 final void attach(Context context, ActivityThread aThread,
6170 Instrumentation instr, IBinder token, int ident,
6171 Application application, Intent intent, ActivityInfo info,
6172 CharSequence title, Activity parent, String id,
6173 NonConfigurationInstances lastNonConfigurationInstances,
6174 Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
6175 attachBaseContext(context);
6177 mFragments.attachHost(null /*parent*/);
6179 mWindow = new PhoneWindow(this);
6180 mWindow.setCallback(this);
6181 mWindow.setOnWindowDismissedCallback(this);
6182 mWindow.getLayoutInflater().setPrivateFactory(this);
6183 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
6184 mWindow.setSoftInputMode(info.softInputMode);
6186 if (info.uiOptions != 0) {
6187 mWindow.setUiOptions(info.uiOptions);
6189 mUiThread = Thread.currentThread();
6191 mMainThread = aThread;
6192 mInstrumentation = instr;
6195 mApplication = application;
6197 mReferrer = referrer;
6198 mComponent = intent.getComponent();
6199 mActivityInfo = info;
6203 mLastNonConfigurationInstances = lastNonConfigurationInstances;
6204 if (voiceInteractor != null) {
6205 if (lastNonConfigurationInstances != null) {
6206 mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
6208 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
6213 mWindow.setWindowManager(
6214 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
6215 mToken, mComponent.flattenToString(),
6216 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
6217 if (mParent != null) {
6218 mWindow.setContainer(mParent.getWindow());
6220 mWindowManager = mWindow.getWindowManager();
6221 mCurrentConfig = config;
6225 public final IBinder getActivityToken() {
6226 return mParent != null ? mParent.getActivityToken() : mToken;
6229 final void performCreateCommon() {
6230 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
6231 com.android.internal.R.styleable.Window_windowNoDisplay, false);
6232 mFragments.dispatchActivityCreated();
6233 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
6236 final void performCreate(Bundle icicle) {
6238 mActivityTransitionState.readState(icicle);
6239 performCreateCommon();
6242 final void performCreate(Bundle icicle, PersistableBundle persistentState) {
6243 onCreate(icicle, persistentState);
6244 mActivityTransitionState.readState(icicle);
6245 performCreateCommon();
6248 final void performStart() {
6249 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
6250 mFragments.noteStateNotSaved();
6252 mFragments.execPendingActions();
6253 mInstrumentation.callActivityOnStart(this);
6255 throw new SuperNotCalledException(
6256 "Activity " + mComponent.toShortString() +
6257 " did not call through to super.onStart()");
6259 mFragments.dispatchStart();
6260 mFragments.reportLoaderStart();
6261 mActivityTransitionState.enterReady(this);
6264 final void performRestart() {
6265 mFragments.noteStateNotSaved();
6269 if (mToken != null && mParent == null) {
6270 WindowManagerGlobal.getInstance().setStoppedState(mToken, false);
6273 synchronized (mManagedCursors) {
6274 final int N = mManagedCursors.size();
6275 for (int i=0; i<N; i++) {
6276 ManagedCursor mc = mManagedCursors.get(i);
6277 if (mc.mReleased || mc.mUpdated) {
6278 if (!mc.mCursor.requery()) {
6279 if (getApplicationInfo().targetSdkVersion
6280 >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
6281 throw new IllegalStateException(
6282 "trying to requery an already closed cursor "
6286 mc.mReleased = false;
6287 mc.mUpdated = false;
6293 mInstrumentation.callActivityOnRestart(this);
6295 throw new SuperNotCalledException(
6296 "Activity " + mComponent.toShortString() +
6297 " did not call through to super.onRestart()");
6303 final void performResume() {
6306 mFragments.execPendingActions();
6308 mLastNonConfigurationInstances = null;
6311 // mResumed is set by the instrumentation
6312 mInstrumentation.callActivityOnResume(this);
6314 throw new SuperNotCalledException(
6315 "Activity " + mComponent.toShortString() +
6316 " did not call through to super.onResume()");
6319 // invisible activities must be finished before onResume() completes
6320 if (!mVisibleFromClient && !mFinished) {
6321 Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
6322 if (getApplicationInfo().targetSdkVersion
6323 > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
6324 throw new IllegalStateException(
6325 "Activity " + mComponent.toShortString() +
6326 " did not call finish() prior to onResume() completing");
6330 // Now really resume, and install the current status bar and menu.
6333 mFragments.dispatchResume();
6334 mFragments.execPendingActions();
6338 throw new SuperNotCalledException(
6339 "Activity " + mComponent.toShortString() +
6340 " did not call through to super.onPostResume()");
6344 final void performPause() {
6345 mDoReportFullyDrawn = false;
6346 mFragments.dispatchPause();
6350 if (!mCalled && getApplicationInfo().targetSdkVersion
6351 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
6352 throw new SuperNotCalledException(
6353 "Activity " + mComponent.toShortString() +
6354 " did not call through to super.onPause()");
6359 final void performUserLeaving() {
6360 onUserInteraction();
6364 final void performStop() {
6365 mDoReportFullyDrawn = false;
6366 mFragments.doLoaderStop(mChangingConfigurations /*retain*/);
6369 if (mWindow != null) {
6370 mWindow.closeAllPanels();
6373 if (mToken != null && mParent == null) {
6374 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
6377 mFragments.dispatchStop();
6380 mInstrumentation.callActivityOnStop(this);
6382 throw new SuperNotCalledException(
6383 "Activity " + mComponent.toShortString() +
6384 " did not call through to super.onStop()");
6387 synchronized (mManagedCursors) {
6388 final int N = mManagedCursors.size();
6389 for (int i=0; i<N; i++) {
6390 ManagedCursor mc = mManagedCursors.get(i);
6391 if (!mc.mReleased) {
6392 mc.mCursor.deactivate();
6393 mc.mReleased = true;
6403 final void performDestroy() {
6406 mFragments.dispatchDestroy();
6408 mFragments.doLoaderDestroy();
6409 if (mVoiceInteractor != null) {
6410 mVoiceInteractor.detachActivity();
6417 public final boolean isResumed() {
6421 void dispatchActivityResult(String who, int requestCode,
6422 int resultCode, Intent data) {
6424 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
6425 + ", resCode=" + resultCode + ", data=" + data);
6426 mFragments.noteStateNotSaved();
6428 onActivityResult(requestCode, resultCode, data);
6429 } else if (who.startsWith(REQUEST_PERMISSIONS_WHO_PREFIX)) {
6430 who = who.substring(REQUEST_PERMISSIONS_WHO_PREFIX.length());
6431 if (TextUtils.isEmpty(who)) {
6432 dispatchRequestPermissionsResult(requestCode, data);
6434 Fragment frag = mFragments.findFragmentByWho(who);
6436 dispatchRequestPermissionsResultToFragment(requestCode, data, frag);
6439 } else if (who.startsWith("@android:view:")) {
6440 ArrayList<ViewRootImpl> views = WindowManagerGlobal.getInstance().getRootViews(
6441 getActivityToken());
6442 for (ViewRootImpl viewRoot : views) {
6443 if (viewRoot.getView() != null
6444 && viewRoot.getView().dispatchActivityResult(
6445 who, requestCode, resultCode, data)) {
6450 Fragment frag = mFragments.findFragmentByWho(who);
6452 frag.onActivityResult(requestCode, resultCode, data);
6458 * Request to put this Activity in a mode where the user is locked to the
6461 * This will prevent the user from launching other apps, going to settings, or reaching the
6462 * home screen. This does not include those apps whose {@link android.R.attr#lockTaskMode}
6463 * values permit launching while locked.
6465 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns true or
6466 * lockTaskMode=lockTaskModeAlways for this component then the app will go directly into
6467 * Lock Task mode. The user will not be able to exit this mode until
6468 * {@link Activity#stopLockTask()} is called.
6470 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns false
6471 * then the system will prompt the user with a dialog requesting permission to enter
6472 * this mode. When entered through this method the user can exit at any time through
6473 * an action described by the request dialog. Calling stopLockTask will also exit the
6476 * @see android.R.attr#lockTaskMode
6478 public void startLockTask() {
6480 ActivityManagerNative.getDefault().startLockTaskMode(mToken);
6481 } catch (RemoteException e) {
6486 * Allow the user to switch away from the current task.
6488 * Called to end the mode started by {@link Activity#startLockTask}. This
6489 * can only be called by activities that have successfully called
6490 * startLockTask previously.
6492 * This will allow the user to exit this app and move onto other activities.
6493 * <p>Note: This method should only be called when the activity is user-facing. That is,
6494 * between onResume() and onPause().
6495 * <p>Note: If there are other tasks below this one that are also locked then calling this
6496 * method will immediately finish this task and resume the previous locked one, remaining in
6499 * @see android.R.attr#lockTaskMode
6500 * @see ActivityManager#getLockTaskModeState()
6502 public void stopLockTask() {
6504 ActivityManagerNative.getDefault().stopLockTaskMode();
6505 } catch (RemoteException e) {
6510 * Shows the user the system defined message for telling the user how to exit
6511 * lock task mode. The task containing this activity must be in lock task mode at the time
6512 * of this call for the message to be displayed.
6514 public void showLockTaskEscapeMessage() {
6516 ActivityManagerNative.getDefault().showLockTaskEscapeMessage(mToken);
6517 } catch (RemoteException e) {
6522 * Interface for informing a translucent {@link Activity} once all visible activities below it
6523 * have completed drawing. This is necessary only after an {@link Activity} has been made
6524 * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
6525 * translucent again following a call to {@link
6526 * Activity#convertToTranslucent(android.app.Activity.TranslucentConversionListener,
6532 public interface TranslucentConversionListener {
6534 * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
6535 * below the top one have been redrawn. Following this callback it is safe to make the top
6536 * Activity translucent because the underlying Activity has been drawn.
6538 * @param drawComplete True if the background Activity has drawn itself. False if a timeout
6539 * occurred waiting for the Activity to complete drawing.
6541 * @see Activity#convertFromTranslucent()
6542 * @see Activity#convertToTranslucent(TranslucentConversionListener, ActivityOptions)
6544 public void onTranslucentConversionComplete(boolean drawComplete);
6547 private void dispatchRequestPermissionsResult(int requestCode, Intent data) {
6548 // If the package installer crashed we may have not data - best effort.
6549 String[] permissions = (data != null) ? data.getStringArrayExtra(
6550 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
6551 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
6552 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
6553 onRequestPermissionsResult(requestCode, permissions, grantResults);
6556 private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data,
6557 Fragment fragment) {
6558 // If the package installer crashed we may have not data - best effort.
6559 String[] permissions = (data != null) ? data.getStringArrayExtra(
6560 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
6561 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
6562 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
6563 fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
6566 class HostCallbacks extends FragmentHostCallback<Activity> {
6567 public HostCallbacks() {
6568 super(Activity.this /*activity*/);
6572 public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
6573 Activity.this.dump(prefix, fd, writer, args);
6577 public boolean onShouldSaveFragmentState(Fragment fragment) {
6578 return !isFinishing();
6582 public LayoutInflater onGetLayoutInflater() {
6583 final LayoutInflater result = Activity.this.getLayoutInflater();
6584 if (onUseFragmentManagerInflaterFactory()) {
6585 return result.cloneInContext(Activity.this);
6591 public boolean onUseFragmentManagerInflaterFactory() {
6592 // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
6593 return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
6597 public Activity onGetHost() {
6598 return Activity.this;
6602 public void onInvalidateOptionsMenu() {
6603 Activity.this.invalidateOptionsMenu();
6607 public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
6609 Activity.this.startActivityFromFragment(fragment, intent, requestCode, options);
6613 public void onRequestPermissionsFromFragment(Fragment fragment, String[] permissions,
6615 String who = REQUEST_PERMISSIONS_WHO_PREFIX + fragment.mWho;
6616 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
6617 startActivityForResult(who, intent, requestCode, null);
6621 public boolean onHasWindowAnimations() {
6622 return getWindow() != null;
6626 public int onGetWindowAnimations() {
6627 final Window w = getWindow();
6628 return (w == null) ? 0 : w.getAttributes().windowAnimations;
6632 public void onAttachFragment(Fragment fragment) {
6633 Activity.this.onAttachFragment(fragment);
6638 public View onFindViewById(int id) {
6639 return Activity.this.findViewById(id);
6643 public boolean onHasView() {
6644 final Window w = getWindow();
6645 return (w != null && w.peekDecorView() != null);