Debian Codegraph @

core/java/android/app/Activity.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.app;
18
19 import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
20 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
21 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
22 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
23 import static android.app.WindowConfiguration.inMultiWindowMode;
24 import static android.os.Process.myUid;
25
26 import static java.lang.Character.MIN_VALUE;
27
28 import android.annotation.CallSuper;
29 import android.annotation.DrawableRes;
30 import android.annotation.IdRes;
31 import android.annotation.IntDef;
32 import android.annotation.LayoutRes;
33 import android.annotation.MainThread;
34 import android.annotation.NonNull;
35 import android.annotation.Nullable;
36 import android.annotation.RequiresPermission;
37 import android.annotation.StyleRes;
38 import android.annotation.SuppressLint;
39 import android.annotation.SystemApi;
40 import android.annotation.TestApi;
41 import android.annotation.UiContext;
42 import android.app.VoiceInteractor.Request;
43 import android.app.admin.DevicePolicyManager;
44 import android.app.assist.AssistContent;
45 import android.app.compat.CompatChanges;
46 import android.compat.annotation.ChangeId;
47 import android.compat.annotation.EnabledSince;
48 import android.compat.annotation.UnsupportedAppUsage;
49 import android.content.ActivityNotFoundException;
50 import android.content.ComponentCallbacks;
51 import android.content.ComponentCallbacks2;
52 import android.content.ComponentCallbacksController;
53 import android.content.ComponentName;
54 import android.content.ContentResolver;
55 import android.content.Context;
56 import android.content.CursorLoader;
57 import android.content.IIntentSender;
58 import android.content.Intent;
59 import android.content.IntentSender;
60 import android.content.LocusId;
61 import android.content.SharedPreferences;
62 import android.content.pm.ActivityInfo;
63 import android.content.pm.ApplicationInfo;
64 import android.content.pm.PackageManager;
65 import android.content.pm.PackageManager.NameNotFoundException;
66 import android.content.res.Configuration;
67 import android.content.res.Resources;
68 import android.content.res.TypedArray;
69 import android.database.Cursor;
70 import android.graphics.Bitmap;
71 import android.graphics.Canvas;
72 import android.graphics.Color;
73 import android.graphics.drawable.Drawable;
74 import android.graphics.drawable.Icon;
75 import android.media.AudioManager;
76 import android.media.session.MediaController;
77 import android.net.Uri;
78 import android.os.BadParcelableException;
79 import android.os.Build;
80 import android.os.Bundle;
81 import android.os.CancellationSignal;
82 import android.os.GraphicsEnvironment;
83 import android.os.Handler;
84 import android.os.IBinder;
85 import android.os.Looper;
86 import android.os.Parcelable;
87 import android.os.PersistableBundle;
88 import android.os.Process;
89 import android.os.RemoteException;
90 import android.os.ServiceManager;
91 import android.os.ServiceManager.ServiceNotFoundException;
92 import android.os.StrictMode;
93 import android.os.Trace;
94 import android.os.UserHandle;
95 import android.service.voice.VoiceInteractionSession;
96 import android.text.Selection;
97 import android.text.SpannableStringBuilder;
98 import android.text.TextUtils;
99 import android.text.method.TextKeyListener;
100 import android.transition.Scene;
101 import android.transition.TransitionManager;
102 import android.util.ArrayMap;
103 import android.util.AttributeSet;
104 import android.util.Dumpable;
105 import android.util.EventLog;
106 import android.util.Log;
107 import android.util.PrintWriterPrinter;
108 import android.util.Slog;
109 import android.util.SparseArray;
110 import android.util.SuperNotCalledException;
111 import android.view.ActionMode;
112 import android.view.ContextMenu;
113 import android.view.ContextMenu.ContextMenuInfo;
114 import android.view.ContextThemeWrapper;
115 import android.view.DragAndDropPermissions;
116 import android.view.DragEvent;
117 import android.view.KeyEvent;
118 import android.view.KeyboardShortcutGroup;
119 import android.view.KeyboardShortcutInfo;
120 import android.view.LayoutInflater;
121 import android.view.Menu;
122 import android.view.MenuInflater;
123 import android.view.MenuItem;
124 import android.view.MotionEvent;
125 import android.view.RemoteAnimationDefinition;
126 import android.view.SearchEvent;
127 import android.view.View;
128 import android.view.View.OnCreateContextMenuListener;
129 import android.view.ViewGroup;
130 import android.view.ViewGroup.LayoutParams;
131 import android.view.ViewManager;
132 import android.view.ViewRootImpl;
133 import android.view.ViewRootImpl.ActivityConfigCallback;
134 import android.view.Window;
135 import android.view.Window.WindowControllerCallback;
136 import android.view.WindowManager;
137 import android.view.WindowManagerGlobal;
138 import android.view.accessibility.AccessibilityEvent;
139 import android.view.autofill.AutofillClientController;
140 import android.view.autofill.AutofillId;
141 import android.view.autofill.AutofillManager.AutofillClient;
142 import android.view.contentcapture.ContentCaptureContext;
143 import android.view.contentcapture.ContentCaptureManager;
144 import android.view.contentcapture.ContentCaptureManager.ContentCaptureClient;
145 import android.view.translation.TranslationSpec;
146 import android.view.translation.UiTranslationController;
147 import android.view.translation.UiTranslationSpec;
148 import android.widget.AdapterView;
149 import android.widget.Toast;
150 import android.widget.Toolbar;
151 import android.window.OnBackInvokedCallback;
152 import android.window.OnBackInvokedDispatcher;
153 import android.window.SplashScreen;
154 import android.window.WindowOnBackInvokedDispatcher;
155
156 import com.android.internal.R;
157 import com.android.internal.annotations.GuardedBy;
158 import com.android.internal.annotations.VisibleForTesting;
159 import com.android.internal.app.IVoiceInteractionManagerService;
160 import com.android.internal.app.IVoiceInteractor;
161 import com.android.internal.app.ToolbarActionBar;
162 import com.android.internal.app.WindowDecorActionBar;
163 import com.android.internal.policy.PhoneWindow;
164 import com.android.internal.util.dump.DumpableContainerImpl;
165
166 import dalvik.system.VMRuntime;
167
168 import java.io.FileDescriptor;
169 import java.io.PrintWriter;
170 import java.lang.annotation.Retention;
171 import java.lang.annotation.RetentionPolicy;
172 import java.lang.ref.WeakReference;
173 import java.util.ArrayList;
174 import java.util.Collections;
175 import java.util.HashMap;
176 import java.util.List;
177 import java.util.concurrent.Executor;
178 import java.util.function.Consumer;
179
180
181 /**
182 * An activity is a single, focused thing that the user can do. Almost all
183 * activities interact with the user, so the Activity class takes care of
184 * creating a window for you in which you can place your UI with
185 * {@link #setContentView}. While activities are often presented to the user
186 * as full-screen windows, they can also be used in other ways: as floating
187 * windows (via a theme with {@link android.R.attr#windowIsFloating} set),
188 * <a href="https://developer.android.com/guide/topics/ui/multi-window">
189 * Multi-Window mode</a> or embedded into other windows.
190 *
191 * There are two methods almost all subclasses of Activity will implement:
192 *
193 * <ul>
194 * <li> {@link #onCreate} is where you initialize your activity. Most
195 * importantly, here you will usually call {@link #setContentView(int)}
196 * with a layout resource defining your UI, and using {@link #findViewById}
197 * to retrieve the widgets in that UI that you need to interact with
198 * programmatically.
199 *
200 * <li> {@link #onPause} is where you deal with the user pausing active
201 * interaction with the activity. Any changes made by the user should at
202 * this point be committed (usually to the
203 * {@link android.content.ContentProvider} holding the data). In this
204 * state the activity is still visible on screen.
205 * </ul>
206 *
207 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
208 * activity classes must have a corresponding
209 * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
210 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
211 *
212 * <p>Topics covered here:
213 * <ol>
214 * <li><a href="#Fragments">Fragments</a>
215 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
216 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
217 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
218 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
219 * <li><a href="#Permissions">Permissions</a>
220 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
221 * </ol>
222 *
223 * <div class="special reference">
224 * <h3>Developer Guides</h3>
225 * <p>The Activity class is an important part of an application's overall lifecycle,
226 * and the way activities are launched and put together is a fundamental
227 * part of the platform's application model. For a detailed perspective on the structure of an
228 * Android application and how activities behave, please read the
229 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and
230 * <a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>
231 * developer guides.</p>
232 *
233 * <p>You can also find a detailed discussion about how to create activities in the
234 * <a href="{@docRoot}guide/components/activities.html">Activities</a>
235 * developer guide.</p>
236 * </div>
237 *
238 * <a name="Fragments"></a>
239 * <h3>Fragments</h3>
240 *
241 * <p>The {@link androidx.fragment.app.FragmentActivity} subclass
242 * can make use of the {@link androidx.fragment.app.Fragment} class to better
243 * modularize their code, build more sophisticated user interfaces for larger
244 * screens, and help scale their application between small and large screens.</p>
245 *
246 * <p>For more information about using fragments, read the
247 * <a href="{@docRoot}guide/components/fragments.html">Fragments</a> developer guide.</p>
248 *
249 * <a name="ActivityLifecycle"></a>
250 * <h3>Activity Lifecycle</h3>
251 *
252 * <p>Activities in the system are managed as
253 * <a href="https://developer.android.com/guide/components/activities/tasks-and-back-stack">
254 * activity stacks</a>. When a new activity is started, it is usually placed on the top of the
255 * current stack and becomes the running activity -- the previous activity always remains
256 * below it in the stack, and will not come to the foreground again until
257 * the new activity exits. There can be one or multiple activity stacks visible
258 * on screen.</p>
259 *
260 * <p>An activity has essentially four states:</p>
261 * <ul>
262 * <li>If an activity is in the foreground of the screen (at the highest position of the topmost
263 * stack), it is <em>active</em> or <em>running</em>. This is usually the activity that the
264 * user is currently interacting with.</li>
265 * <li>If an activity has lost focus but is still presented to the user, it is <em>visible</em>.
266 * It is possible if a new non-full-sized or transparent activity has focus on top of your
267 * activity, another activity has higher position in multi-window mode, or the activity
268 * itself is not focusable in current windowing mode. Such activity is completely alive (it
269 * maintains all state and member information and remains attached to the window manager).
270 * <li>If an activity is completely obscured by another activity,
271 * it is <em>stopped</em> or <em>hidden</em>. It still retains all state and member
272 * information, however, it is no longer visible to the user so its window is hidden
273 * and it will often be killed by the system when memory is needed elsewhere.</li>
274 * <li>The system can drop the activity from memory by either asking it to finish,
275 * or simply killing its process, making it <em>destroyed</em>. When it is displayed again
276 * to the user, it must be completely restarted and restored to its previous state.</li>
277 * </ul>
278 *
279 * <p>The following diagram shows the important state paths of an Activity.
280 * The square rectangles represent callback methods you can implement to
281 * perform operations when the Activity moves between states. The colored
282 * ovals are major states the Activity can be in.</p>
283 *
284 * <p><img src="../../../images/activity_lifecycle.png"
285 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
286 *
287 * <p>There are three key loops you may be interested in monitoring within your
288 * activity:
289 *
290 * <ul>
291 * <li>The <b>entire lifetime</b> of an activity happens between the first call
292 * to {@link android.app.Activity#onCreate} through to a single final call
293 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
294 * of "global" state in onCreate(), and release all remaining resources in
295 * onDestroy(). For example, if it has a thread running in the background
296 * to download data from the network, it may create that thread in onCreate()
297 * and then stop the thread in onDestroy().
298 *
299 * <li>The <b>visible lifetime</b> of an activity happens between a call to
300 * {@link android.app.Activity#onStart} until a corresponding call to
301 * {@link android.app.Activity#onStop}. During this time the user can see the
302 * activity on-screen, though it may not be in the foreground and interacting
303 * with the user. Between these two methods you can maintain resources that
304 * are needed to show the activity to the user. For example, you can register
305 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
306 * that impact your UI, and unregister it in onStop() when the user no
307 * longer sees what you are displaying. The onStart() and onStop() methods
308 * can be called multiple times, as the activity becomes visible and hidden
309 * to the user.
310 *
311 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
312 * {@link android.app.Activity#onResume} until a corresponding call to
313 * {@link android.app.Activity#onPause}. During this time the activity is
314 * visible, active and interacting with the user. An activity
315 * can frequently go between the resumed and paused states -- for example when
316 * the device goes to sleep, when an activity result is delivered, when a new
317 * intent is delivered -- so the code in these methods should be fairly
318 * lightweight.
319 * </ul>
320 *
321 * <p>The entire lifecycle of an activity is defined by the following
322 * Activity methods. All of these are hooks that you can override
323 * to do appropriate work when the activity changes state. All
324 * activities will implement {@link android.app.Activity#onCreate}
325 * to do their initial setup; many will also implement
326 * {@link android.app.Activity#onPause} to commit changes to data and
327 * prepare to pause interacting with the user, and {@link android.app.Activity#onStop}
328 * to handle no longer being visible on screen. You should always
329 * call up to your superclass when implementing these methods.</p>
330 *
331 * </p>
332 * <pre class="prettyprint">
333 * public class Activity extends ApplicationContext {
334 * protected void onCreate(Bundle savedInstanceState);
335 *
336 * protected void onStart();
337 *
338 * protected void onRestart();
339 *
340 * protected void onResume();
341 *
342 * protected void onPause();
343 *
344 * protected void onStop();
345 *
346 * protected void onDestroy();
347 * }
348 * </pre>
349 *
350 * <p>In general the movement through an activity's lifecycle looks like
351 * this:</p>
352 *
353 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
354 * <colgroup align="left" span="3" />
355 * <colgroup align="left" />
356 * <colgroup align="center" />
357 * <colgroup align="center" />
358 *
359 * <thead>
360 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
361 * </thead>
362 *
363 * <tbody>
364 * <tr><td colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</td>
365 * <td>Called when the activity is first created.
366 * This is where you should do all of your normal static set up:
367 * create views, bind data to lists, etc. This method also
368 * provides you with a Bundle containing the activity's previously
369 * frozen state, if there was one.
370 * <p>Always followed by <code>onStart()</code>.</td>
371 * <td align="center">No</td>
372 * <td align="center"><code>onStart()</code></td>
373 * </tr>
374 *
375 * <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
376 * <td colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</td>
377 * <td>Called after your activity has been stopped, prior to it being
378 * started again.
379 * <p>Always followed by <code>onStart()</code></td>
380 * <td align="center">No</td>
381 * <td align="center"><code>onStart()</code></td>
382 * </tr>
383 *
384 * <tr><td colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</td>
385 * <td>Called when the activity is becoming visible to the user.
386 * <p>Followed by <code>onResume()</code> if the activity comes
387 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
388 * <td align="center">No</td>
389 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
390 * </tr>
391 *
392 * <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
393 * <td align="left" border="0">{@link android.app.Activity#onResume onResume()}</td>
394 * <td>Called when the activity will start
395 * interacting with the user. At this point your activity is at
396 * the top of its activity stack, with user input going to it.
397 * <p>Always followed by <code>onPause()</code>.</td>
398 * <td align="center">No</td>
399 * <td align="center"><code>onPause()</code></td>
400 * </tr>
401 *
402 * <tr><td align="left" border="0">{@link android.app.Activity#onPause onPause()}</td>
403 * <td>Called when the activity loses foreground state, is no longer focusable or before
404 * transition to stopped/hidden or destroyed state. The activity is still visible to
405 * user, so it's recommended to keep it visually active and continue updating the UI.
406 * Implementations of this method must be very quick because
407 * the next activity will not be resumed until this method returns.
408 * <p>Followed by either <code>onResume()</code> if the activity
409 * returns back to the front, or <code>onStop()</code> if it becomes
410 * invisible to the user.</td>
411 * <td align="center"><font color="#800000"><strong>Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB}</strong></font></td>
412 * <td align="center"><code>onResume()</code> or<br>
413 * <code>onStop()</code></td>
414 * </tr>
415 *
416 * <tr><td colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</td>
417 * <td>Called when the activity is no longer visible to the user. This may happen either
418 * because a new activity is being started on top, an existing one is being brought in
419 * front of this one, or this one is being destroyed. This is typically used to stop
420 * animations and refreshing the UI, etc.
421 * <p>Followed by either <code>onRestart()</code> if
422 * this activity is coming back to interact with the user, or
423 * <code>onDestroy()</code> if this activity is going away.</td>
424 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
425 * <td align="center"><code>onRestart()</code> or<br>
426 * <code>onDestroy()</code></td>
427 * </tr>
428 *
429 * <tr><td colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</td>
430 * <td>The final call you receive before your
431 * activity is destroyed. This can happen either because the
432 * activity is finishing (someone called {@link Activity#finish} on
433 * it), or because the system is temporarily destroying this
434 * instance of the activity to save space. You can distinguish
435 * between these two scenarios with the {@link
436 * Activity#isFinishing} method.</td>
437 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
438 * <td align="center"><em>nothing</em></td>
439 * </tr>
440 * </tbody>
441 * </table>
442 *
443 * <p>Note the "Killable" column in the above table -- for those methods that
444 * are marked as being killable, after that method returns the process hosting the
445 * activity may be killed by the system <em>at any time</em> without another line
446 * of its code being executed. Because of this, you should use the
447 * {@link #onPause} method to write any persistent data (such as user edits)
448 * to storage. In addition, the method
449 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
450 * in such a background state, allowing you to save away any dynamic instance
451 * state in your activity into the given Bundle, to be later received in
452 * {@link #onCreate} if the activity needs to be re-created.
453 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
454 * section for more information on how the lifecycle of a process is tied
455 * to the activities it is hosting. Note that it is important to save
456 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
457 * because the latter is not part of the lifecycle callbacks, so will not
458 * be called in every situation as described in its documentation.</p>
459 *
460 * <p class="note">Be aware that these semantics will change slightly between
461 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
462 * vs. those targeting prior platforms. Starting with Honeycomb, an application
463 * is not in the killable state until its {@link #onStop} has returned. This
464 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
465 * safely called after {@link #onPause()}) and allows an application to safely
466 * wait until {@link #onStop()} to save persistent state.</p>
467 *
468 * <p class="note">For applications targeting platforms starting with
469 * {@link android.os.Build.VERSION_CODES#P} {@link #onSaveInstanceState(Bundle)}
470 * will always be called after {@link #onStop}, so an application may safely
471 * perform fragment transactions in {@link #onStop} and will be able to save
472 * persistent state later.</p>
473 *
474 * <p>For those methods that are not marked as being killable, the activity's
475 * process will not be killed by the system starting from the time the method
476 * is called and continuing after it returns. Thus an activity is in the killable
477 * state, for example, between after <code>onStop()</code> to the start of
478 * <code>onResume()</code>. Keep in mind that under extreme memory pressure the
479 * system can kill the application process at any time.</p>
480 *
481 * <a name="ConfigurationChanges"></a>
482 * <h3>Configuration Changes</h3>
483 *
484 * <p>If the configuration of the device (as defined by the
485 * {@link Configuration Resources.Configuration} class) changes,
486 * then anything displaying a user interface will need to update to match that
487 * configuration. Because Activity is the primary mechanism for interacting
488 * with the user, it includes special support for handling configuration
489 * changes.</p>
490 *
491 * <p>Unless you specify otherwise, a configuration change (such as a change
492 * in screen orientation, language, input devices, etc) will cause your
493 * current activity to be <em>destroyed</em>, going through the normal activity
494 * lifecycle process of {@link #onPause},
495 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
496 * had been in the foreground or visible to the user, once {@link #onDestroy} is
497 * called in that instance then a new instance of the activity will be
498 * created, with whatever savedInstanceState the previous instance had generated
499 * from {@link #onSaveInstanceState}.</p>
500 *
501 * <p>This is done because any application resource,
502 * including layout files, can change based on any configuration value. Thus
503 * the only safe way to handle a configuration change is to re-retrieve all
504 * resources, including layouts, drawables, and strings. Because activities
505 * must already know how to save their state and re-create themselves from
506 * that state, this is a convenient way to have an activity restart itself
507 * with a new configuration.</p>
508 *
509 * <p>In some special cases, you may want to bypass restarting of your
510 * activity based on one or more types of configuration changes. This is
511 * done with the {@link android.R.attr#configChanges android:configChanges}
512 * attribute in its manifest. For any types of configuration changes you say
513 * that you handle there, you will receive a call to your current activity's
514 * {@link #onConfigurationChanged} method instead of being restarted. If
515 * a configuration change involves any that you do not handle, however, the
516 * activity will still be restarted and {@link #onConfigurationChanged}
517 * will not be called.</p>
518 *
519 * <a name="StartingActivities"></a>
520 * <h3>Starting Activities and Getting Results</h3>
521 *
522 * <p>The {@link android.app.Activity#startActivity}
523 * method is used to start a
524 * new activity, which will be placed at the top of the activity stack. It
525 * takes a single argument, an {@link android.content.Intent Intent},
526 * which describes the activity
527 * to be executed.</p>
528 *
529 * <p>Sometimes you want to get a result back from an activity when it
530 * ends. For example, you may start an activity that lets the user pick
531 * a person in a list of contacts; when it ends, it returns the person
532 * that was selected. To do this, you call the
533 * {@link android.app.Activity#startActivityForResult(Intent, int)}
534 * version with a second integer parameter identifying the call. The result
535 * will come back through your {@link android.app.Activity#onActivityResult}
536 * method.</p>
537 *
538 * <p>When an activity exits, it can call
539 * {@link android.app.Activity#setResult(int)}
540 * to return data back to its parent. It must always supply a result code,
541 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
542 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
543 * return back an Intent containing any additional data it wants. All of this
544 * information appears back on the
545 * parent's <code>Activity.onActivityResult()</code>, along with the integer
546 * identifier it originally supplied.</p>
547 *
548 * <p>If a child activity fails for any reason (such as crashing), the parent
549 * activity will receive a result with the code RESULT_CANCELED.</p>
550 *
551 * <pre class="prettyprint">
552 * public class MyActivity extends Activity {
553 * ...
554 *
555 * static final int PICK_CONTACT_REQUEST = 0;
556 *
557 * public boolean onKeyDown(int keyCode, KeyEvent event) {
558 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
559 * // When the user center presses, let them pick a contact.
560 * startActivityForResult(
561 * new Intent(Intent.ACTION_PICK,
562 * new Uri("content://contacts")),
563 * PICK_CONTACT_REQUEST);
564 * return true;
565 * }
566 * return false;
567 * }
568 *
569 * protected void onActivityResult(int requestCode, int resultCode,
570 * Intent data) {
571 * if (requestCode == PICK_CONTACT_REQUEST) {
572 * if (resultCode == RESULT_OK) {
573 * // A contact was picked. Here we will just display it
574 * // to the user.
575 * startActivity(new Intent(Intent.ACTION_VIEW, data));
576 * }
577 * }
578 * }
579 * }
580 * </pre>
581 *
582 * <a name="SavingPersistentState"></a>
583 * <h3>Saving Persistent State</h3>
584 *
585 * <p>There are generally two kinds of persistent state that an activity
586 * will deal with: shared document-like data (typically stored in a SQLite
587 * database using a {@linkplain android.content.ContentProvider content provider})
588 * and internal state such as user preferences.</p>
589 *
590 * <p>For content provider data, we suggest that activities use an
591 * "edit in place" user model. That is, any edits a user makes are effectively
592 * made immediately without requiring an additional confirmation step.
593 * Supporting this model is generally a simple matter of following two rules:</p>
594 *
595 * <ul>
596 * <li> <p>When creating a new document, the backing database entry or file for
597 * it is created immediately. For example, if the user chooses to write
598 * a new email, a new entry for that email is created as soon as they
599 * start entering data, so that if they go to any other activity after
600 * that point this email will now appear in the list of drafts.</p>
601 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
602 * commit to the backing content provider or file any changes the user
603 * has made. This ensures that those changes will be seen by any other
604 * activity that is about to run. You will probably want to commit
605 * your data even more aggressively at key times during your
606 * activity's lifecycle: for example before starting a new
607 * activity, before finishing your own activity, when the user
608 * switches between input fields, etc.</p>
609 * </ul>
610 *
611 * <p>This model is designed to prevent data loss when a user is navigating
612 * between activities, and allows the system to safely kill an activity (because
613 * system resources are needed somewhere else) at any time after it has been
614 * stopped (or paused on platform versions before {@link android.os.Build.VERSION_CODES#HONEYCOMB}).
615 * Note this implies that the user pressing BACK from your activity does <em>not</em>
616 * mean "cancel" -- it means to leave the activity with its current contents
617 * saved away. Canceling edits in an activity must be provided through
618 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
619 *
620 * <p>See the {@linkplain android.content.ContentProvider content package} for
621 * more information about content providers. These are a key aspect of how
622 * different activities invoke and propagate data between themselves.</p>
623 *
624 * <p>The Activity class also provides an API for managing internal persistent state
625 * associated with an activity. This can be used, for example, to remember
626 * the user's preferred initial display in a calendar (day view or week view)
627 * or the user's default home page in a web browser.</p>
628 *
629 * <p>Activity persistent state is managed
630 * with the method {@link #getPreferences},
631 * allowing you to retrieve and
632 * modify a set of name/value pairs associated with the activity. To use
633 * preferences that are shared across multiple application components
634 * (activities, receivers, services, providers), you can use the underlying
635 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
636 * to retrieve a preferences
637 * object stored under a specific name.
638 * (Note that it is not possible to share settings data across application
639 * packages -- for that you will need a content provider.)</p>
640 *
641 * <p>Here is an excerpt from a calendar activity that stores the user's
642 * preferred view mode in its persistent settings:</p>
643 *
644 * <pre class="prettyprint">
645 * public class CalendarActivity extends Activity {
646 * ...
647 *
648 * static final int DAY_VIEW_MODE = 0;
649 * static final int WEEK_VIEW_MODE = 1;
650 *
651 * private SharedPreferences mPrefs;
652 * private int mCurViewMode;
653 *
654 * protected void onCreate(Bundle savedInstanceState) {
655 * super.onCreate(savedInstanceState);
656 *
657 * mPrefs = getSharedPreferences(getLocalClassName(), MODE_PRIVATE);
658 * mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
659 * }
660 *
661 * protected void onPause() {
662 * super.onPause();
663 *
664 * SharedPreferences.Editor ed = mPrefs.edit();
665 * ed.putInt("view_mode", mCurViewMode);
666 * ed.commit();
667 * }
668 * }
669 * </pre>
670 *
671 * <a name="Permissions"></a>
672 * <h3>Permissions</h3>
673 *
674 * <p>The ability to start a particular Activity can be enforced when it is
675 * declared in its
676 * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
677 * tag. By doing so, other applications will need to declare a corresponding
678 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
679 * element in their own manifest to be able to start that activity.
680 *
681 * <p>When starting an Activity you can set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
682 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
683 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the
684 * Activity access to the specific URIs in the Intent. Access will remain
685 * until the Activity has finished (it will remain across the hosting
686 * process being killed and other temporary destruction). As of
687 * {@link android.os.Build.VERSION_CODES#GINGERBREAD}, if the Activity
688 * was already created and a new Intent is being delivered to
689 * {@link #onNewIntent(Intent)}, any newly granted URI permissions will be added
690 * to the existing ones it holds.
691 *
692 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
693 * document for more information on permissions and security in general.
694 *
695 * <a name="ProcessLifecycle"></a>
696 * <h3>Process Lifecycle</h3>
697 *
698 * <p>The Android system attempts to keep an application process around for as
699 * long as possible, but eventually will need to remove old processes when
700 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
701 * Lifecycle</a>, the decision about which process to remove is intimately
702 * tied to the state of the user's interaction with it. In general, there
703 * are four states a process can be in based on the activities running in it,
704 * listed here in order of importance. The system will kill less important
705 * processes (the last ones) before it resorts to killing more important
706 * processes (the first ones).
707 *
708 * <ol>
709 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
710 * that the user is currently interacting with) is considered the most important.
711 * Its process will only be killed as a last resort, if it uses more memory
712 * than is available on the device. Generally at this point the device has
713 * reached a memory paging state, so this is required in order to keep the user
714 * interface responsive.
715 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
716 * but not in the foreground, such as one sitting behind a foreground dialog
717 * or next to other activities in multi-window mode)
718 * is considered extremely important and will not be killed unless that is
719 * required to keep the foreground activity running.
720 * <li> <p>A <b>background activity</b> (an activity that is not visible to
721 * the user and has been stopped) is no longer critical, so the system may
722 * safely kill its process to reclaim memory for other foreground or
723 * visible processes. If its process needs to be killed, when the user navigates
724 * back to the activity (making it visible on the screen again), its
725 * {@link #onCreate} method will be called with the savedInstanceState it had previously
726 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
727 * state as the user last left it.
728 * <li> <p>An <b>empty process</b> is one hosting no activities or other
729 * application components (such as {@link Service} or
730 * {@link android.content.BroadcastReceiver} classes). These are killed very
731 * quickly by the system as memory becomes low. For this reason, any
732 * background operation you do outside of an activity must be executed in the
733 * context of an activity BroadcastReceiver or Service to ensure that the system
734 * knows it needs to keep your process around.
735 * </ol>
736 *
737 * <p>Sometimes an Activity may need to do a long-running operation that exists
738 * independently of the activity lifecycle itself. An example may be a camera
739 * application that allows you to upload a picture to a web site. The upload
740 * may take a long time, and the application should allow the user to leave
741 * the application while it is executing. To accomplish this, your Activity
742 * should start a {@link Service} in which the upload takes place. This allows
743 * the system to properly prioritize your process (considering it to be more
744 * important than other non-visible applications) for the duration of the
745 * upload, independent of whether the original activity is paused, stopped,
746 * or finished.
747 */
748 @UiContext
749 public class Activity extends ContextThemeWrapper
750 implements LayoutInflater.Factory2,
751 Window.Callback, KeyEvent.Callback,
752 OnCreateContextMenuListener, ComponentCallbacks2,
753 Window.OnWindowDismissedCallback,
754 ContentCaptureManager.ContentCaptureClient {
755 private static final String TAG = "Activity";
756 private static final boolean DEBUG_LIFECYCLE = false;
757
758 /** Standard activity result: operation canceled. */
759 public static final int RESULT_CANCELED = 0;
760 /** Standard activity result: operation succeeded. */
761 public static final int RESULT_OK = -1;
762 /** Start of user-defined activity results. */
763 public static final int RESULT_FIRST_USER = 1;
764
765 /** @hide Task isn't finished when activity is finished */
766 public static final int DONT_FINISH_TASK_WITH_ACTIVITY = 0;
767 /**
768 * @hide Task is finished if the finishing activity is the root of the task. To preserve the
769 * past behavior the task is also removed from recents.
770 */
771 public static final int FINISH_TASK_WITH_ROOT_ACTIVITY = 1;
772 /**
773 * @hide Task is finished along with the finishing activity, but it is not removed from
774 * recents.
775 */
776 public static final int FINISH_TASK_WITH_ACTIVITY = 2;
777
778 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
779 static final String FRAGMENTS_TAG = "android:fragments";
780
781 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
782 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
783 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
784 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
785 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
786 private static final String HAS_CURENT_PERMISSIONS_REQUEST_KEY =
787 "android:hasCurrentPermissionsRequest";
788
789 private static final String REQUEST_PERMISSIONS_WHO_PREFIX = "@android:requestPermissions:";
790 private static final String KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME = "com.android.systemui";
791
792 private static final int LOG_AM_ON_CREATE_CALLED = 30057;
793 private static final int LOG_AM_ON_START_CALLED = 30059;
794 private static final int LOG_AM_ON_RESUME_CALLED = 30022;
795 private static final int LOG_AM_ON_PAUSE_CALLED = 30021;
796 private static final int LOG_AM_ON_STOP_CALLED = 30049;
797 private static final int LOG_AM_ON_RESTART_CALLED = 30058;
798 private static final int LOG_AM_ON_DESTROY_CALLED = 30060;
799 private static final int LOG_AM_ON_ACTIVITY_RESULT_CALLED = 30062;
800 private static final int LOG_AM_ON_TOP_RESUMED_GAINED_CALLED = 30064;
801 private static final int LOG_AM_ON_TOP_RESUMED_LOST_CALLED = 30065;
802 private OnBackInvokedCallback mDefaultBackCallback;
803
804 /**
805 * After {@link Build.VERSION_CODES#TIRAMISU},
806 * {@link #dump(String, FileDescriptor, PrintWriter, String[])} is not called if
807 * {@code dumpsys activity} is called with some special arguments.
808 */
809 @ChangeId
810 @EnabledSince(targetSdkVersion = Build.VERSION_CODES.TIRAMISU)
811 @VisibleForTesting
812 private static final long DUMP_IGNORES_SPECIAL_ARGS = 149254050L;
813
814 private static class ManagedDialog {
815 Dialog mDialog;
816 Bundle mArgs;
817 }
818
819 /** @hide */ public static final String DUMP_ARG_AUTOFILL = "--autofill";
820 /** @hide */ public static final String DUMP_ARG_CONTENT_CAPTURE = "--contentcapture";
821 /** @hide */ public static final String DUMP_ARG_TRANSLATION = "--translation";
822 /** @hide */ @TestApi public static final String DUMP_ARG_LIST_DUMPABLES = "--list-dumpables";
823 /** @hide */ @TestApi public static final String DUMP_ARG_DUMP_DUMPABLE = "--dump-dumpable";
824
825 private SparseArray<ManagedDialog> mManagedDialogs;
826
827 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
828 @UnsupportedAppUsage
829 private Instrumentation mInstrumentation;
830 @UnsupportedAppUsage
831 private IBinder mToken;
832 private IBinder mAssistToken;
833 private IBinder mShareableActivityToken;
834 @UnsupportedAppUsage
835 private int mIdent;
836 @UnsupportedAppUsage
837 /*package*/ String mEmbeddedID;
838 @UnsupportedAppUsage
839 private Application mApplication;
840 @UnsupportedAppUsage
841 /*package*/ Intent mIntent;
842 @UnsupportedAppUsage
843 /*package*/ String mReferrer;
844 @UnsupportedAppUsage
845 private ComponentName mComponent;
846 @UnsupportedAppUsage
847 /*package*/ ActivityInfo mActivityInfo;
848 @UnsupportedAppUsage
849 /*package*/ ActivityThread mMainThread;
850 @UnsupportedAppUsage(trackingBug = 137825207, maxTargetSdk = Build.VERSION_CODES.Q,
851 publicAlternatives = "Use {@code androidx.fragment.app.Fragment} and "
852 + "{@code androidx.fragment.app.FragmentManager} instead")
853 Activity mParent;
854 @UnsupportedAppUsage
855 boolean mCalled;
856 @UnsupportedAppUsage
857 /*package*/ boolean mResumed;
858 @UnsupportedAppUsage
859 /*package*/ boolean mStopped;
860 @UnsupportedAppUsage
861 boolean mFinished;
862 boolean mStartedActivity;
863 @UnsupportedAppUsage
864 private boolean mDestroyed;
865 private boolean mDoReportFullyDrawn = true;
866 private boolean mRestoredFromBundle;
867
868 /** {@code true} if the activity lifecycle is in a state which supports picture-in-picture.
869 * This only affects the client-side exception, the actual state check still happens in AMS. */
870 private boolean mCanEnterPictureInPicture = false;
871 /** true if the activity is being destroyed in order to recreate it with a new configuration */
872 /*package*/ boolean mChangingConfigurations = false;
873 @UnsupportedAppUsage
874 /*package*/ int mConfigChangeFlags;
875 @UnsupportedAppUsage
876 /*package*/ Configuration mCurrentConfig = Configuration.EMPTY;
877 private SearchManager mSearchManager;
878 private MenuInflater mMenuInflater;
879
880 /** The content capture manager. Access via {@link #getContentCaptureManager()}. */
881 @Nullable private ContentCaptureManager mContentCaptureManager;
882
883 private final ArrayList<Application.ActivityLifecycleCallbacks> mActivityLifecycleCallbacks =
884 new ArrayList<Application.ActivityLifecycleCallbacks>();
885
886 static final class NonConfigurationInstances {
887 Object activity;
888 HashMap<String, Object> children;
889 FragmentManagerNonConfig fragments;
890 ArrayMap<String, LoaderManager> loaders;
891 VoiceInteractor voiceInteractor;
892 }
893 @UnsupportedAppUsage
894 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
895
896 @UnsupportedAppUsage
897 private Window mWindow;
898
899 @UnsupportedAppUsage
900 private WindowManager mWindowManager;
901 /*package*/ View mDecor = null;
902 @UnsupportedAppUsage
903 /*package*/ boolean mWindowAdded = false;
904 /*package*/ boolean mVisibleFromServer = false;
905 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
906 /*package*/ boolean mVisibleFromClient = true;
907 /*package*/ ActionBar mActionBar = null;
908 private boolean mEnableDefaultActionBarUp;
909
910 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
911 VoiceInteractor mVoiceInteractor;
912
913 @UnsupportedAppUsage
914 private CharSequence mTitle;
915 private int mTitleColor = 0;
916
917 // we must have a handler before the FragmentController is constructed
918 @UnsupportedAppUsage
919 final Handler mHandler = new Handler();
920 @UnsupportedAppUsage
921 final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
922
923 /** The options for scene transition. */
924 ActivityOptions mPendingOptions;
925
926 /** Whether this activity was launched from a bubble. **/
927 boolean mLaunchedFromBubble;
928
929 private static final class ManagedCursor {
930 ManagedCursor(Cursor cursor) {
931 mCursor = cursor;
932 mReleased = false;
933 mUpdated = false;
934 }
935
936 private final Cursor mCursor;
937 private boolean mReleased;
938 private boolean mUpdated;
939 }
940
941 @GuardedBy("mManagedCursors")
942 private final ArrayList<ManagedCursor> mManagedCursors = new ArrayList<>();
943
944 @GuardedBy("this")
945 @UnsupportedAppUsage
946 int mResultCode = RESULT_CANCELED;
947 @GuardedBy("this")
948 @UnsupportedAppUsage
949 Intent mResultData = null;
950
951 private TranslucentConversionListener mTranslucentCallback;
952 private boolean mChangeCanvasToTranslucent;
953
954 private SearchEvent mSearchEvent;
955
956 private boolean mTitleReady = false;
957 private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
958
959 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
960 private SpannableStringBuilder mDefaultKeySsb = null;
961
962 private ActivityManager.TaskDescription mTaskDescription =
963 new ActivityManager.TaskDescription();
964
965 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
966
967 @SuppressWarnings("unused")
968 private final Object mInstanceTracker = StrictMode.trackActivity(this);
969
970 private Thread mUiThread;
971
972 @UnsupportedAppUsage
973 ActivityTransitionState mActivityTransitionState = new ActivityTransitionState();
974 SharedElementCallback mEnterTransitionListener = SharedElementCallback.NULL_CALLBACK;
975 SharedElementCallback mExitTransitionListener = SharedElementCallback.NULL_CALLBACK;
976
977 private boolean mHasCurrentPermissionsRequest;
978
979 /** The autofill client controller. Always access via {@link #getAutofillClientController()}. */
980 private AutofillClientController mAutofillClientController;
981
982 /** @hide */
983 boolean mEnterAnimationComplete;
984
985 private boolean mIsInMultiWindowMode;
986 /** @hide */
987 boolean mIsInPictureInPictureMode;
988
989 private boolean mShouldDockBigOverlays;
990
991 private UiTranslationController mUiTranslationController;
992
993 private SplashScreen mSplashScreen;
994
995 @Nullable
996 private DumpableContainerImpl mDumpableContainer;
997
998 private ComponentCallbacksController mCallbacksController;
999
1000 private final WindowControllerCallback mWindowControllerCallback =
1001 new WindowControllerCallback() {
1002 /**
1003 * Moves the activity between {@link WindowConfiguration#WINDOWING_MODE_FREEFORM} windowing
1004 * mode and {@link WindowConfiguration#WINDOWING_MODE_FULLSCREEN}.
1005 *
1006 * @hide
1007 */
1008 @Override
1009 public void toggleFreeformWindowingMode() {
1010 ActivityClient.getInstance().toggleFreeformWindowingMode(mToken);
1011 }
1012
1013 /**
1014 * Puts the activity in picture-in-picture mode if the activity supports.
1015 * @see android.R.attr#supportsPictureInPicture
1016 * @hide
1017 */
1018 @Override
1019 public void enterPictureInPictureModeIfPossible() {
1020 if (mActivityInfo.supportsPictureInPicture()) {
1021 enterPictureInPictureMode();
1022 }
1023 }
1024
1025 @Override
1026 public boolean isTaskRoot() {
1027 return ActivityClient.getInstance().getTaskForActivity(
1028 mToken, true /* onlyRoot */) >= 0;
1029 }
1030
1031 /**
1032 * Update the forced status bar color.
1033 * @hide
1034 */
1035 @Override
1036 public void updateStatusBarColor(int color) {
1037 mTaskDescription.setStatusBarColor(color);
1038 setTaskDescription(mTaskDescription);
1039 }
1040
1041 /**
1042 * Update the forced navigation bar color.
1043 * @hide
1044 */
1045 @Override
1046 public void updateNavigationBarColor(int color) {
1047 mTaskDescription.setNavigationBarColor(color);
1048 setTaskDescription(mTaskDescription);
1049 }
1050
1051 };
1052
1053 private static native String getDlWarning();
1054
1055 /** Return the intent that started this activity. */
1056 public Intent getIntent() {
1057 return mIntent;
1058 }
1059
1060 /**
1061 * Change the intent returned by {@link #getIntent}. This holds a
1062 * reference to the given intent; it does not copy it. Often used in
1063 * conjunction with {@link #onNewIntent}.
1064 *
1065 * @param newIntent The new Intent object to return from getIntent
1066 *
1067 * @see #getIntent
1068 * @see #onNewIntent
1069 */
1070 public void setIntent(Intent newIntent) {
1071 mIntent = newIntent;
1072 }
1073
1074 /**
1075 * Sets the {@link android.content.LocusId} for this activity. The locus id
1076 * helps identify different instances of the same {@code Activity} class.
1077 * <p> For example, a locus id based on a specific conversation could be set on a
1078 * conversation app's chat {@code Activity}. The system can then use this locus id
1079 * along with app's contents to provide ranking signals in various UI surfaces
1080 * including sharing, notifications, shortcuts and so on.
1081 * <p> It is recommended to set the same locus id in the shortcut's locus id using
1082 * {@link android.content.pm.ShortcutInfo.Builder#setLocusId(android.content.LocusId)
1083 * setLocusId}
1084 * so that the system can learn appropriate ranking signals linking the activity's
1085 * locus id with the matching shortcut.
1086 *
1087 * @param locusId a unique, stable id that identifies this {@code Activity} instance. LocusId
1088 * is an opaque ID that links this Activity's state to different Android concepts:
1089 * {@link android.content.pm.ShortcutInfo.Builder#setLocusId(android.content.LocusId)
1090 * setLocusId}. LocusID is null by default or if you explicitly reset it.
1091 * @param bundle extras set or updated as part of this locus context. This may help provide
1092 * additional metadata such as URLs, conversation participants specific to this
1093 * {@code Activity}'s context. Bundle can be null if additional metadata is not needed.
1094 * Bundle should always be null for null locusId.
1095 *
1096 * @see android.view.contentcapture.ContentCaptureManager
1097 * @see android.view.contentcapture.ContentCaptureContext
1098 */
1099 public void setLocusContext(@Nullable LocusId locusId, @Nullable Bundle bundle) {
1100 try {
1101 ActivityManager.getService().setActivityLocusContext(mComponent, locusId, mToken);
1102 } catch (RemoteException re) {
1103 re.rethrowFromSystemServer();
1104 }
1105 // If locusId is not null pass it to the Content Capture.
1106 if (locusId != null) {
1107 setLocusContextToContentCapture(locusId, bundle);
1108 }
1109 }
1110
1111 /** Return the application that owns this activity. */
1112 public final Application getApplication() {
1113 return mApplication;
1114 }
1115
1116 /** Is this activity embedded inside of another activity? */
1117 public final boolean isChild() {
1118 return mParent != null;
1119 }
1120
1121 /** Return the parent activity if this view is an embedded child. */
1122 public final Activity getParent() {
1123 return mParent;
1124 }
1125
1126 /** Retrieve the window manager for showing custom windows. */
1127 public WindowManager getWindowManager() {
1128 return mWindowManager;
1129 }
1130
1131 /**
1132 * Retrieve the current {@link android.view.Window} for the activity.
1133 * This can be used to directly access parts of the Window API that
1134 * are not available through Activity/Screen.
1135 *
1136 * @return Window The current window, or null if the activity is not
1137 * visual.
1138 */
1139 public Window getWindow() {
1140 return mWindow;
1141 }
1142
1143 /**
1144 * Return the LoaderManager for this activity, creating it if needed.
1145 *
1146 * @deprecated Use {@link androidx.fragment.app.FragmentActivity#getSupportLoaderManager()}
1147 */
1148 @Deprecated
1149 public LoaderManager getLoaderManager() {
1150 return mFragments.getLoaderManager();
1151 }
1152
1153 /**
1154 * Calls {@link android.view.Window#getCurrentFocus} on the
1155 * Window of this Activity to return the currently focused view.
1156 *
1157 * @return View The current View with focus or null.
1158 *
1159 * @see #getWindow
1160 * @see android.view.Window#getCurrentFocus
1161 */
1162 @Nullable
1163 public View getCurrentFocus() {
1164 return mWindow != null ? mWindow.getCurrentFocus() : null;
1165 }
1166
1167 /**
1168 * (Creates, sets, and ) returns the content capture manager
1169 *
1170 * @return The content capture manager
1171 */
1172 @Nullable private ContentCaptureManager getContentCaptureManager() {
1173 // ContextCapture disabled for system apps
1174 if (!UserHandle.isApp(myUid())) return null;
1175 if (mContentCaptureManager == null) {
1176 mContentCaptureManager = getSystemService(ContentCaptureManager.class);
1177 }
1178 return mContentCaptureManager;
1179 }
1180
1181 /** @hide */ private static final int CONTENT_CAPTURE_START = 1;
1182 /** @hide */ private static final int CONTENT_CAPTURE_RESUME = 2;
1183 /** @hide */ private static final int CONTENT_CAPTURE_PAUSE = 3;
1184 /** @hide */ private static final int CONTENT_CAPTURE_STOP = 4;
1185
1186 /** @hide */
1187 @IntDef(prefix = { "CONTENT_CAPTURE_" }, value = {
1188 CONTENT_CAPTURE_START,
1189 CONTENT_CAPTURE_RESUME,
1190 CONTENT_CAPTURE_PAUSE,
1191 CONTENT_CAPTURE_STOP
1192 })
1193 @Retention(RetentionPolicy.SOURCE)
1194 @interface ContentCaptureNotificationType{}
1195
1196 private String getContentCaptureTypeAsString(@ContentCaptureNotificationType int type) {
1197 switch (type) {
1198 case CONTENT_CAPTURE_START:
1199 return "START";
1200 case CONTENT_CAPTURE_RESUME:
1201 return "RESUME";
1202 case CONTENT_CAPTURE_PAUSE:
1203 return "PAUSE";
1204 case CONTENT_CAPTURE_STOP:
1205 return "STOP";
1206 default:
1207 return "UNKNOW-" + type;
1208 }
1209 }
1210
1211 private void notifyContentCaptureManagerIfNeeded(@ContentCaptureNotificationType int type) {
1212 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1213 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1214 "notifyContentCapture(" + getContentCaptureTypeAsString(type) + ") for "
1215 + mComponent.toShortString());
1216 }
1217 try {
1218 final ContentCaptureManager cm = getContentCaptureManager();
1219 if (cm == null) return;
1220
1221 switch (type) {
1222 case CONTENT_CAPTURE_START:
1223 //TODO(b/111276913): decide whether the InteractionSessionId should be
1224 // saved / restored in the activity bundle - probably not
1225 final Window window = getWindow();
1226 if (window != null) {
1227 cm.updateWindowAttributes(window.getAttributes());
1228 }
1229 cm.onActivityCreated(mToken, mShareableActivityToken, getComponentName());
1230 break;
1231 case CONTENT_CAPTURE_RESUME:
1232 cm.onActivityResumed();
1233 break;
1234 case CONTENT_CAPTURE_PAUSE:
1235 cm.onActivityPaused();
1236 break;
1237 case CONTENT_CAPTURE_STOP:
1238 cm.onActivityDestroyed();
1239 break;
1240 default:
1241 Log.wtf(TAG, "Invalid @ContentCaptureNotificationType: " + type);
1242 }
1243 } finally {
1244 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1245 }
1246 }
1247
1248 private void setLocusContextToContentCapture(LocusId locusId, @Nullable Bundle bundle) {
1249 final ContentCaptureManager cm = getContentCaptureManager();
1250 if (cm == null) return;
1251
1252 ContentCaptureContext.Builder contentCaptureContextBuilder =
1253 new ContentCaptureContext.Builder(locusId);
1254 if (bundle != null) {
1255 contentCaptureContextBuilder.setExtras(bundle);
1256 }
1257 cm.getMainContentCaptureSession().setContentCaptureContext(
1258 contentCaptureContextBuilder.build());
1259 }
1260
1261 @Override
1262 protected void attachBaseContext(Context newBase) {
1263 super.attachBaseContext(newBase);
1264 if (newBase != null) {
1265 newBase.setAutofillClient(getAutofillClient());
1266 newBase.setContentCaptureOptions(getContentCaptureOptions());
1267 }
1268 }
1269
1270 /** @hide */
1271 @Override
1272 public final AutofillClient getAutofillClient() {
1273 return getAutofillClientController();
1274 }
1275
1276 private AutofillClientController getAutofillClientController() {
1277 if (mAutofillClientController == null) {
1278 mAutofillClientController = new AutofillClientController(this);
1279 }
1280 return mAutofillClientController;
1281 }
1282
1283 /** @hide */
1284 @Override
1285 public final ContentCaptureClient getContentCaptureClient() {
1286 return this;
1287 }
1288
1289 /**
1290 * Register an {@link Application.ActivityLifecycleCallbacks} instance that receives
1291 * lifecycle callbacks for only this Activity.
1292 * <p>
1293 * In relation to any
1294 * {@link Application#registerActivityLifecycleCallbacks Application registered callbacks},
1295 * the callbacks registered here will always occur nested within those callbacks. This means:
1296 * <ul>
1297 * <li>Pre events will first be sent to Application registered callbacks, then to callbacks
1298 * registered here.</li>
1299 * <li>{@link Application.ActivityLifecycleCallbacks#onActivityCreated(Activity, Bundle)},
1300 * {@link Application.ActivityLifecycleCallbacks#onActivityStarted(Activity)}, and
1301 * {@link Application.ActivityLifecycleCallbacks#onActivityResumed(Activity)} will
1302 * be sent first to Application registered callbacks, then to callbacks registered here.
1303 * For all other events, callbacks registered here will be sent first.</li>
1304 * <li>Post events will first be sent to callbacks registered here, then to
1305 * Application registered callbacks.</li>
1306 * </ul>
1307 * <p>
1308 * If multiple callbacks are registered here, they receive events in a first in (up through
1309 * {@link Application.ActivityLifecycleCallbacks#onActivityPostResumed}, last out
1310 * ordering.
1311 * <p>
1312 * It is strongly recommended to register this in the constructor of your Activity to ensure
1313 * you get all available callbacks. As this callback is associated with only this Activity,
1314 * it is not usually necessary to {@link #unregisterActivityLifecycleCallbacks unregister} it
1315 * unless you specifically do not want to receive further lifecycle callbacks.
1316 *
1317 * @param callback The callback instance to register
1318 */
1319 public void registerActivityLifecycleCallbacks(
1320 @NonNull Application.ActivityLifecycleCallbacks callback) {
1321 synchronized (mActivityLifecycleCallbacks) {
1322 mActivityLifecycleCallbacks.add(callback);
1323 }
1324 }
1325
1326 /**
1327 * Unregister an {@link Application.ActivityLifecycleCallbacks} previously registered
1328 * with {@link #registerActivityLifecycleCallbacks}. It will not receive any further
1329 * callbacks.
1330 *
1331 * @param callback The callback instance to unregister
1332 * @see #registerActivityLifecycleCallbacks
1333 */
1334 public void unregisterActivityLifecycleCallbacks(
1335 @NonNull Application.ActivityLifecycleCallbacks callback) {
1336 synchronized (mActivityLifecycleCallbacks) {
1337 mActivityLifecycleCallbacks.remove(callback);
1338 }
1339 }
1340
1341 @Override
1342 public void registerComponentCallbacks(ComponentCallbacks callback) {
1343 if (CompatChanges.isChangeEnabled(OVERRIDABLE_COMPONENT_CALLBACKS)
1344 && mCallbacksController == null) {
1345 mCallbacksController = new ComponentCallbacksController();
1346 }
1347 if (mCallbacksController != null) {
1348 mCallbacksController.registerCallbacks(callback);
1349 } else {
1350 super.registerComponentCallbacks(callback);
1351 }
1352 }
1353
1354 @Override
1355 public void unregisterComponentCallbacks(ComponentCallbacks callback) {
1356 if (mCallbacksController != null) {
1357 mCallbacksController.unregisterCallbacks(callback);
1358 } else {
1359 super.unregisterComponentCallbacks(callback);
1360 }
1361 }
1362
1363 private void dispatchActivityPreCreated(@Nullable Bundle savedInstanceState) {
1364 getApplication().dispatchActivityPreCreated(this, savedInstanceState);
1365 Object[] callbacks = collectActivityLifecycleCallbacks();
1366 if (callbacks != null) {
1367 for (int i = 0; i < callbacks.length; i++) {
1368 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreCreated(this,
1369 savedInstanceState);
1370 }
1371 }
1372 }
1373
1374 private void dispatchActivityCreated(@Nullable Bundle savedInstanceState) {
1375 getApplication().dispatchActivityCreated(this, savedInstanceState);
1376 Object[] callbacks = collectActivityLifecycleCallbacks();
1377 if (callbacks != null) {
1378 for (int i = 0; i < callbacks.length; i++) {
1379 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityCreated(this,
1380 savedInstanceState);
1381 }
1382 }
1383 }
1384
1385 private void dispatchActivityPostCreated(@Nullable Bundle savedInstanceState) {
1386 Object[] callbacks = collectActivityLifecycleCallbacks();
1387 if (callbacks != null) {
1388 for (int i = 0; i < callbacks.length; i++) {
1389 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPostCreated(this,
1390 savedInstanceState);
1391 }
1392 }
1393 getApplication().dispatchActivityPostCreated(this, savedInstanceState);
1394 }
1395
1396 private void dispatchActivityPreStarted() {
1397 getApplication().dispatchActivityPreStarted(this);
1398 Object[] callbacks = collectActivityLifecycleCallbacks();
1399 if (callbacks != null) {
1400 for (int i = 0; i < callbacks.length; i++) {
1401 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreStarted(this);
1402 }
1403 }
1404 }
1405
1406 private void dispatchActivityStarted() {
1407 getApplication().dispatchActivityStarted(this);
1408 Object[] callbacks = collectActivityLifecycleCallbacks();
1409 if (callbacks != null) {
1410 for (int i = 0; i < callbacks.length; i++) {
1411 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityStarted(this);
1412 }
1413 }
1414 }
1415
1416 private void dispatchActivityPostStarted() {
1417 Object[] callbacks = collectActivityLifecycleCallbacks();
1418 if (callbacks != null) {
1419 for (int i = 0; i < callbacks.length; i++) {
1420 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1421 .onActivityPostStarted(this);
1422 }
1423 }
1424 getApplication().dispatchActivityPostStarted(this);
1425 }
1426
1427 private void dispatchActivityPreResumed() {
1428 getApplication().dispatchActivityPreResumed(this);
1429 Object[] callbacks = collectActivityLifecycleCallbacks();
1430 if (callbacks != null) {
1431 for (int i = 0; i < callbacks.length; i++) {
1432 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreResumed(this);
1433 }
1434 }
1435 }
1436
1437 private void dispatchActivityResumed() {
1438 getApplication().dispatchActivityResumed(this);
1439 Object[] callbacks = collectActivityLifecycleCallbacks();
1440 if (callbacks != null) {
1441 for (int i = 0; i < callbacks.length; i++) {
1442 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityResumed(this);
1443 }
1444 }
1445 }
1446
1447 private void dispatchActivityPostResumed() {
1448 Object[] callbacks = collectActivityLifecycleCallbacks();
1449 if (callbacks != null) {
1450 for (int i = 0; i < callbacks.length; i++) {
1451 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPostResumed(this);
1452 }
1453 }
1454 getApplication().dispatchActivityPostResumed(this);
1455 }
1456
1457 private void dispatchActivityPrePaused() {
1458 getApplication().dispatchActivityPrePaused(this);
1459 Object[] callbacks = collectActivityLifecycleCallbacks();
1460 if (callbacks != null) {
1461 for (int i = callbacks.length - 1; i >= 0; i--) {
1462 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPrePaused(this);
1463 }
1464 }
1465 }
1466
1467 private void dispatchActivityPaused() {
1468 Object[] callbacks = collectActivityLifecycleCallbacks();
1469 if (callbacks != null) {
1470 for (int i = callbacks.length - 1; i >= 0; i--) {
1471 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPaused(this);
1472 }
1473 }
1474 getApplication().dispatchActivityPaused(this);
1475 }
1476
1477 private void dispatchActivityPostPaused() {
1478 Object[] callbacks = collectActivityLifecycleCallbacks();
1479 if (callbacks != null) {
1480 for (int i = callbacks.length - 1; i >= 0; i--) {
1481 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPostPaused(this);
1482 }
1483 }
1484 getApplication().dispatchActivityPostPaused(this);
1485 }
1486
1487 private void dispatchActivityPreStopped() {
1488 getApplication().dispatchActivityPreStopped(this);
1489 Object[] callbacks = collectActivityLifecycleCallbacks();
1490 if (callbacks != null) {
1491 for (int i = callbacks.length - 1; i >= 0; i--) {
1492 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreStopped(this);
1493 }
1494 }
1495 }
1496
1497 private void dispatchActivityStopped() {
1498 Object[] callbacks = collectActivityLifecycleCallbacks();
1499 if (callbacks != null) {
1500 for (int i = callbacks.length - 1; i >= 0; i--) {
1501 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityStopped(this);
1502 }
1503 }
1504 getApplication().dispatchActivityStopped(this);
1505 }
1506
1507 private void dispatchActivityPostStopped() {
1508 Object[] callbacks = collectActivityLifecycleCallbacks();
1509 if (callbacks != null) {
1510 for (int i = callbacks.length - 1; i >= 0; i--) {
1511 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1512 .onActivityPostStopped(this);
1513 }
1514 }
1515 getApplication().dispatchActivityPostStopped(this);
1516 }
1517
1518 private void dispatchActivityPreSaveInstanceState(@NonNull Bundle outState) {
1519 getApplication().dispatchActivityPreSaveInstanceState(this, outState);
1520 Object[] callbacks = collectActivityLifecycleCallbacks();
1521 if (callbacks != null) {
1522 for (int i = callbacks.length - 1; i >= 0; i--) {
1523 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1524 .onActivityPreSaveInstanceState(this, outState);
1525 }
1526 }
1527 }
1528
1529 private void dispatchActivitySaveInstanceState(@NonNull Bundle outState) {
1530 Object[] callbacks = collectActivityLifecycleCallbacks();
1531 if (callbacks != null) {
1532 for (int i = callbacks.length - 1; i >= 0; i--) {
1533 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1534 .onActivitySaveInstanceState(this, outState);
1535 }
1536 }
1537 getApplication().dispatchActivitySaveInstanceState(this, outState);
1538 }
1539
1540 private void dispatchActivityPostSaveInstanceState(@NonNull Bundle outState) {
1541 Object[] callbacks = collectActivityLifecycleCallbacks();
1542 if (callbacks != null) {
1543 for (int i = callbacks.length - 1; i >= 0; i--) {
1544 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1545 .onActivityPostSaveInstanceState(this, outState);
1546 }
1547 }
1548 getApplication().dispatchActivityPostSaveInstanceState(this, outState);
1549 }
1550
1551 private void dispatchActivityPreDestroyed() {
1552 getApplication().dispatchActivityPreDestroyed(this);
1553 Object[] callbacks = collectActivityLifecycleCallbacks();
1554 if (callbacks != null) {
1555 for (int i = callbacks.length - 1; i >= 0; i--) {
1556 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1557 .onActivityPreDestroyed(this);
1558 }
1559 }
1560 }
1561
1562 private void dispatchActivityDestroyed() {
1563 Object[] callbacks = collectActivityLifecycleCallbacks();
1564 if (callbacks != null) {
1565 for (int i = callbacks.length - 1; i >= 0; i--) {
1566 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityDestroyed(this);
1567 }
1568 }
1569 getApplication().dispatchActivityDestroyed(this);
1570 }
1571
1572 private void dispatchActivityPostDestroyed() {
1573 Object[] callbacks = collectActivityLifecycleCallbacks();
1574 if (callbacks != null) {
1575 for (int i = callbacks.length - 1; i >= 0; i--) {
1576 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1577 .onActivityPostDestroyed(this);
1578 }
1579 }
1580 getApplication().dispatchActivityPostDestroyed(this);
1581 }
1582
1583 private void dispatchActivityConfigurationChanged() {
1584 // In case the new config comes before mApplication is assigned.
1585 if (getApplication() != null) {
1586 getApplication().dispatchActivityConfigurationChanged(this);
1587 }
1588 Object[] callbacks = collectActivityLifecycleCallbacks();
1589 if (callbacks != null) {
1590 for (int i = 0; i < callbacks.length; i++) {
1591 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1592 .onActivityConfigurationChanged(this);
1593 }
1594 }
1595 }
1596
1597 private Object[] collectActivityLifecycleCallbacks() {
1598 Object[] callbacks = null;
1599 synchronized (mActivityLifecycleCallbacks) {
1600 if (mActivityLifecycleCallbacks.size() > 0) {
1601 callbacks = mActivityLifecycleCallbacks.toArray();
1602 }
1603 }
1604 return callbacks;
1605 }
1606
1607 private void notifyVoiceInteractionManagerServiceActivityEvent(
1608 @VoiceInteractionSession.VoiceInteractionActivityEventType int type) {
1609
1610 final IVoiceInteractionManagerService service =
1611 IVoiceInteractionManagerService.Stub.asInterface(
1612 ServiceManager.getService(Context.VOICE_INTERACTION_MANAGER_SERVICE));
1613 if (service == null) {
1614 Log.w(TAG, "notifyVoiceInteractionManagerServiceActivityEvent: Can not get "
1615 + "VoiceInteractionManagerService");
1616 return;
1617 }
1618
1619 try {
1620 service.notifyActivityEventChanged(mToken, type);
1621 } catch (RemoteException e) {
1622 // Empty
1623 }
1624 }
1625
1626 /**
1627 * Called when the activity is starting. This is where most initialization
1628 * should go: calling {@link #setContentView(int)} to inflate the
1629 * activity's UI, using {@link #findViewById} to programmatically interact
1630 * with widgets in the UI, calling
1631 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
1632 * cursors for data being displayed, etc.
1633 *
1634 * <p>You can call {@link #finish} from within this function, in
1635 * which case onDestroy() will be immediately called after {@link #onCreate} without any of the
1636 * rest of the activity lifecycle ({@link #onStart}, {@link #onResume}, {@link #onPause}, etc)
1637 * executing.
1638 *
1639 * <p><em>Derived classes must call through to the super class's
1640 * implementation of this method. If they do not, an exception will be
1641 * thrown.</em></p>
1642 *
1643 * @param savedInstanceState If the activity is being re-initialized after
1644 * previously being shut down then this Bundle contains the data it most
1645 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
1646 *
1647 * @see #onStart
1648 * @see #onSaveInstanceState
1649 * @see #onRestoreInstanceState
1650 * @see #onPostCreate
1651 */
1652 @MainThread
1653 @CallSuper
1654 protected void onCreate(@Nullable Bundle savedInstanceState) {
1655 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
1656
1657 if (mLastNonConfigurationInstances != null) {
1658 mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
1659 }
1660 if (mActivityInfo.parentActivityName != null) {
1661 if (mActionBar == null) {
1662 mEnableDefaultActionBarUp = true;
1663 } else {
1664 mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
1665 }
1666 }
1667
1668 if (savedInstanceState != null) {
1669 getAutofillClientController().onActivityCreated(savedInstanceState);
1670
1671 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
1672 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
1673 ? mLastNonConfigurationInstances.fragments : null);
1674 }
1675 mFragments.dispatchCreate();
1676 dispatchActivityCreated(savedInstanceState);
1677 if (mVoiceInteractor != null) {
1678 mVoiceInteractor.attachActivity(this);
1679 }
1680 mRestoredFromBundle = savedInstanceState != null;
1681 mCalled = true;
1682
1683 boolean aheadOfTimeBack = WindowOnBackInvokedDispatcher
1684 .isOnBackInvokedCallbackEnabled(this);
1685 if (aheadOfTimeBack) {
1686 // Add onBackPressed as default back behavior.
1687 mDefaultBackCallback = this::onBackInvoked;
1688 getOnBackInvokedDispatcher().registerSystemOnBackInvokedCallback(mDefaultBackCallback);
1689 }
1690 }
1691
1692 /**
1693 * Get the interface that activity use to talk to the splash screen.
1694 * @see SplashScreen
1695 */
1696 public final @NonNull SplashScreen getSplashScreen() {
1697 return getOrCreateSplashScreen();
1698 }
1699
1700 private SplashScreen getOrCreateSplashScreen() {
1701 synchronized (this) {
1702 if (mSplashScreen == null) {
1703 mSplashScreen = new SplashScreen.SplashScreenImpl(this);
1704 }
1705 return mSplashScreen;
1706 }
1707 }
1708
1709 /**
1710 * Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
1711 * the attribute {@link android.R.attr#persistableMode} set to
1712 * <code>persistAcrossReboots</code>.
1713 *
1714 * @param savedInstanceState if the activity is being re-initialized after
1715 * previously being shut down then this Bundle contains the data it most
1716 * recently supplied in {@link #onSaveInstanceState}.
1717 * <b><i>Note: Otherwise it is null.</i></b>
1718 * @param persistentState if the activity is being re-initialized after
1719 * previously being shut down or powered off then this Bundle contains the data it most
1720 * recently supplied to outPersistentState in {@link #onSaveInstanceState}.
1721 * <b><i>Note: Otherwise it is null.</i></b>
1722 *
1723 * @see #onCreate(android.os.Bundle)
1724 * @see #onStart
1725 * @see #onSaveInstanceState
1726 * @see #onRestoreInstanceState
1727 * @see #onPostCreate
1728 */
1729 public void onCreate(@Nullable Bundle savedInstanceState,
1730 @Nullable PersistableBundle persistentState) {
1731 onCreate(savedInstanceState);
1732 }
1733
1734 /**
1735 * The hook for {@link ActivityThread} to restore the state of this activity.
1736 *
1737 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
1738 * {@link #restoreManagedDialogs(android.os.Bundle)}.
1739 *
1740 * @param savedInstanceState contains the saved state
1741 */
1742 final void performRestoreInstanceState(@NonNull Bundle savedInstanceState) {
1743 onRestoreInstanceState(savedInstanceState);
1744 restoreManagedDialogs(savedInstanceState);
1745 }
1746
1747 /**
1748 * The hook for {@link ActivityThread} to restore the state of this activity.
1749 *
1750 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
1751 * {@link #restoreManagedDialogs(android.os.Bundle)}.
1752 *
1753 * @param savedInstanceState contains the saved state
1754 * @param persistentState contains the persistable saved state
1755 */
1756 final void performRestoreInstanceState(@Nullable Bundle savedInstanceState,
1757 @Nullable PersistableBundle persistentState) {
1758 onRestoreInstanceState(savedInstanceState, persistentState);
1759 if (savedInstanceState != null) {
1760 restoreManagedDialogs(savedInstanceState);
1761 }
1762 }
1763
1764 /**
1765 * This method is called after {@link #onStart} when the activity is
1766 * being re-initialized from a previously saved state, given here in
1767 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
1768 * to restore their state, but it is sometimes convenient to do it here
1769 * after all of the initialization has been done or to allow subclasses to
1770 * decide whether to use your default implementation. The default
1771 * implementation of this method performs a restore of any view state that
1772 * had previously been frozen by {@link #onSaveInstanceState}.
1773 *
1774 * <p>This method is called between {@link #onStart} and
1775 * {@link #onPostCreate}. This method is called only when recreating
1776 * an activity; the method isn't invoked if {@link #onStart} is called for
1777 * any other reason.</p>
1778 *
1779 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1780 *
1781 * @see #onCreate
1782 * @see #onPostCreate
1783 * @see #onResume
1784 * @see #onSaveInstanceState
1785 */
1786 protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
1787 if (mWindow != null) {
1788 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
1789 if (windowState != null) {
1790 mWindow.restoreHierarchyState(windowState);
1791 }
1792 }
1793 }
1794
1795 /**
1796 * This is the same as {@link #onRestoreInstanceState(Bundle)} but is called for activities
1797 * created with the attribute {@link android.R.attr#persistableMode} set to
1798 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1799 * came from the restored PersistableBundle first
1800 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1801 *
1802 * <p>This method is called between {@link #onStart} and
1803 * {@link #onPostCreate}.
1804 *
1805 * <p>If this method is called {@link #onRestoreInstanceState(Bundle)} will not be called.
1806 *
1807 * <p>At least one of {@code savedInstanceState} or {@code persistentState} will not be null.
1808 *
1809 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}
1810 * or null.
1811 * @param persistentState the data most recently supplied in {@link #onSaveInstanceState}
1812 * or null.
1813 *
1814 * @see #onRestoreInstanceState(Bundle)
1815 * @see #onCreate
1816 * @see #onPostCreate
1817 * @see #onResume
1818 * @see #onSaveInstanceState
1819 */
1820 public void onRestoreInstanceState(@Nullable Bundle savedInstanceState,
1821 @Nullable PersistableBundle persistentState) {
1822 if (savedInstanceState != null) {
1823 onRestoreInstanceState(savedInstanceState);
1824 }
1825 }
1826
1827 /**
1828 * Restore the state of any saved managed dialogs.
1829 *
1830 * @param savedInstanceState The bundle to restore from.
1831 */
1832 private void restoreManagedDialogs(Bundle savedInstanceState) {
1833 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
1834 if (b == null) {
1835 return;
1836 }
1837
1838 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
1839 final int numDialogs = ids.length;
1840 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
1841 for (int i = 0; i < numDialogs; i++) {
1842 final Integer dialogId = ids[i];
1843 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
1844 if (dialogState != null) {
1845 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
1846 // so tell createDialog() not to do it, otherwise we get an exception
1847 final ManagedDialog md = new ManagedDialog();
1848 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
1849 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
1850 if (md.mDialog != null) {
1851 mManagedDialogs.put(dialogId, md);
1852 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
1853 md.mDialog.onRestoreInstanceState(dialogState);
1854 }
1855 }
1856 }
1857 }
1858
1859 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
1860 final Dialog dialog = onCreateDialog(dialogId, args);
1861 if (dialog == null) {
1862 return null;
1863 }
1864 dialog.dispatchOnCreate(state);
1865 return dialog;
1866 }
1867
1868 private static String savedDialogKeyFor(int key) {
1869 return SAVED_DIALOG_KEY_PREFIX + key;
1870 }
1871
1872 private static String savedDialogArgsKeyFor(int key) {
1873 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
1874 }
1875
1876 /**
1877 * Called when activity start-up is complete (after {@link #onStart}
1878 * and {@link #onRestoreInstanceState} have been called). Applications will
1879 * generally not implement this method; it is intended for system
1880 * classes to do final initialization after application code has run.
1881 *
1882 * <p><em>Derived classes must call through to the super class's
1883 * implementation of this method. If they do not, an exception will be
1884 * thrown.</em></p>
1885 *
1886 * @param savedInstanceState If the activity is being re-initialized after
1887 * previously being shut down then this Bundle contains the data it most
1888 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
1889 * @see #onCreate
1890 */
1891 @CallSuper
1892 protected void onPostCreate(@Nullable Bundle savedInstanceState) {
1893 if (!isChild()) {
1894 mTitleReady = true;
1895 onTitleChanged(getTitle(), getTitleColor());
1896 }
1897
1898 mCalled = true;
1899
1900 notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_START);
1901
1902 notifyVoiceInteractionManagerServiceActivityEvent(
1903 VoiceInteractionSession.VOICE_INTERACTION_ACTIVITY_EVENT_START);
1904 }
1905
1906 /**
1907 * This is the same as {@link #onPostCreate(Bundle)} but is called for activities
1908 * created with the attribute {@link android.R.attr#persistableMode} set to
1909 * <code>persistAcrossReboots</code>.
1910 *
1911 * @param savedInstanceState The data most recently supplied in {@link #onSaveInstanceState}
1912 * @param persistentState The data caming from the PersistableBundle first
1913 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1914 *
1915 * @see #onCreate
1916 */
1917 public void onPostCreate(@Nullable Bundle savedInstanceState,
1918 @Nullable PersistableBundle persistentState) {
1919 onPostCreate(savedInstanceState);
1920 }
1921
1922 /**
1923 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
1924 * the activity had been stopped, but is now again being displayed to the
1925 * user. It will usually be followed by {@link #onResume}. This is a good place to begin
1926 * drawing visual elements, running animations, etc.
1927 *
1928 * <p>You can call {@link #finish} from within this function, in
1929 * which case {@link #onStop} will be immediately called after {@link #onStart} without the
1930 * lifecycle transitions in-between ({@link #onResume}, {@link #onPause}, etc) executing.
1931 *
1932 * <p><em>Derived classes must call through to the super class's
1933 * implementation of this method. If they do not, an exception will be
1934 * thrown.</em></p>
1935 *
1936 * @see #onCreate
1937 * @see #onStop
1938 * @see #onResume
1939 */
1940 @CallSuper
1941 protected void onStart() {
1942 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
1943 mCalled = true;
1944
1945 mFragments.doLoaderStart();
1946
1947 dispatchActivityStarted();
1948
1949 getAutofillClientController().onActivityStarted();
1950 }
1951
1952 /**
1953 * Called after {@link #onStop} when the current activity is being
1954 * re-displayed to the user (the user has navigated back to it). It will
1955 * be followed by {@link #onStart} and then {@link #onResume}.
1956 *
1957 * <p>For activities that are using raw {@link Cursor} objects (instead of
1958 * creating them through
1959 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1960 * this is usually the place
1961 * where the cursor should be requeried (because you had deactivated it in
1962 * {@link #onStop}.
1963 *
1964 * <p><em>Derived classes must call through to the super class's
1965 * implementation of this method. If they do not, an exception will be
1966 * thrown.</em></p>
1967 *
1968 * @see #onStop
1969 * @see #onStart
1970 * @see #onResume
1971 */
1972 @CallSuper
1973 protected void onRestart() {
1974 mCalled = true;
1975 }
1976
1977 /**
1978 * Called when an {@link #onResume} is coming up, prior to other pre-resume callbacks
1979 * such as {@link #onNewIntent} and {@link #onActivityResult}. This is primarily intended
1980 * to give the activity a hint that its state is no longer saved -- it will generally
1981 * be called after {@link #onSaveInstanceState} and prior to the activity being
1982 * resumed/started again.
1983 *
1984 * @deprecated starting with {@link android.os.Build.VERSION_CODES#P} onSaveInstanceState is
1985 * called after {@link #onStop}, so this hint isn't accurate anymore: you should consider your
1986 * state not saved in between {@code onStart} and {@code onStop} callbacks inclusively.
1987 */
1988 @Deprecated
1989 public void onStateNotSaved() {
1990 }
1991
1992 /**
1993 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or {@link #onPause}. This
1994 * is usually a hint for your activity to start interacting with the user, which is a good
1995 * indicator that the activity became active and ready to receive input. This sometimes could
1996 * also be a transit state toward another resting state. For instance, an activity may be
1997 * relaunched to {@link #onPause} due to configuration changes and the activity was visible,
1998 * but wasn’t the top-most activity of an activity task. {@link #onResume} is guaranteed to be
1999 * called before {@link #onPause} in this case which honors the activity lifecycle policy and
2000 * the activity eventually rests in {@link #onPause}.
2001 *
2002 * <p>On platform versions prior to {@link android.os.Build.VERSION_CODES#Q} this is also a good
2003 * place to try to open exclusive-access devices or to get access to singleton resources.
2004 * Starting with {@link android.os.Build.VERSION_CODES#Q} there can be multiple resumed
2005 * activities in the system simultaneously, so {@link #onTopResumedActivityChanged(boolean)}
2006 * should be used for that purpose instead.
2007 *
2008 * <p><em>Derived classes must call through to the super class's
2009 * implementation of this method. If they do not, an exception will be
2010 * thrown.</em></p>
2011 *
2012 * @see #onRestoreInstanceState
2013 * @see #onRestart
2014 * @see #onPostResume
2015 * @see #onPause
2016 * @see #onTopResumedActivityChanged(boolean)
2017 */
2018 @CallSuper
2019 protected void onResume() {
2020 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this);
2021 dispatchActivityResumed();
2022 mActivityTransitionState.onResume(this);
2023 getAutofillClientController().onActivityResumed();
2024
2025 notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_RESUME);
2026
2027 mCalled = true;
2028 }
2029
2030 /**
2031 * Called when activity resume is complete (after {@link #onResume} has
2032 * been called). Applications will generally not implement this method;
2033 * it is intended for system classes to do final setup after application
2034 * resume code has run.
2035 *
2036 * <p><em>Derived classes must call through to the super class's
2037 * implementation of this method. If they do not, an exception will be
2038 * thrown.</em></p>
2039 *
2040 * @see #onResume
2041 */
2042 @CallSuper
2043 protected void onPostResume() {
2044 final Window win = getWindow();
2045 if (win != null) win.makeActive();
2046 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
2047
2048 // Because the test case "com.android.launcher3.jank.BinderTests#testPressHome" doesn't
2049 // allow any binder call in onResume, we call this method in onPostResume.
2050 notifyVoiceInteractionManagerServiceActivityEvent(
2051 VoiceInteractionSession.VOICE_INTERACTION_ACTIVITY_EVENT_RESUME);
2052
2053 mCalled = true;
2054 }
2055
2056 /**
2057 * Called when activity gets or loses the top resumed position in the system.
2058 *
2059 * <p>Starting with {@link android.os.Build.VERSION_CODES#Q} multiple activities can be resumed
2060 * at the same time in multi-window and multi-display modes. This callback should be used
2061 * instead of {@link #onResume()} as an indication that the activity can try to open
2062 * exclusive-access devices like camera.</p>
2063 *
2064 * <p>It will always be delivered after the activity was resumed and before it is paused. In
2065 * some cases it might be skipped and activity can go straight from {@link #onResume()} to
2066 * {@link #onPause()} without receiving the top resumed state.</p>
2067 *
2068 * @param isTopResumedActivity {@code true} if it's the topmost resumed activity in the system,
2069 * {@code false} otherwise. A call with this as {@code true} will
2070 * always be followed by another one with {@code false}.
2071 *
2072 * @see #onResume()
2073 * @see #onPause()
2074 * @see #onWindowFocusChanged(boolean)
2075 */
2076 public void onTopResumedActivityChanged(boolean isTopResumedActivity) {
2077 }
2078
2079 final void performTopResumedActivityChanged(boolean isTopResumedActivity, String reason) {
2080 onTopResumedActivityChanged(isTopResumedActivity);
2081
2082 if (isTopResumedActivity) {
2083 EventLogTags.writeWmOnTopResumedGainedCalled(mIdent, getComponentName().getClassName(),
2084 reason);
2085 } else {
2086 EventLogTags.writeWmOnTopResumedLostCalled(mIdent, getComponentName().getClassName(),
2087 reason);
2088 }
2089 }
2090
2091 void setVoiceInteractor(IVoiceInteractor voiceInteractor) {
2092 if (mVoiceInteractor != null) {
2093 final Request[] requests = mVoiceInteractor.getActiveRequests();
2094 if (requests != null) {
2095 for (Request activeRequest : mVoiceInteractor.getActiveRequests()) {
2096 activeRequest.cancel();
2097 activeRequest.clear();
2098 }
2099 }
2100 }
2101 if (voiceInteractor == null) {
2102 mVoiceInteractor = null;
2103 } else {
2104 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
2105 Looper.myLooper());
2106 }
2107 }
2108
2109 /**
2110 * Returns the next autofill ID that is unique in the activity
2111 *
2112 * <p>All IDs will be bigger than {@link View#LAST_APP_AUTOFILL_ID}. All IDs returned
2113 * will be unique.
2114 *
2115 * {@hide}
2116 */
2117 @Override
2118 public int getNextAutofillId() {
2119 return getAutofillClientController().getNextAutofillId();
2120 }
2121
2122 /**
2123 * Check whether this activity is running as part of a voice interaction with the user.
2124 * If true, it should perform its interaction with the user through the
2125 * {@link VoiceInteractor} returned by {@link #getVoiceInteractor}.
2126 */
2127 public boolean isVoiceInteraction() {
2128 return mVoiceInteractor != null;
2129 }
2130
2131 /**
2132 * Like {@link #isVoiceInteraction}, but only returns {@code true} if this is also the root
2133 * of a voice interaction. That is, returns {@code true} if this activity was directly
2134 * started by the voice interaction service as the initiation of a voice interaction.
2135 * Otherwise, for example if it was started by another activity while under voice
2136 * interaction, returns {@code false}.
2137 * If the activity {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode} is
2138 * {@code singleTask}, it forces the activity to launch in a new task, separate from the one
2139 * that started it. Therefore, there is no longer a relationship between them, and
2140 * {@link #isVoiceInteractionRoot()} return {@code false} in this case.
2141 */
2142 public boolean isVoiceInteractionRoot() {
2143 return mVoiceInteractor != null
2144 && ActivityClient.getInstance().isRootVoiceInteraction(mToken);
2145 }
2146
2147 /**
2148 * Retrieve the active {@link VoiceInteractor} that the user is going through to
2149 * interact with this activity.
2150 */
2151 public VoiceInteractor getVoiceInteractor() {
2152 return mVoiceInteractor;
2153 }
2154
2155 /**
2156 * Queries whether the currently enabled voice interaction service supports returning
2157 * a voice interactor for use by the activity. This is valid only for the duration of the
2158 * activity.
2159 *
2160 * @return whether the current voice interaction service supports local voice interaction
2161 */
2162 public boolean isLocalVoiceInteractionSupported() {
2163 try {
2164 return ActivityTaskManager.getService().supportsLocalVoiceInteraction();
2165 } catch (RemoteException re) {
2166 }
2167 return false;
2168 }
2169
2170 /**
2171 * Starts a local voice interaction session. When ready,
2172 * {@link #onLocalVoiceInteractionStarted()} is called. You can pass a bundle of private options
2173 * to the registered voice interaction service.
2174 * @param privateOptions a Bundle of private arguments to the current voice interaction service
2175 */
2176 public void startLocalVoiceInteraction(Bundle privateOptions) {
2177 ActivityClient.getInstance().startLocalVoiceInteraction(mToken, privateOptions);
2178 }
2179
2180 /**
2181 * Callback to indicate that {@link #startLocalVoiceInteraction(Bundle)} has resulted in a
2182 * voice interaction session being started. You can now retrieve a voice interactor using
2183 * {@link #getVoiceInteractor()}.
2184 */
2185 public void onLocalVoiceInteractionStarted() {
2186 }
2187
2188 /**
2189 * Callback to indicate that the local voice interaction has stopped either
2190 * because it was requested through a call to {@link #stopLocalVoiceInteraction()}
2191 * or because it was canceled by the user. The previously acquired {@link VoiceInteractor}
2192 * is no longer valid after this.
2193 */
2194 public void onLocalVoiceInteractionStopped() {
2195 }
2196
2197 /**
2198 * Request to terminate the current voice interaction that was previously started
2199 * using {@link #startLocalVoiceInteraction(Bundle)}. When the interaction is
2200 * terminated, {@link #onLocalVoiceInteractionStopped()} will be called.
2201 */
2202 public void stopLocalVoiceInteraction() {
2203 ActivityClient.getInstance().stopLocalVoiceInteraction(mToken);
2204 }
2205
2206 /**
2207 * This is called for activities that set launchMode to "singleTop" in
2208 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
2209 * flag when calling {@link #startActivity}. In either case, when the
2210 * activity is re-launched while at the top of the activity stack instead
2211 * of a new instance of the activity being started, onNewIntent() will be
2212 * called on the existing instance with the Intent that was used to
2213 * re-launch it.
2214 *
2215 * <p>An activity can never receive a new intent in the resumed state. You can count on
2216 * {@link #onResume} being called after this method, though not necessarily immediately after
2217 * the completion this callback. If the activity was resumed, it will be paused and new intent
2218 * will be delivered, followed by {@link #onResume}. If the activity wasn't in the resumed
2219 * state, then new intent can be delivered immediately, with {@link #onResume()} called
2220 * sometime later when activity becomes active again.
2221 *
2222 * <p>Note that {@link #getIntent} still returns the original Intent. You
2223 * can use {@link #setIntent} to update it to this new Intent.
2224 *
2225 * @param intent The new intent that was started for the activity.
2226 *
2227 * @see #getIntent
2228 * @see #setIntent
2229 * @see #onResume
2230 */
2231 protected void onNewIntent(Intent intent) {
2232 }
2233
2234 /**
2235 * The hook for {@link ActivityThread} to save the state of this activity.
2236 *
2237 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
2238 * and {@link #saveManagedDialogs(android.os.Bundle)}.
2239 *
2240 * @param outState The bundle to save the state to.
2241 */
2242 final void performSaveInstanceState(@NonNull Bundle outState) {
2243 dispatchActivityPreSaveInstanceState(outState);
2244 onSaveInstanceState(outState);
2245 saveManagedDialogs(outState);
2246 mActivityTransitionState.saveState(outState);
2247 storeHasCurrentPermissionRequest(outState);
2248 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState);
2249 dispatchActivityPostSaveInstanceState(outState);
2250 }
2251
2252 /**
2253 * The hook for {@link ActivityThread} to save the state of this activity.
2254 *
2255 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
2256 * and {@link #saveManagedDialogs(android.os.Bundle)}.
2257 *
2258 * @param outState The bundle to save the state to.
2259 * @param outPersistentState The bundle to save persistent state to.
2260 */
2261 final void performSaveInstanceState(@NonNull Bundle outState,
2262 @NonNull PersistableBundle outPersistentState) {
2263 dispatchActivityPreSaveInstanceState(outState);
2264 onSaveInstanceState(outState, outPersistentState);
2265 saveManagedDialogs(outState);
2266 storeHasCurrentPermissionRequest(outState);
2267 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState +
2268 ", " + outPersistentState);
2269 dispatchActivityPostSaveInstanceState(outState);
2270 }
2271
2272 /**
2273 * Called to retrieve per-instance state from an activity before being killed
2274 * so that the state can be restored in {@link #onCreate} or
2275 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
2276 * will be passed to both).
2277 *
2278 * <p>This method is called before an activity may be killed so that when it
2279 * comes back some time in the future it can restore its state. For example,
2280 * if activity B is launched in front of activity A, and at some point activity
2281 * A is killed to reclaim resources, activity A will have a chance to save the
2282 * current state of its user interface via this method so that when the user
2283 * returns to activity A, the state of the user interface can be restored
2284 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
2285 *
2286 * <p>Do not confuse this method with activity lifecycle callbacks such as {@link #onPause},
2287 * which is always called when the user no longer actively interacts with an activity, or
2288 * {@link #onStop} which is called when activity becomes invisible. One example of when
2289 * {@link #onPause} and {@link #onStop} is called and not this method is when a user navigates
2290 * back from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
2291 * on B because that particular instance will never be restored,
2292 * so the system avoids calling it. An example when {@link #onPause} is called and
2293 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
2294 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
2295 * killed during the lifetime of B since the state of the user interface of
2296 * A will stay intact.
2297 *
2298 * <p>The default implementation takes care of most of the UI per-instance
2299 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
2300 * view in the hierarchy that has an id, and by saving the id of the currently
2301 * focused view (all of which is restored by the default implementation of
2302 * {@link #onRestoreInstanceState}). If you override this method to save additional
2303 * information not captured by each individual view, you will likely want to
2304 * call through to the default implementation, otherwise be prepared to save
2305 * all of the state of each view yourself.
2306 *
2307 * <p>If called, this method will occur after {@link #onStop} for applications
2308 * targeting platforms starting with {@link android.os.Build.VERSION_CODES#P}.
2309 * For applications targeting earlier platform versions this method will occur
2310 * before {@link #onStop} and there are no guarantees about whether it will
2311 * occur before or after {@link #onPause}.
2312 *
2313 * @param outState Bundle in which to place your saved state.
2314 *
2315 * @see #onCreate
2316 * @see #onRestoreInstanceState
2317 * @see #onPause
2318 */
2319 protected void onSaveInstanceState(@NonNull Bundle outState) {
2320 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
2321
2322 Parcelable p = mFragments.saveAllState();
2323 if (p != null) {
2324 outState.putParcelable(FRAGMENTS_TAG, p);
2325 }
2326 getAutofillClientController().onSaveInstanceState(outState);
2327 dispatchActivitySaveInstanceState(outState);
2328 }
2329
2330 /**
2331 * This is the same as {@link #onSaveInstanceState} but is called for activities
2332 * created with the attribute {@link android.R.attr#persistableMode} set to
2333 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
2334 * in will be saved and presented in {@link #onCreate(Bundle, PersistableBundle)}
2335 * the first time that this activity is restarted following the next device reboot.
2336 *
2337 * @param outState Bundle in which to place your saved state.
2338 * @param outPersistentState State which will be saved across reboots.
2339 *
2340 * @see #onSaveInstanceState(Bundle)
2341 * @see #onCreate
2342 * @see #onRestoreInstanceState(Bundle, PersistableBundle)
2343 * @see #onPause
2344 */
2345 public void onSaveInstanceState(@NonNull Bundle outState,
2346 @NonNull PersistableBundle outPersistentState) {
2347 onSaveInstanceState(outState);
2348 }
2349
2350 /**
2351 * Save the state of any managed dialogs.
2352 *
2353 * @param outState place to store the saved state.
2354 */
2355 @UnsupportedAppUsage
2356 private void saveManagedDialogs(Bundle outState) {
2357 if (mManagedDialogs == null) {
2358 return;
2359 }
2360
2361 final int numDialogs = mManagedDialogs.size();
2362 if (numDialogs == 0) {
2363 return;
2364 }
2365
2366 Bundle dialogState = new Bundle();
2367
2368 int[] ids = new int[mManagedDialogs.size()];
2369
2370 // save each dialog's bundle, gather the ids
2371 for (int i = 0; i < numDialogs; i++) {
2372 final int key = mManagedDialogs.keyAt(i);
2373 ids[i] = key;
2374 final ManagedDialog md = mManagedDialogs.valueAt(i);
2375 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
2376 if (md.mArgs != null) {
2377 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
2378 }
2379 }
2380
2381 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
2382 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
2383 }
2384
2385
2386 /**
2387 * Called as part of the activity lifecycle when the user no longer actively interacts with the
2388 * activity, but it is still visible on screen. The counterpart to {@link #onResume}.
2389 *
2390 * <p>When activity B is launched in front of activity A, this callback will
2391 * be invoked on A. B will not be created until A's {@link #onPause} returns,
2392 * so be sure to not do anything lengthy here.
2393 *
2394 * <p>This callback is mostly used for saving any persistent state the
2395 * activity is editing, to present a "edit in place" model to the user and
2396 * making sure nothing is lost if there are not enough resources to start
2397 * the new activity without first killing this one. This is also a good
2398 * place to stop things that consume a noticeable amount of CPU in order to
2399 * make the switch to the next activity as fast as possible.
2400 *
2401 * <p>On platform versions prior to {@link android.os.Build.VERSION_CODES#Q} this is also a good
2402 * place to try to close exclusive-access devices or to release access to singleton resources.
2403 * Starting with {@link android.os.Build.VERSION_CODES#Q} there can be multiple resumed
2404 * activities in the system at the same time, so {@link #onTopResumedActivityChanged(boolean)}
2405 * should be used for that purpose instead.
2406 *
2407 * <p>If an activity is launched on top, after receiving this call you will usually receive a
2408 * following call to {@link #onStop} (after the next activity has been resumed and displayed
2409 * above). However in some cases there will be a direct call back to {@link #onResume} without
2410 * going through the stopped state. An activity can also rest in paused state in some cases when
2411 * in multi-window mode, still visible to user.
2412 *
2413 * <p><em>Derived classes must call through to the super class's
2414 * implementation of this method. If they do not, an exception will be
2415 * thrown.</em></p>
2416 *
2417 * @see #onResume
2418 * @see #onSaveInstanceState
2419 * @see #onStop
2420 */
2421 @CallSuper
2422 protected void onPause() {
2423 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this);
2424 dispatchActivityPaused();
2425 getAutofillClientController().onActivityPaused();
2426
2427 notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_PAUSE);
2428
2429 notifyVoiceInteractionManagerServiceActivityEvent(
2430 VoiceInteractionSession.VOICE_INTERACTION_ACTIVITY_EVENT_PAUSE);
2431
2432 mCalled = true;
2433 }
2434
2435 /**
2436 * Called as part of the activity lifecycle when an activity is about to go
2437 * into the background as the result of user choice. For example, when the
2438 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
2439 * when an incoming phone call causes the in-call Activity to be automatically
2440 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
2441 * the activity being interrupted. In cases when it is invoked, this method
2442 * is called right before the activity's {@link #onPause} callback.
2443 *
2444 * <p>This callback and {@link #onUserInteraction} are intended to help
2445 * activities manage status bar notifications intelligently; specifically,
2446 * for helping activities determine the proper time to cancel a notification.
2447 *
2448 * @see #onUserInteraction()
2449 * @see android.content.Intent#FLAG_ACTIVITY_NO_USER_ACTION
2450 */
2451 protected void onUserLeaveHint() {
2452 }
2453
2454 /**
2455 * @deprecated Method doesn't do anything and will be removed in the future.
2456 */
2457 @Deprecated
2458 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
2459 return false;
2460 }
2461
2462 /**
2463 * Generate a new description for this activity. This method is called
2464 * before stopping the activity and can, if desired, return some textual
2465 * description of its current state to be displayed to the user.
2466 *
2467 * <p>The default implementation returns null, which will cause you to
2468 * inherit the description from the previous activity. If all activities
2469 * return null, generally the label of the top activity will be used as the
2470 * description.
2471 *
2472 * @return A description of what the user is doing. It should be short and
2473 * sweet (only a few words).
2474 *
2475 * @see #onSaveInstanceState
2476 * @see #onStop
2477 */
2478 @Nullable
2479 public CharSequence onCreateDescription() {
2480 return null;
2481 }
2482
2483 /**
2484 * This is called when the user is requesting an assist, to build a full
2485 * {@link Intent#ACTION_ASSIST} Intent with all of the context of the current
2486 * application. You can override this method to place into the bundle anything
2487 * you would like to appear in the {@link Intent#EXTRA_ASSIST_CONTEXT} part
2488 * of the assist Intent.
2489 *
2490 * <p>This function will be called after any global assist callbacks that had
2491 * been registered with {@link Application#registerOnProvideAssistDataListener
2492 * Application.registerOnProvideAssistDataListener}.
2493 */
2494 public void onProvideAssistData(Bundle data) {
2495 }
2496
2497 /**
2498 * This is called when the user is requesting an assist, to provide references
2499 * to content related to the current activity. Before being called, the
2500 * {@code outContent} Intent is filled with the base Intent of the activity (the Intent
2501 * returned by {@link #getIntent()}). The Intent's extras are stripped of any types
2502 * that are not valid for {@link PersistableBundle} or non-framework Parcelables, and
2503 * the flags {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} and
2504 * {@link Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION} are cleared from the Intent.
2505 *
2506 * <p>Custom implementation may adjust the content intent to better reflect the top-level
2507 * context of the activity, and fill in its ClipData with additional content of
2508 * interest that the user is currently viewing. For example, an image gallery application
2509 * that has launched in to an activity allowing the user to swipe through pictures should
2510 * modify the intent to reference the current image they are looking it; such an
2511 * application when showing a list of pictures should add a ClipData that has
2512 * references to all of the pictures currently visible on screen.</p>
2513 *
2514 * @param outContent The assist content to return.
2515 */
2516 public void onProvideAssistContent(AssistContent outContent) {
2517 }
2518
2519 /**
2520 * Returns the list of direct actions supported by the app.
2521 *
2522 * <p>You should return the list of actions that could be executed in the
2523 * current context, which is in the current state of the app. If the actions
2524 * that could be executed by the app changes you should report that via
2525 * calling {@link VoiceInteractor#notifyDirectActionsChanged()}.
2526 *
2527 * <p>To get the voice interactor you need to call {@link #getVoiceInteractor()}
2528 * which would return non <code>null</code> only if there is an ongoing voice
2529 * interaction session. You can also detect when the voice interactor is no
2530 * longer valid because the voice interaction session that is backing is finished
2531 * by calling {@link VoiceInteractor#registerOnDestroyedCallback(Executor, Runnable)}.
2532 *
2533 * <p>This method will be called only after {@link #onStart()} and before {@link #onStop()}.
2534 *
2535 * <p>You should pass to the callback the currently supported direct actions which
2536 * cannot be <code>null</code> or contain <code>null</code> elements.
2537 *
2538 * <p>You should return the action list as soon as possible to ensure the consumer,
2539 * for example the assistant, is as responsive as possible which would improve user
2540 * experience of your app.
2541 *
2542 * @param cancellationSignal A signal to cancel the operation in progress.
2543 * @param callback The callback to send the action list. The actions list cannot
2544 * contain <code>null</code> elements. You can call this on any thread.
2545 */
2546 public void onGetDirectActions(@NonNull CancellationSignal cancellationSignal,
2547 @NonNull Consumer<List<DirectAction>> callback) {
2548 callback.accept(Collections.emptyList());
2549 }
2550
2551 /**
2552 * This is called to perform an action previously defined by the app.
2553 * Apps also have access to {@link #getVoiceInteractor()} to follow up on the action.
2554 *
2555 * @param actionId The ID for the action you previously reported via
2556 * {@link #onGetDirectActions(CancellationSignal, Consumer)}.
2557 * @param arguments Any additional arguments provided by the caller that are
2558 * specific to the given action.
2559 * @param cancellationSignal A signal to cancel the operation in progress.
2560 * @param resultListener The callback to provide the result back to the caller.
2561 * You can call this on any thread. The result bundle is action specific.
2562 *
2563 * @see #onGetDirectActions(CancellationSignal, Consumer)
2564 */
2565 public void onPerformDirectAction(@NonNull String actionId,
2566 @NonNull Bundle arguments, @NonNull CancellationSignal cancellationSignal,
2567 @NonNull Consumer<Bundle> resultListener) { }
2568
2569 /**
2570 * Request the Keyboard Shortcuts screen to show up. This will trigger
2571 * {@link #onProvideKeyboardShortcuts} to retrieve the shortcuts for the foreground activity.
2572 */
2573 public final void requestShowKeyboardShortcuts() {
2574 final ComponentName sysuiComponent = ComponentName.unflattenFromString(
2575 getResources().getString(
2576 com.android.internal.R.string.config_systemUIServiceComponent));
2577 Intent intent = new Intent(Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS);
2578 intent.setPackage(sysuiComponent.getPackageName());
2579 sendBroadcastAsUser(intent, Process.myUserHandle());
2580 }
2581
2582 /**
2583 * Dismiss the Keyboard Shortcuts screen.
2584 */
2585 public final void dismissKeyboardShortcutsHelper() {
2586 final ComponentName sysuiComponent = ComponentName.unflattenFromString(
2587 getResources().getString(
2588 com.android.internal.R.string.config_systemUIServiceComponent));
2589 Intent intent = new Intent(Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS);
2590 intent.setPackage(sysuiComponent.getPackageName());
2591 sendBroadcastAsUser(intent, Process.myUserHandle());
2592 }
2593
2594 @Override
2595 public void onProvideKeyboardShortcuts(
2596 List<KeyboardShortcutGroup> data, Menu menu, int deviceId) {
2597 if (menu == null) {
2598 return;
2599 }
2600 KeyboardShortcutGroup group = null;
2601 int menuSize = menu.size();
2602 for (int i = 0; i < menuSize; ++i) {
2603 final MenuItem item = menu.getItem(i);
2604 final CharSequence title = item.getTitle();
2605 final char alphaShortcut = item.getAlphabeticShortcut();
2606 final int alphaModifiers = item.getAlphabeticModifiers();
2607 if (title != null && alphaShortcut != MIN_VALUE) {
2608 if (group == null) {
2609 final int resource = mApplication.getApplicationInfo().labelRes;
2610 group = new KeyboardShortcutGroup(resource != 0 ? getString(resource) : null);
2611 }
2612 group.addItem(new KeyboardShortcutInfo(
2613 title, alphaShortcut, alphaModifiers));
2614 }
2615 }
2616 if (group != null) {
2617 data.add(group);
2618 }
2619 }
2620
2621 /**
2622 * Ask to have the current assistant shown to the user. This only works if the calling
2623 * activity is the current foreground activity. It is the same as calling
2624 * {@link android.service.voice.VoiceInteractionService#showSession
2625 * VoiceInteractionService.showSession} and requesting all of the possible context.
2626 * The receiver will always see
2627 * {@link android.service.voice.VoiceInteractionSession#SHOW_SOURCE_APPLICATION} set.
2628 * @return Returns true if the assistant was successfully invoked, else false. For example
2629 * false will be returned if the caller is not the current top activity.
2630 */
2631 public boolean showAssist(Bundle args) {
2632 return ActivityClient.getInstance().showAssistFromActivity(mToken, args);
2633 }
2634
2635 /**
2636 * Called when you are no longer visible to the user. You will next
2637 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
2638 * depending on later user activity. This is a good place to stop
2639 * refreshing UI, running animations and other visual things.
2640 *
2641 * <p><em>Derived classes must call through to the super class's
2642 * implementation of this method. If they do not, an exception will be
2643 * thrown.</em></p>
2644 *
2645 * @see #onRestart
2646 * @see #onResume
2647 * @see #onSaveInstanceState
2648 * @see #onDestroy
2649 */
2650 @CallSuper
2651 protected void onStop() {
2652 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
2653 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
2654 mActivityTransitionState.onStop(this);
2655 dispatchActivityStopped();
2656 mTranslucentCallback = null;
2657 mCalled = true;
2658
2659 getAutofillClientController().onActivityStopped(mIntent, mChangingConfigurations);
2660 mEnterAnimationComplete = false;
2661
2662 notifyVoiceInteractionManagerServiceActivityEvent(
2663 VoiceInteractionSession.VOICE_INTERACTION_ACTIVITY_EVENT_STOP);
2664 }
2665
2666 /**
2667 * Perform any final cleanup before an activity is destroyed. This can
2668 * happen either because the activity is finishing (someone called
2669 * {@link #finish} on it), or because the system is temporarily destroying
2670 * this instance of the activity to save space. You can distinguish
2671 * between these two scenarios with the {@link #isFinishing} method.
2672 *
2673 * <p><em>Note: do not count on this method being called as a place for
2674 * saving data! For example, if an activity is editing data in a content
2675 * provider, those edits should be committed in either {@link #onPause} or
2676 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
2677 * free resources like threads that are associated with an activity, so
2678 * that a destroyed activity does not leave such things around while the
2679 * rest of its application is still running. There are situations where
2680 * the system will simply kill the activity's hosting process without
2681 * calling this method (or any others) in it, so it should not be used to
2682 * do things that are intended to remain around after the process goes
2683 * away.
2684 *
2685 * <p><em>Derived classes must call through to the super class's
2686 * implementation of this method. If they do not, an exception will be
2687 * thrown.</em></p>
2688 *
2689 * @see #onPause
2690 * @see #onStop
2691 * @see #finish
2692 * @see #isFinishing
2693 */
2694 @CallSuper
2695 protected void onDestroy() {
2696 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
2697 mCalled = true;
2698
2699 getAutofillClientController().onActivityDestroyed();
2700
2701 // dismiss any dialogs we are managing.
2702 if (mManagedDialogs != null) {
2703 final int numDialogs = mManagedDialogs.size();
2704 for (int i = 0; i < numDialogs; i++) {
2705 final ManagedDialog md = mManagedDialogs.valueAt(i);
2706 if (md.mDialog.isShowing()) {
2707 md.mDialog.dismiss();
2708 }
2709 }
2710 mManagedDialogs = null;
2711 }
2712
2713 // close any cursors we are managing.
2714 synchronized (mManagedCursors) {
2715 int numCursors = mManagedCursors.size();
2716 for (int i = 0; i < numCursors; i++) {
2717 ManagedCursor c = mManagedCursors.get(i);
2718 if (c != null) {
2719 c.mCursor.close();
2720 }
2721 }
2722 mManagedCursors.clear();
2723 }
2724
2725 // Close any open search dialog
2726 if (mSearchManager != null) {
2727 mSearchManager.stopSearch();
2728 }
2729
2730 if (mActionBar != null) {
2731 mActionBar.onDestroy();
2732 }
2733
2734 dispatchActivityDestroyed();
2735
2736 notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_STOP);
2737
2738 if (mUiTranslationController != null) {
2739 mUiTranslationController.onActivityDestroyed();
2740 }
2741 if (mDefaultBackCallback != null) {
2742 getOnBackInvokedDispatcher().unregisterOnBackInvokedCallback(mDefaultBackCallback);
2743 mDefaultBackCallback = null;
2744 }
2745 if (mCallbacksController != null) {
2746 mCallbacksController.clearCallbacks();
2747 }
2748 }
2749
2750 /**
2751 * Report to the system that your app is now fully drawn, for diagnostic and
2752 * optimization purposes. The system may adjust optimizations to prioritize
2753 * work that happens before reportFullyDrawn is called, to improve app startup.
2754 * Misrepresenting the startup window by calling reportFullyDrawn too late or too
2755 * early may decrease application and startup performance.<p>
2756 * This is also used to help instrument application launch times, so that the
2757 * app can report when it is fully in a usable state; without this, the only thing
2758 * the system itself can determine is the point at which the activity's window
2759 * is <em>first</em> drawn and displayed. To participate in app launch time
2760 * measurement, you should always call this method after first launch (when
2761 * {@link #onCreate(android.os.Bundle)} is called), at the point where you have
2762 * entirely drawn your UI and populated with all of the significant data. You
2763 * can safely call this method any time after first launch as well, in which case
2764 * it will simply be ignored.
2765 * <p>If this method is called before the activity's window is <em>first</em> drawn
2766 * and displayed as measured by the system, the reported time here will be shifted
2767 * to the system measured time.
2768 */
2769 public void reportFullyDrawn() {
2770 if (mDoReportFullyDrawn) {
2771 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
2772 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
2773 "reportFullyDrawn() for " + mComponent.toShortString());
2774 }
2775 mDoReportFullyDrawn = false;
2776 try {
2777 ActivityClient.getInstance().reportActivityFullyDrawn(
2778 mToken, mRestoredFromBundle);
2779 VMRuntime.getRuntime().notifyStartupCompleted();
2780 } finally {
2781 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2782 }
2783 }
2784 }
2785
2786 /**
2787 * Called by the system when the activity changes from fullscreen mode to multi-window mode and
2788 * visa-versa. This method provides the same configuration that will be sent in the following
2789 * {@link #onConfigurationChanged(Configuration)} call after the activity enters this mode.
2790 *
2791 * @see android.R.attr#resizeableActivity
2792 *
2793 * @param isInMultiWindowMode True if the activity is in multi-window mode.
2794 * @param newConfig The new configuration of the activity with the state
2795 * {@param isInMultiWindowMode}.
2796 */
2797 public void onMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig) {
2798 // Left deliberately empty. There should be no side effects if a direct
2799 // subclass of Activity does not call super.
2800 onMultiWindowModeChanged(isInMultiWindowMode);
2801 }
2802
2803 /**
2804 * Called by the system when the activity changes from fullscreen mode to multi-window mode and
2805 * visa-versa.
2806 *
2807 * @see android.R.attr#resizeableActivity
2808 *
2809 * @param isInMultiWindowMode True if the activity is in multi-window mode.
2810 *
2811 * @deprecated Use {@link #onMultiWindowModeChanged(boolean, Configuration)} instead.
2812 */
2813 @Deprecated
2814 public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
2815 // Left deliberately empty. There should be no side effects if a direct
2816 // subclass of Activity does not call super.
2817 }
2818
2819 /**
2820 * Returns true if the activity is currently in multi-window mode.
2821 * @see android.R.attr#resizeableActivity
2822 *
2823 * @return True if the activity is in multi-window mode.
2824 */
2825 public boolean isInMultiWindowMode() {
2826 return mIsInMultiWindowMode;
2827 }
2828
2829 /**
2830 * Called by the system when the activity changes to and from picture-in-picture mode. This
2831 * method provides the same configuration that will be sent in the following
2832 * {@link #onConfigurationChanged(Configuration)} call after the activity enters this mode.
2833 *
2834 * @see android.R.attr#supportsPictureInPicture
2835 *
2836 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
2837 * @param newConfig The new configuration of the activity with the state
2838 * {@param isInPictureInPictureMode}.
2839 */
2840 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode,
2841 Configuration newConfig) {
2842 // Left deliberately empty. There should be no side effects if a direct
2843 // subclass of Activity does not call super.
2844 onPictureInPictureModeChanged(isInPictureInPictureMode);
2845 }
2846
2847 /**
2848 * Called by the system when the activity is in PiP and has state changes.
2849 *
2850 * Compare to {@link #onPictureInPictureModeChanged(boolean, Configuration)}, which is only
2851 * called when PiP mode changes (meaning, enters or exits PiP), this can be called at any time
2852 * while the activity is in PiP mode. Therefore, all invocation can only happen after
2853 * {@link #onPictureInPictureModeChanged(boolean, Configuration)} is called with true, and
2854 * before {@link #onPictureInPictureModeChanged(boolean, Configuration)} is called with false.
2855 * You would not need to worry about cases where this is called and the activity is not in
2856 * Picture-In-Picture mode. For managing cases where the activity enters/exits
2857 * Picture-in-Picture (e.g. resources clean-up on exit), use
2858 * {@link #onPictureInPictureModeChanged(boolean, Configuration)}.
2859 *
2860 * The default state is everything declared in {@link PictureInPictureUiState} is false, such as
2861 * {@link PictureInPictureUiState#isStashed()}.
2862 *
2863 * @param pipState the new Picture-in-Picture state.
2864 */
2865 public void onPictureInPictureUiStateChanged(@NonNull PictureInPictureUiState pipState) {
2866 // Left deliberately empty. There should be no side effects if a direct
2867 // subclass of Activity does not call super.
2868 }
2869
2870 /**
2871 * Called by the system when the activity changes to and from picture-in-picture mode.
2872 *
2873 * @see android.R.attr#supportsPictureInPicture
2874 *
2875 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
2876 *
2877 * @deprecated Use {@link #onPictureInPictureModeChanged(boolean, Configuration)} instead.
2878 */
2879 @Deprecated
2880 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
2881 // Left deliberately empty. There should be no side effects if a direct
2882 // subclass of Activity does not call super.
2883 }
2884
2885 /**
2886 * Returns true if the activity is currently in picture-in-picture mode.
2887 * @see android.R.attr#supportsPictureInPicture
2888 *
2889 * @return True if the activity is in picture-in-picture mode.
2890 */
2891 public boolean isInPictureInPictureMode() {
2892 return mIsInPictureInPictureMode;
2893 }
2894
2895 /**
2896 * Puts the activity in picture-in-picture mode if possible in the current system state. Any
2897 * prior calls to {@link #setPictureInPictureParams(PictureInPictureParams)} will still apply
2898 * when entering picture-in-picture through this call.
2899 *
2900 * @see #enterPictureInPictureMode(PictureInPictureParams)
2901 * @see android.R.attr#supportsPictureInPicture
2902 */
2903 @Deprecated
2904 public void enterPictureInPictureMode() {
2905 enterPictureInPictureMode(new PictureInPictureParams.Builder().build());
2906 }
2907
2908 /**
2909 * Puts the activity in picture-in-picture mode if possible in the current system state. The
2910 * set parameters in {@param params} will be combined with the parameters from prior calls to
2911 * {@link #setPictureInPictureParams(PictureInPictureParams)}.
2912 *
2913 * The system may disallow entering picture-in-picture in various cases, including when the
2914 * activity is not visible, if the screen is locked or if the user has an activity pinned.
2915 *
2916 * <p>By default, system calculates the dimension of picture-in-picture window based on the
2917 * given {@param params}.
2918 * See <a href="{@docRoot}guide/topics/ui/picture-in-picture">Picture-in-picture Support</a>
2919 * on how to override this behavior.</p>
2920 *
2921 * @see android.R.attr#supportsPictureInPicture
2922 * @see PictureInPictureParams
2923 *
2924 * @param params non-null parameters to be combined with previously set parameters when entering
2925 * picture-in-picture.
2926 *
2927 * @return true if the system successfully put this activity into picture-in-picture mode or was
2928 * already in picture-in-picture mode (see {@link #isInPictureInPictureMode()}). If the device
2929 * does not support picture-in-picture, return false.
2930 */
2931 public boolean enterPictureInPictureMode(@NonNull PictureInPictureParams params) {
2932 if (!deviceSupportsPictureInPictureMode()) {
2933 return false;
2934 }
2935 if (params == null) {
2936 throw new IllegalArgumentException("Expected non-null picture-in-picture params");
2937 }
2938 if (!mCanEnterPictureInPicture) {
2939 throw new IllegalStateException("Activity must be resumed to enter"
2940 + " picture-in-picture");
2941 }
2942 // Set mIsInPictureInPictureMode earlier and don't wait for
2943 // onPictureInPictureModeChanged callback here. This is to ensure that
2944 // isInPictureInPictureMode returns true in the following onPause callback.
2945 // See https://developer.android.com/guide/topics/ui/picture-in-picture for guidance.
2946 mIsInPictureInPictureMode = ActivityClient.getInstance().enterPictureInPictureMode(
2947 mToken, params);
2948 return mIsInPictureInPictureMode;
2949 }
2950
2951 /**
2952 * Updates the properties of the picture-in-picture activity, or sets it to be used later when
2953 * {@link #enterPictureInPictureMode()} is called.
2954 *
2955 * @param params the new parameters for the picture-in-picture.
2956 */
2957 public void setPictureInPictureParams(@NonNull PictureInPictureParams params) {
2958 if (!deviceSupportsPictureInPictureMode()) {
2959 return;
2960 }
2961 if (params == null) {
2962 throw new IllegalArgumentException("Expected non-null picture-in-picture params");
2963 }
2964 ActivityClient.getInstance().setPictureInPictureParams(mToken, params);
2965 }
2966
2967 /**
2968 * Return the number of actions that will be displayed in the picture-in-picture UI when the
2969 * user interacts with the activity currently in picture-in-picture mode. This number may change
2970 * if the global configuration changes (ie. if the device is plugged into an external display),
2971 * but will always be at least three.
2972 */
2973 public int getMaxNumPictureInPictureActions() {
2974 return ActivityTaskManager.getMaxNumPictureInPictureActions(this);
2975 }
2976
2977 /**
2978 * @return Whether this device supports picture-in-picture.
2979 */
2980 private boolean deviceSupportsPictureInPictureMode() {
2981 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE);
2982 }
2983
2984 /**
2985 * This method is called by the system in various cases where picture in picture mode should be
2986 * entered if supported.
2987 *
2988 * <p>It is up to the app developer to choose whether to call
2989 * {@link #enterPictureInPictureMode(PictureInPictureParams)} at this time. For example, the
2990 * system will call this method when the activity is being put into the background, so the app
2991 * developer might want to switch an activity into PIP mode instead.</p>
2992 *
2993 * @return {@code true} if the activity received this callback regardless of if it acts on it
2994 * or not. If {@code false}, the framework will assume the app hasn't been updated to leverage
2995 * this callback and will in turn send a legacy callback of {@link #onUserLeaveHint()} for the
2996 * app to enter picture-in-picture mode.
2997 */
2998 public boolean onPictureInPictureRequested() {
2999 return false;
3000 }
3001
3002 /**
3003 * Specifies a preference to dock big overlays like the expanded picture-in-picture on TV
3004 * (see {@link PictureInPictureParams.Builder#setExpandedAspectRatio}). Docking puts the
3005 * big overlay side-by-side next to this activity, so that both windows are fully visible to
3006 * the user.
3007 *
3008 * <p> If unspecified, whether the overlay window will be docked or not, will be defined
3009 * by the system.
3010 *
3011 * <p> If specified, the system will try to respect the preference, but it may be
3012 * overridden by a user preference.
3013 *
3014 * @param shouldDockBigOverlays indicates that big overlays should be docked next to the
3015 * activity instead of overlay its content
3016 *
3017 * @see PictureInPictureParams.Builder#setExpandedAspectRatio
3018 * @see #shouldDockBigOverlays
3019 */
3020 public void setShouldDockBigOverlays(boolean shouldDockBigOverlays) {
3021 ActivityClient.getInstance().setShouldDockBigOverlays(mToken, shouldDockBigOverlays);
3022 mShouldDockBigOverlays = shouldDockBigOverlays;
3023 }
3024
3025 /**
3026 * Returns whether big overlays should be docked next to the activity as set by
3027 * {@link #setShouldDockBigOverlays}.
3028 *
3029 * @return {@code true} if big overlays should be docked next to the activity instead
3030 * of overlay its content
3031 *
3032 * @see #setShouldDockBigOverlays
3033 */
3034 public boolean shouldDockBigOverlays() {
3035 return mShouldDockBigOverlays;
3036 }
3037
3038 void dispatchMovedToDisplay(int displayId, Configuration config) {
3039 updateDisplay(displayId);
3040 onMovedToDisplay(displayId, config);
3041 }
3042
3043 /**
3044 * Called by the system when the activity is moved from one display to another without
3045 * recreation. This means that this activity is declared to handle all changes to configuration
3046 * that happened when it was switched to another display, so it wasn't destroyed and created
3047 * again.
3048 *
3049 * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
3050 * applied configuration actually changed. It is up to app developer to choose whether to handle
3051 * the change in this method or in the following {@link #onConfigurationChanged(Configuration)}
3052 * call.
3053 *
3054 * <p>Use this callback to track changes to the displays if some activity functionality relies
3055 * on an association with some display properties.
3056 *
3057 * @param displayId The id of the display to which activity was moved.
3058 * @param config Configuration of the activity resources on new display after move.
3059 *
3060 * @see #onConfigurationChanged(Configuration)
3061 * @see View#onMovedToDisplay(int, Configuration)
3062 * @hide
3063 */
3064 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3065 @TestApi
3066 public void onMovedToDisplay(int displayId, Configuration config) {
3067 }
3068
3069 /**
3070 * Called by the system when the device configuration changes while your
3071 * activity is running. Note that this will <em>only</em> be called if
3072 * you have selected configurations you would like to handle with the
3073 * {@link android.R.attr#configChanges} attribute in your manifest. If
3074 * any configuration change occurs that is not selected to be reported
3075 * by that attribute, then instead of reporting it the system will stop
3076 * and restart the activity (to have it launched with the new
3077 * configuration).
3078 *
3079 * <p>At the time that this function has been called, your Resources
3080 * object will have been updated to return resource values matching the
3081 * new configuration.
3082 *
3083 * @param newConfig The new device configuration.
3084 */
3085 public void onConfigurationChanged(@NonNull Configuration newConfig) {
3086 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onConfigurationChanged " + this + ": " + newConfig);
3087 mCalled = true;
3088
3089 mFragments.dispatchConfigurationChanged(newConfig);
3090
3091 if (mWindow != null) {
3092 // Pass the configuration changed event to the window
3093 mWindow.onConfigurationChanged(newConfig);
3094 }
3095
3096 if (mActionBar != null) {
3097 // Do this last; the action bar will need to access
3098 // view changes from above.
3099 mActionBar.onConfigurationChanged(newConfig);
3100 }
3101
3102 dispatchActivityConfigurationChanged();
3103 if (mCallbacksController != null) {
3104 mCallbacksController.dispatchConfigurationChanged(newConfig);
3105 }
3106 }
3107
3108 /**
3109 * If this activity is being destroyed because it can not handle a
3110 * configuration parameter being changed (and thus its
3111 * {@link #onConfigurationChanged(Configuration)} method is
3112 * <em>not</em> being called), then you can use this method to discover
3113 * the set of changes that have occurred while in the process of being
3114 * destroyed. Note that there is no guarantee that these will be
3115 * accurate (other changes could have happened at any time), so you should
3116 * only use this as an optimization hint.
3117 *
3118 * @return Returns a bit field of the configuration parameters that are
3119 * changing, as defined by the {@link android.content.res.Configuration}
3120 * class.
3121 */
3122 public int getChangingConfigurations() {
3123 return mConfigChangeFlags;
3124 }
3125
3126 /**
3127 * Retrieve the non-configuration instance data that was previously
3128 * returned by {@link #onRetainNonConfigurationInstance()}. This will
3129 * be available from the initial {@link #onCreate} and
3130 * {@link #onStart} calls to the new instance, allowing you to extract
3131 * any useful dynamic state from the previous instance.
3132 *
3133 * <p>Note that the data you retrieve here should <em>only</em> be used
3134 * as an optimization for handling configuration changes. You should always
3135 * be able to handle getting a null pointer back, and an activity must
3136 * still be able to restore itself to its previous state (through the
3137 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
3138 * function returns null.
3139 *
3140 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
3141 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
3142 * available on older platforms through the Android support libraries.
3143 *
3144 * @return the object previously returned by {@link #onRetainNonConfigurationInstance()}
3145 */
3146 @Nullable
3147 public Object getLastNonConfigurationInstance() {
3148 return mLastNonConfigurationInstances != null
3149 ? mLastNonConfigurationInstances.activity : null;
3150 }
3151
3152 /**
3153 * Called by the system, as part of destroying an
3154 * activity due to a configuration change, when it is known that a new
3155 * instance will immediately be created for the new configuration. You
3156 * can return any object you like here, including the activity instance
3157 * itself, which can later be retrieved by calling
3158 * {@link #getLastNonConfigurationInstance()} in the new activity
3159 * instance.
3160 *
3161 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3162 * or later, consider instead using a {@link Fragment} with
3163 * {@link Fragment#setRetainInstance(boolean)
3164 * Fragment.setRetainInstance(boolean}.</em>
3165 *
3166 * <p>This function is called purely as an optimization, and you must
3167 * not rely on it being called. When it is called, a number of guarantees
3168 * will be made to help optimize configuration switching:
3169 * <ul>
3170 * <li> The function will be called between {@link #onStop} and
3171 * {@link #onDestroy}.
3172 * <li> A new instance of the activity will <em>always</em> be immediately
3173 * created after this one's {@link #onDestroy()} is called. In particular,
3174 * <em>no</em> messages will be dispatched during this time (when the returned
3175 * object does not have an activity to be associated with).
3176 * <li> The object you return here will <em>always</em> be available from
3177 * the {@link #getLastNonConfigurationInstance()} method of the following
3178 * activity instance as described there.
3179 * </ul>
3180 *
3181 * <p>These guarantees are designed so that an activity can use this API
3182 * to propagate extensive state from the old to new activity instance, from
3183 * loaded bitmaps, to network connections, to evenly actively running
3184 * threads. Note that you should <em>not</em> propagate any data that
3185 * may change based on the configuration, including any data loaded from
3186 * resources such as strings, layouts, or drawables.
3187 *
3188 * <p>The guarantee of no message handling during the switch to the next
3189 * activity simplifies use with active objects. For example if your retained
3190 * state is an {@link android.os.AsyncTask} you are guaranteed that its
3191 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
3192 * not be called from the call here until you execute the next instance's
3193 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
3194 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
3195 * running in a separate thread.)
3196 *
3197 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
3198 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
3199 * available on older platforms through the Android support libraries.
3200 *
3201 * @return any Object holding the desired state to propagate to the
3202 * next activity instance
3203 */
3204 public Object onRetainNonConfigurationInstance() {
3205 return null;
3206 }
3207
3208 /**
3209 * Retrieve the non-configuration instance data that was previously
3210 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
3211 * be available from the initial {@link #onCreate} and
3212 * {@link #onStart} calls to the new instance, allowing you to extract
3213 * any useful dynamic state from the previous instance.
3214 *
3215 * <p>Note that the data you retrieve here should <em>only</em> be used
3216 * as an optimization for handling configuration changes. You should always
3217 * be able to handle getting a null pointer back, and an activity must
3218 * still be able to restore itself to its previous state (through the
3219 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
3220 * function returns null.
3221 *
3222 * @return Returns the object previously returned by
3223 * {@link #onRetainNonConfigurationChildInstances()}
3224 */
3225 @Nullable
3226 HashMap<String, Object> getLastNonConfigurationChildInstances() {
3227 return mLastNonConfigurationInstances != null
3228 ? mLastNonConfigurationInstances.children : null;
3229 }
3230
3231 /**
3232 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
3233 * it should return either a mapping from child activity id strings to arbitrary objects,
3234 * or null. This method is intended to be used by Activity framework subclasses that control a
3235 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
3236 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
3237 */
3238 @Nullable
3239 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
3240 return null;
3241 }
3242
3243 NonConfigurationInstances retainNonConfigurationInstances() {
3244 Object activity = onRetainNonConfigurationInstance();
3245 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
3246 FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();
3247
3248 // We're already stopped but we've been asked to retain.
3249 // Our fragments are taken care of but we need to mark the loaders for retention.
3250 // In order to do this correctly we need to restart the loaders first before
3251 // handing them off to the next activity.
3252 mFragments.doLoaderStart();
3253 mFragments.doLoaderStop(true);
3254 ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
3255
3256 if (activity == null && children == null && fragments == null && loaders == null
3257 && mVoiceInteractor == null) {
3258 return null;
3259 }
3260
3261 NonConfigurationInstances nci = new NonConfigurationInstances();
3262 nci.activity = activity;
3263 nci.children = children;
3264 nci.fragments = fragments;
3265 nci.loaders = loaders;
3266 if (mVoiceInteractor != null) {
3267 mVoiceInteractor.retainInstance();
3268 nci.voiceInteractor = mVoiceInteractor;
3269 }
3270 return nci;
3271 }
3272
3273 public void onLowMemory() {
3274 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onLowMemory " + this);
3275 mCalled = true;
3276 mFragments.dispatchLowMemory();
3277 if (mCallbacksController != null) {
3278 mCallbacksController.dispatchLowMemory();
3279 }
3280 }
3281
3282 public void onTrimMemory(int level) {
3283 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onTrimMemory " + this + ": " + level);
3284 mCalled = true;
3285 mFragments.dispatchTrimMemory(level);
3286 if (mCallbacksController != null) {
3287 mCallbacksController.dispatchTrimMemory(level);
3288 }
3289 }
3290
3291 /**
3292 * Return the FragmentManager for interacting with fragments associated
3293 * with this activity.
3294 *
3295 * @deprecated Use {@link androidx.fragment.app.FragmentActivity#getSupportFragmentManager()}
3296 */
3297 @Deprecated
3298 public FragmentManager getFragmentManager() {
3299 return mFragments.getFragmentManager();
3300 }
3301
3302 /**
3303 * Called when a Fragment is being attached to this activity, immediately
3304 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
3305 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
3306 *
3307 * @deprecated Use {@link
3308 * androidx.fragment.app.FragmentActivity#onAttachFragment(androidx.fragment.app.Fragment)}
3309 */
3310 @Deprecated
3311 public void onAttachFragment(Fragment fragment) {
3312 }
3313
3314 /**
3315 * Wrapper around
3316 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
3317 * that gives the resulting {@link Cursor} to call
3318 * {@link #startManagingCursor} so that the activity will manage its
3319 * lifecycle for you.
3320 *
3321 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3322 * or later, consider instead using {@link LoaderManager} instead, available
3323 * via {@link #getLoaderManager()}.</em>
3324 *
3325 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
3326 * this method, because the activity will do that for you at the appropriate time. However, if
3327 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
3328 * not</em> automatically close the cursor and, in that case, you must call
3329 * {@link Cursor#close()}.</p>
3330 *
3331 * @param uri The URI of the content provider to query.
3332 * @param projection List of columns to return.
3333 * @param selection SQL WHERE clause.
3334 * @param sortOrder SQL ORDER BY clause.
3335 *
3336 * @return The Cursor that was returned by query().
3337 *
3338 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
3339 * @see #startManagingCursor
3340 * @hide
3341 *
3342 * @deprecated Use {@link CursorLoader} instead.
3343 */
3344 @Deprecated
3345 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3346 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
3347 String sortOrder) {
3348 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
3349 if (c != null) {
3350 startManagingCursor(c);
3351 }
3352 return c;
3353 }
3354
3355 /**
3356 * Wrapper around
3357 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
3358 * that gives the resulting {@link Cursor} to call
3359 * {@link #startManagingCursor} so that the activity will manage its
3360 * lifecycle for you.
3361 *
3362 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3363 * or later, consider instead using {@link LoaderManager} instead, available
3364 * via {@link #getLoaderManager()}.</em>
3365 *
3366 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
3367 * this method, because the activity will do that for you at the appropriate time. However, if
3368 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
3369 * not</em> automatically close the cursor and, in that case, you must call
3370 * {@link Cursor#close()}.</p>
3371 *
3372 * @param uri The URI of the content provider to query.
3373 * @param projection List of columns to return.
3374 * @param selection SQL WHERE clause.
3375 * @param selectionArgs The arguments to selection, if any ?s are pesent
3376 * @param sortOrder SQL ORDER BY clause.
3377 *
3378 * @return The Cursor that was returned by query().
3379 *
3380 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
3381 * @see #startManagingCursor
3382 *
3383 * @deprecated Use {@link CursorLoader} instead.
3384 */
3385 @Deprecated
3386 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
3387 String[] selectionArgs, String sortOrder) {
3388 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
3389 if (c != null) {
3390 startManagingCursor(c);
3391 }
3392 return c;
3393 }
3394
3395 /**
3396 * This method allows the activity to take care of managing the given
3397 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
3398 * That is, when the activity is stopped it will automatically call
3399 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
3400 * it will call {@link Cursor#requery} for you. When the activity is
3401 * destroyed, all managed Cursors will be closed automatically.
3402 *
3403 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3404 * or later, consider instead using {@link LoaderManager} instead, available
3405 * via {@link #getLoaderManager()}.</em>
3406 *
3407 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on cursor obtained from
3408 * {@link #managedQuery}, because the activity will do that for you at the appropriate time.
3409 * However, if you call {@link #stopManagingCursor} on a cursor from a managed query, the system
3410 * <em>will not</em> automatically close the cursor and, in that case, you must call
3411 * {@link Cursor#close()}.</p>
3412 *
3413 * @param c The Cursor to be managed.
3414 *
3415 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
3416 * @see #stopManagingCursor
3417 *
3418 * @deprecated Use the new {@link android.content.CursorLoader} class with
3419 * {@link LoaderManager} instead; this is also
3420 * available on older platforms through the Android compatibility package.
3421 */
3422 @Deprecated
3423 public void startManagingCursor(Cursor c) {
3424 synchronized (mManagedCursors) {
3425 mManagedCursors.add(new ManagedCursor(c));
3426 }
3427 }
3428
3429 /**
3430 * Given a Cursor that was previously given to
3431 * {@link #startManagingCursor}, stop the activity's management of that
3432 * cursor.
3433 *
3434 * <p><strong>Warning:</strong> After calling this method on a cursor from a managed query,
3435 * the system <em>will not</em> automatically close the cursor and you must call
3436 * {@link Cursor#close()}.</p>
3437 *
3438 * @param c The Cursor that was being managed.
3439 *
3440 * @see #startManagingCursor
3441 *
3442 * @deprecated Use the new {@link android.content.CursorLoader} class with
3443 * {@link LoaderManager} instead; this is also
3444 * available on older platforms through the Android compatibility package.
3445 */
3446 @Deprecated
3447 public void stopManagingCursor(Cursor c) {
3448 synchronized (mManagedCursors) {
3449 final int N = mManagedCursors.size();
3450 for (int i=0; i<N; i++) {
3451 ManagedCursor mc = mManagedCursors.get(i);
3452 if (mc.mCursor == c) {
3453 mManagedCursors.remove(i);
3454 break;
3455 }
3456 }
3457 }
3458 }
3459
3460 /**
3461 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
3462 * this is a no-op.
3463 * @hide
3464 */
3465 @Deprecated
3466 @UnsupportedAppUsage
3467 public void setPersistent(boolean isPersistent) {
3468 }
3469
3470 /**
3471 * Finds a view that was identified by the {@code android:id} XML attribute
3472 * that was processed in {@link #onCreate}.
3473 * <p>
3474 * <strong>Note:</strong> In most cases -- depending on compiler support --
3475 * the resulting view is automatically cast to the target class type. If
3476 * the target class type is unconstrained, an explicit cast may be
3477 * necessary.
3478 *
3479 * @param id the ID to search for
3480 * @return a view with given ID if found, or {@code null} otherwise
3481 * @see View#findViewById(int)
3482 * @see Activity#requireViewById(int)
3483 */
3484 @Nullable
3485 public <T extends View> T findViewById(@IdRes int id) {
3486 return getWindow().findViewById(id);
3487 }
3488
3489 /**
3490 * Finds a view that was identified by the {@code android:id} XML attribute that was processed
3491 * in {@link #onCreate}, or throws an IllegalArgumentException if the ID is invalid, or there is
3492 * no matching view in the hierarchy.
3493 * <p>
3494 * <strong>Note:</strong> In most cases -- depending on compiler support --
3495 * the resulting view is automatically cast to the target class type. If
3496 * the target class type is unconstrained, an explicit cast may be
3497 * necessary.
3498 *
3499 * @param id the ID to search for
3500 * @return a view with given ID
3501 * @see View#requireViewById(int)
3502 * @see Activity#findViewById(int)
3503 */
3504 @NonNull
3505 public final <T extends View> T requireViewById(@IdRes int id) {
3506 T view = findViewById(id);
3507 if (view == null) {
3508 throw new IllegalArgumentException("ID does not reference a View inside this Activity");
3509 }
3510 return view;
3511 }
3512
3513 /**
3514 * Retrieve a reference to this activity's ActionBar.
3515 *
3516 * @return The Activity's ActionBar, or null if it does not have one.
3517 */
3518 @Nullable
3519 public ActionBar getActionBar() {
3520 initWindowDecorActionBar();
3521 return mActionBar;
3522 }
3523
3524 /**
3525 * Set a {@link android.widget.Toolbar Toolbar} to act as the {@link ActionBar} for this
3526 * Activity window.
3527 *
3528 * <p>When set to a non-null value the {@link #getActionBar()} method will return
3529 * an {@link ActionBar} object that can be used to control the given toolbar as if it were
3530 * a traditional window decor action bar. The toolbar's menu will be populated with the
3531 * Activity's options menu and the navigation button will be wired through the standard
3532 * {@link android.R.id#home home} menu select action.</p>
3533 *
3534 * <p>In order to use a Toolbar within the Activity's window content the application
3535 * must not request the window feature {@link Window#FEATURE_ACTION_BAR FEATURE_ACTION_BAR}.</p>
3536 *
3537 * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it
3538 */
3539 public void setActionBar(@Nullable Toolbar toolbar) {
3540 final ActionBar ab = getActionBar();
3541 if (ab instanceof WindowDecorActionBar) {
3542 throw new IllegalStateException("This Activity already has an action bar supplied " +
3543 "by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " +
3544 "android:windowActionBar to false in your theme to use a Toolbar instead.");
3545 }
3546
3547 // If we reach here then we're setting a new action bar
3548 // First clear out the MenuInflater to make sure that it is valid for the new Action Bar
3549 mMenuInflater = null;
3550
3551 // If we have an action bar currently, destroy it
3552 if (ab != null) {
3553 ab.onDestroy();
3554 }
3555
3556 if (toolbar != null) {
3557 final ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this);
3558 mActionBar = tbab;
3559 mWindow.setCallback(tbab.getWrappedWindowCallback());
3560 } else {
3561 mActionBar = null;
3562 // Re-set the original window callback since we may have already set a Toolbar wrapper
3563 mWindow.setCallback(this);
3564 }
3565
3566 invalidateOptionsMenu();
3567 }
3568
3569 /**
3570 * Creates a new ActionBar, locates the inflated ActionBarView,
3571 * initializes the ActionBar with the view, and sets mActionBar.
3572 */
3573 private void initWindowDecorActionBar() {
3574 Window window = getWindow();
3575
3576 // Initializing the window decor can change window feature flags.
3577 // Make sure that we have the correct set before performing the test below.
3578 window.getDecorView();
3579
3580 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
3581 return;
3582 }
3583
3584 mActionBar = new WindowDecorActionBar(this);
3585 mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
3586
3587 mWindow.setDefaultIcon(mActivityInfo.getIconResource());
3588 mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
3589 }
3590
3591 /**
3592 * Set the activity content from a layout resource. The resource will be
3593 * inflated, adding all top-level views to the activity.
3594 *
3595 * @param layoutResID Resource ID to be inflated.
3596 *
3597 * @see #setContentView(android.view.View)
3598 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
3599 */
3600 public void setContentView(@LayoutRes int layoutResID) {
3601 getWindow().setContentView(layoutResID);
3602 initWindowDecorActionBar();
3603 }
3604
3605 /**
3606 * Set the activity content to an explicit view. This view is placed
3607 * directly into the activity's view hierarchy. It can itself be a complex
3608 * view hierarchy. When calling this method, the layout parameters of the
3609 * specified view are ignored. Both the width and the height of the view are
3610 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
3611 * your own layout parameters, invoke
3612 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
3613 * instead.
3614 *
3615 * @param view The desired content to display.
3616 *
3617 * @see #setContentView(int)
3618 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
3619 */
3620 public void setContentView(View view) {
3621 getWindow().setContentView(view);
3622 initWindowDecorActionBar();
3623 }
3624
3625 /**
3626 * Set the activity content to an explicit view. This view is placed
3627 * directly into the activity's view hierarchy. It can itself be a complex
3628 * view hierarchy.
3629 *
3630 * @param view The desired content to display.
3631 * @param params Layout parameters for the view.
3632 *
3633 * @see #setContentView(android.view.View)
3634 * @see #setContentView(int)
3635 */
3636 public void setContentView(View view, ViewGroup.LayoutParams params) {
3637 getWindow().setContentView(view, params);
3638 initWindowDecorActionBar();
3639 }
3640
3641 /**
3642 * Add an additional content view to the activity. Added after any existing
3643 * ones in the activity -- existing views are NOT removed.
3644 *
3645 * @param view The desired content to display.
3646 * @param params Layout parameters for the view.
3647 */
3648 public void addContentView(View view, ViewGroup.LayoutParams params) {
3649 getWindow().addContentView(view, params);
3650 initWindowDecorActionBar();
3651 }
3652
3653 /**
3654 * Retrieve the {@link TransitionManager} responsible for default transitions in this window.
3655 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
3656 *
3657 * <p>This method will return non-null after content has been initialized (e.g. by using
3658 * {@link #setContentView}) if {@link Window#FEATURE_CONTENT_TRANSITIONS} has been granted.</p>
3659 *
3660 * @return This window's content TransitionManager or null if none is set.
3661 */
3662 public TransitionManager getContentTransitionManager() {
3663 return getWindow().getTransitionManager();
3664 }
3665
3666 /**
3667 * Set the {@link TransitionManager} to use for default transitions in this window.
3668 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
3669 *
3670 * @param tm The TransitionManager to use for scene changes.
3671 */
3672 public void setContentTransitionManager(TransitionManager tm) {
3673 getWindow().setTransitionManager(tm);
3674 }
3675
3676 /**
3677 * Retrieve the {@link Scene} representing this window's current content.
3678 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
3679 *
3680 * <p>This method will return null if the current content is not represented by a Scene.</p>
3681 *
3682 * @return Current Scene being shown or null
3683 */
3684 public Scene getContentScene() {
3685 return getWindow().getContentScene();
3686 }
3687
3688 /**
3689 * Sets whether this activity is finished when touched outside its window's
3690 * bounds.
3691 */
3692 public void setFinishOnTouchOutside(boolean finish) {
3693 mWindow.setCloseOnTouchOutside(finish);
3694 }
3695
3696 /** @hide */
3697 @IntDef(prefix = { "DEFAULT_KEYS_" }, value = {
3698 DEFAULT_KEYS_DISABLE,
3699 DEFAULT_KEYS_DIALER,
3700 DEFAULT_KEYS_SHORTCUT,
3701 DEFAULT_KEYS_SEARCH_LOCAL,
3702 DEFAULT_KEYS_SEARCH_GLOBAL
3703 })
3704 @Retention(RetentionPolicy.SOURCE)
3705 @interface DefaultKeyMode {}
3706
3707 /**
3708 * Use with {@link #setDefaultKeyMode} to turn off default handling of
3709 * keys.
3710 *
3711 * @see #setDefaultKeyMode
3712 */
3713 static public final int DEFAULT_KEYS_DISABLE = 0;
3714 /**
3715 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
3716 * key handling.
3717 *
3718 * @see #setDefaultKeyMode
3719 */
3720 static public final int DEFAULT_KEYS_DIALER = 1;
3721 /**
3722 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
3723 * default key handling.
3724 *
3725 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
3726 *
3727 * @see #setDefaultKeyMode
3728 */
3729 static public final int DEFAULT_KEYS_SHORTCUT = 2;
3730 /**
3731 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
3732 * will start an application-defined search. (If the application or activity does not
3733 * actually define a search, the keys will be ignored.)
3734 *
3735 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
3736 *
3737 * @see #setDefaultKeyMode
3738 */
3739 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
3740
3741 /**
3742 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
3743 * will start a global search (typically web search, but some platforms may define alternate
3744 * methods for global search)
3745 *
3746 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
3747 *
3748 * @see #setDefaultKeyMode
3749 */
3750 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
3751
3752 /**
3753 * Select the default key handling for this activity. This controls what
3754 * will happen to key events that are not otherwise handled. The default
3755 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
3756 * floor. Other modes allow you to launch the dialer
3757 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
3758 * menu without requiring the menu key be held down
3759 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
3760 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
3761 *
3762 * <p>Note that the mode selected here does not impact the default
3763 * handling of system keys, such as the "back" and "menu" keys, and your
3764 * activity and its views always get a first chance to receive and handle
3765 * all application keys.
3766 *
3767 * @param mode The desired default key mode constant.
3768 *
3769 * @see #onKeyDown
3770 */
3771 public final void setDefaultKeyMode(@DefaultKeyMode int mode) {
3772 mDefaultKeyMode = mode;
3773
3774 // Some modes use a SpannableStringBuilder to track & dispatch input events
3775 // This list must remain in sync with the switch in onKeyDown()
3776 switch (mode) {
3777 case DEFAULT_KEYS_DISABLE:
3778 case DEFAULT_KEYS_SHORTCUT:
3779 mDefaultKeySsb = null; // not used in these modes
3780 break;
3781 case DEFAULT_KEYS_DIALER:
3782 case DEFAULT_KEYS_SEARCH_LOCAL:
3783 case DEFAULT_KEYS_SEARCH_GLOBAL:
3784 mDefaultKeySsb = new SpannableStringBuilder();
3785 Selection.setSelection(mDefaultKeySsb,0);
3786 break;
3787 default:
3788 throw new IllegalArgumentException();
3789 }
3790 }
3791
3792 /**
3793 * Called when a key was pressed down and not handled by any of the views
3794 * inside of the activity. So, for example, key presses while the cursor
3795 * is inside a TextView will not trigger the event (unless it is a navigation
3796 * to another object) because TextView handles its own key presses.
3797 *
3798 * <p>If the focused view didn't want this event, this method is called.
3799 *
3800 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
3801 * by calling {@link #onBackPressed()}, though the behavior varies based
3802 * on the application compatibility mode: for
3803 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
3804 * it will set up the dispatch to call {@link #onKeyUp} where the action
3805 * will be performed; for earlier applications, it will perform the
3806 * action immediately in on-down, as those versions of the platform
3807 * behaved.
3808 *
3809 * <p>Other additional default key handling may be performed
3810 * if configured with {@link #setDefaultKeyMode}.
3811 *
3812 * @return Return <code>true</code> to prevent this event from being propagated
3813 * further, or <code>false</code> to indicate that you have not handled
3814 * this event and it should continue to be propagated.
3815 * @see #onKeyUp
3816 * @see android.view.KeyEvent
3817 */
3818 public boolean onKeyDown(int keyCode, KeyEvent event) {
3819 if (keyCode == KeyEvent.KEYCODE_BACK) {
3820 if (getApplicationInfo().targetSdkVersion
3821 >= Build.VERSION_CODES.ECLAIR) {
3822 event.startTracking();
3823 } else {
3824 onBackPressed();
3825 }
3826 return true;
3827 }
3828
3829 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
3830 return false;
3831 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
3832 Window w = getWindow();
3833 if (w.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3834 w.performPanelShortcut(Window.FEATURE_OPTIONS_PANEL, keyCode, event,
3835 Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
3836 return true;
3837 }
3838 return false;
3839 } else if (keyCode == KeyEvent.KEYCODE_TAB) {
3840 // Don't consume TAB here since it's used for navigation. Arrow keys
3841 // aren't considered "typing keys" so they already won't get consumed.
3842 return false;
3843 } else {
3844 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
3845 boolean clearSpannable = false;
3846 boolean handled;
3847 if ((event.getRepeatCount() != 0) || event.isSystem()) {
3848 clearSpannable = true;
3849 handled = false;
3850 } else {
3851 handled = TextKeyListener.getInstance().onKeyDown(
3852 null, mDefaultKeySsb, keyCode, event);
3853 if (handled && mDefaultKeySsb.length() > 0) {
3854 // something useable has been typed - dispatch it now.
3855
3856 final String str = mDefaultKeySsb.toString();
3857 clearSpannable = true;
3858
3859 switch (mDefaultKeyMode) {
3860 case DEFAULT_KEYS_DIALER:
3861 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
3862 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3863 startActivity(intent);
3864 break;
3865 case DEFAULT_KEYS_SEARCH_LOCAL:
3866 startSearch(str, false, null, false);
3867 break;
3868 case DEFAULT_KEYS_SEARCH_GLOBAL:
3869 startSearch(str, false, null, true);
3870 break;
3871 }
3872 }
3873 }
3874 if (clearSpannable) {
3875 mDefaultKeySsb.clear();
3876 mDefaultKeySsb.clearSpans();
3877 Selection.setSelection(mDefaultKeySsb,0);
3878 }
3879 return handled;
3880 }
3881 }
3882
3883 /**
3884 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
3885 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
3886 * the event).
3887 *
3888 * To receive this callback, you must return true from onKeyDown for the current
3889 * event stream.
3890 *
3891 * @see KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
3892 */
3893 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
3894 return false;
3895 }
3896
3897 /**
3898 * Called when a key was released and not handled by any of the views
3899 * inside of the activity. So, for example, key presses while the cursor
3900 * is inside a TextView will not trigger the event (unless it is a navigation
3901 * to another object) because TextView handles its own key presses.
3902 *
3903 * <p>The default implementation handles KEYCODE_BACK to stop the activity
3904 * and go back.
3905 *
3906 * @return Return <code>true</code> to prevent this event from being propagated
3907 * further, or <code>false</code> to indicate that you have not handled
3908 * this event and it should continue to be propagated.
3909 * @see #onKeyDown
3910 * @see KeyEvent
3911 */
3912 public boolean onKeyUp(int keyCode, KeyEvent event) {
3913 int sdkVersion = getApplicationInfo().targetSdkVersion;
3914 if (sdkVersion >= Build.VERSION_CODES.ECLAIR) {
3915 if (keyCode == KeyEvent.KEYCODE_BACK
3916 && event.isTracking()
3917 && !event.isCanceled()
3918 && mDefaultBackCallback == null) {
3919 // Using legacy back handling.
3920 onBackPressed();
3921 return true;
3922 }
3923 }
3924 return false;
3925 }
3926
3927 /**
3928 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
3929 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
3930 * the event).
3931 */
3932 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
3933 return false;
3934 }
3935
3936 private static final class RequestFinishCallback extends IRequestFinishCallback.Stub {
3937 private final WeakReference<Activity> mActivityRef;
3938
3939 RequestFinishCallback(WeakReference<Activity> activityRef) {
3940 mActivityRef = activityRef;
3941 }
3942
3943 @Override
3944 public void requestFinish() {
3945 Activity activity = mActivityRef.get();
3946 if (activity != null) {
3947 activity.mHandler.post(activity::finishAfterTransition);
3948 }
3949 }
3950 }
3951
3952 /**
3953 * Called when the activity has detected the user's press of the back key. The default
3954 * implementation depends on the platform version:
3955 *
3956 * <ul>
3957 * <li>On platform versions prior to {@link android.os.Build.VERSION_CODES#S}, it
3958 * finishes the current activity, but you can override this to do whatever you want.
3959 *
3960 * <li><p>Starting with platform version {@link android.os.Build.VERSION_CODES#S}, for
3961 * activities that are the root activity of the task and also declare an
3962 * {@link android.content.IntentFilter} with {@link Intent#ACTION_MAIN} and
3963 * {@link Intent#CATEGORY_LAUNCHER} in the manifest, the current activity and its
3964 * task will be moved to the back of the activity stack instead of being finished.
3965 * Other activities will simply be finished.
3966 *
3967 * <li><p>If you target version {@link android.os.Build.VERSION_CODES#S} and
3968 * override this method, we strongly recommend to call through to the superclass
3969 * implementation after you finish handling navigation within the app.
3970 *
3971 * <li><p>If you target version {@link android.os.Build.VERSION_CODES#TIRAMISU} or later,
3972 * you should not use this method but register an {@link OnBackInvokedCallback} on an
3973 * {@link OnBackInvokedDispatcher} that you can retrieve using
3974 * {@link #getOnBackInvokedDispatcher()}. You should also set
3975 * {@code android:enableOnBackInvokedCallback="true"} in the application manifest.
3976 * <p>Alternatively, you can use
3977 * {@code androidx.activity.ComponentActivity#getOnBackPressedDispatcher()}
3978 * for backward compatibility.
3979 * </ul>
3980 *
3981 * @see #moveTaskToBack(boolean)
3982 *
3983 * @deprecated Use {@link OnBackInvokedCallback} or
3984 * {@code androidx.activity.OnBackPressedCallback} to handle back navigation instead.
3985 * <p>
3986 * Starting from Android 13 (API level 33), back event handling is
3987 * moving to an ahead-of-time model and {@link Activity#onBackPressed()} and
3988 * {@link KeyEvent#KEYCODE_BACK} should not be used to handle back events (back gesture or
3989 * back button click). Instead, an {@link OnBackInvokedCallback} should be registered using
3990 * {@link Activity#getOnBackInvokedDispatcher()}
3991 * {@link OnBackInvokedDispatcher#registerOnBackInvokedCallback(int, OnBackInvokedCallback)
3992 * .registerOnBackInvokedCallback(priority, callback)}.
3993 */
3994 @Deprecated
3995 public void onBackPressed() {
3996 if (mActionBar != null && mActionBar.collapseActionView()) {
3997 return;
3998 }
3999
4000 FragmentManager fragmentManager = mFragments.getFragmentManager();
4001
4002 if (!fragmentManager.isStateSaved() && fragmentManager.popBackStackImmediate()) {
4003 return;
4004 }
4005 onBackInvoked();
4006 }
4007
4008 private void onBackInvoked() {
4009 // Inform activity task manager that the activity received a back press.
4010 // This call allows ActivityTaskManager to intercept or move the task
4011 // to the back when needed.
4012 ActivityClient.getInstance().onBackPressed(mToken,
4013 new RequestFinishCallback(new WeakReference<>(this)));
4014
4015 if (isTaskRoot()) {
4016 getAutofillClientController().onActivityBackPressed(mIntent);
4017 }
4018 }
4019
4020 /**
4021 * Called when a key shortcut event is not handled by any of the views in the Activity.
4022 * Override this method to implement global key shortcuts for the Activity.
4023 * Key shortcuts can also be implemented by setting the
4024 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
4025 *
4026 * @param keyCode The value in event.getKeyCode().
4027 * @param event Description of the key event.
4028 * @return True if the key shortcut was handled.
4029 */
4030 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4031 // Let the Action Bar have a chance at handling the shortcut.
4032 ActionBar actionBar = getActionBar();
4033 return (actionBar != null && actionBar.onKeyShortcut(keyCode, event));
4034 }
4035
4036 /**
4037 * Called when a touch screen event was not handled by any of the views
4038 * under it. This is most useful to process touch events that happen
4039 * outside of your window bounds, where there is no view to receive it.
4040 *
4041 * @param event The touch screen event being processed.
4042 *
4043 * @return Return true if you have consumed the event, false if you haven't.
4044 * The default implementation always returns false.
4045 */
4046 public boolean onTouchEvent(MotionEvent event) {
4047 if (mWindow.shouldCloseOnTouch(this, event)) {
4048 finish();
4049 return true;
4050 }
4051
4052 return false;
4053 }
4054
4055 /**
4056 * Called when the trackball was moved and not handled by any of the
4057 * views inside of the activity. So, for example, if the trackball moves
4058 * while focus is on a button, you will receive a call here because
4059 * buttons do not normally do anything with trackball events. The call
4060 * here happens <em>before</em> trackball movements are converted to
4061 * DPAD key events, which then get sent back to the view hierarchy, and
4062 * will be processed at the point for things like focus navigation.
4063 *
4064 * @param event The trackball event being processed.
4065 *
4066 * @return Return true if you have consumed the event, false if you haven't.
4067 * The default implementation always returns false.
4068 */
4069 public boolean onTrackballEvent(MotionEvent event) {
4070 return false;
4071 }
4072
4073 /**
4074 * Called when a generic motion event was not handled by any of the
4075 * views inside of the activity.
4076 * <p>
4077 * Generic motion events describe joystick movements, mouse hovers, track pad
4078 * touches, scroll wheel movements and other input events. The
4079 * {@link MotionEvent#getSource() source} of the motion event specifies
4080 * the class of input that was received. Implementations of this method
4081 * must examine the bits in the source before processing the event.
4082 * The following code example shows how this is done.
4083 * </p><p>
4084 * Generic motion events with source class
4085 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
4086 * are delivered to the view under the pointer. All other generic motion events are
4087 * delivered to the focused view.
4088 * </p><p>
4089 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
4090 * handle this event.
4091 * </p>
4092 *
4093 * @param event The generic motion event being processed.
4094 *
4095 * @return Return true if you have consumed the event, false if you haven't.
4096 * The default implementation always returns false.
4097 */
4098 public boolean onGenericMotionEvent(MotionEvent event) {
4099 return false;
4100 }
4101
4102 /**
4103 * Called whenever a key, touch, or trackball event is dispatched to the
4104 * activity. Implement this method if you wish to know that the user has
4105 * interacted with the device in some way while your activity is running.
4106 * This callback and {@link #onUserLeaveHint} are intended to help
4107 * activities manage status bar notifications intelligently; specifically,
4108 * for helping activities determine the proper time to cancel a notification.
4109 *
4110 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
4111 * be accompanied by calls to {@link #onUserInteraction}. This
4112 * ensures that your activity will be told of relevant user activity such
4113 * as pulling down the notification pane and touching an item there.
4114 *
4115 * <p>Note that this callback will be invoked for the touch down action
4116 * that begins a touch gesture, but may not be invoked for the touch-moved
4117 * and touch-up actions that follow.
4118 *
4119 * @see #onUserLeaveHint()
4120 */
4121 public void onUserInteraction() {
4122 }
4123
4124 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
4125 // Update window manager if: we have a view, that view is
4126 // attached to its parent (which will be a RootView), and
4127 // this activity is not embedded.
4128 if (mParent == null) {
4129 View decor = mDecor;
4130 if (decor != null && decor.getParent() != null) {
4131 getWindowManager().updateViewLayout(decor, params);
4132 if (mContentCaptureManager != null) {
4133 mContentCaptureManager.updateWindowAttributes(params);
4134 }
4135 }
4136 }
4137 }
4138
4139 public void onContentChanged() {
4140 }
4141
4142 /**
4143 * Called when the current {@link Window} of the activity gains or loses
4144 * focus. This is the best indicator of whether this activity is the entity
4145 * with which the user actively interacts. The default implementation
4146 * clears the key tracking state, so should always be called.
4147 *
4148 * <p>Note that this provides information about global focus state, which
4149 * is managed independently of activity lifecycle. As such, while focus
4150 * changes will generally have some relation to lifecycle changes (an
4151 * activity that is stopped will not generally get window focus), you
4152 * should not rely on any particular order between the callbacks here and
4153 * those in the other lifecycle methods such as {@link #onResume}.
4154 *
4155 * <p>As a general rule, however, a foreground activity will have window
4156 * focus... unless it has displayed other dialogs or popups that take
4157 * input focus, in which case the activity itself will not have focus
4158 * when the other windows have it. Likewise, the system may display
4159 * system-level windows (such as the status bar notification panel or
4160 * a system alert) which will temporarily take window input focus without
4161 * pausing the foreground activity.
4162 *
4163 * <p>Starting with {@link android.os.Build.VERSION_CODES#Q} there can be
4164 * multiple resumed activities at the same time in multi-window mode, so
4165 * resumed state does not guarantee window focus even if there are no
4166 * overlays above.
4167 *
4168 * <p>If the intent is to know when an activity is the topmost active, the
4169 * one the user interacted with last among all activities but not including
4170 * non-activity windows like dialogs and popups, then
4171 * {@link #onTopResumedActivityChanged(boolean)} should be used. On platform
4172 * versions prior to {@link android.os.Build.VERSION_CODES#Q},
4173 * {@link #onResume} is the best indicator.
4174 *
4175 * @param hasFocus Whether the window of this activity has focus.
4176 *
4177 * @see #hasWindowFocus()
4178 * @see #onResume
4179 * @see View#onWindowFocusChanged(boolean)
4180 * @see #onTopResumedActivityChanged(boolean)
4181 */
4182 public void onWindowFocusChanged(boolean hasFocus) {
4183 }
4184
4185 /**
4186 * Called when the main window associated with the activity has been
4187 * attached to the window manager.
4188 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
4189 * for more information.
4190 * @see View#onAttachedToWindow
4191 */
4192 public void onAttachedToWindow() {
4193 }
4194
4195 /**
4196 * Called when the main window associated with the activity has been
4197 * detached from the window manager.
4198 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
4199 * for more information.
4200 * @see View#onDetachedFromWindow
4201 */
4202 public void onDetachedFromWindow() {
4203 }
4204
4205 /**
4206 * Returns true if this activity's <em>main</em> window currently has window focus.
4207 * Note that this is not the same as the view itself having focus.
4208 *
4209 * @return True if this activity's main window currently has window focus.
4210 *
4211 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
4212 */
4213 public boolean hasWindowFocus() {
4214 Window w = getWindow();
4215 if (w != null) {
4216 View d = w.getDecorView();
4217 if (d != null) {
4218 return d.hasWindowFocus();
4219 }
4220 }
4221 return false;
4222 }
4223
4224 /**
4225 * Called when the main window associated with the activity has been dismissed.
4226 * @hide
4227 */
4228 @Override
4229 public void onWindowDismissed(boolean finishTask, boolean suppressWindowTransition) {
4230 finish(finishTask ? FINISH_TASK_WITH_ACTIVITY : DONT_FINISH_TASK_WITH_ACTIVITY);
4231 if (suppressWindowTransition) {
4232 overridePendingTransition(0, 0);
4233 }
4234 }
4235
4236
4237 /**
4238 * Called to process key events. You can override this to intercept all
4239 * key events before they are dispatched to the window. Be sure to call
4240 * this implementation for key events that should be handled normally.
4241 *
4242 * @param event The key event.
4243 *
4244 * @return boolean Return true if this event was consumed.
4245 */
4246 public boolean dispatchKeyEvent(KeyEvent event) {
4247 onUserInteraction();
4248
4249 // Let action bars open menus in response to the menu key prioritized over
4250 // the window handling it
4251 final int keyCode = event.getKeyCode();
4252 if (keyCode == KeyEvent.KEYCODE_MENU &&
4253 mActionBar != null && mActionBar.onMenuKeyEvent(event)) {
4254 return true;
4255 }
4256
4257 Window win = getWindow();
4258 if (win.superDispatchKeyEvent(event)) {
4259 return true;
4260 }
4261 View decor = mDecor;
4262 if (decor == null) decor = win.getDecorView();
4263 return event.dispatch(this, decor != null
4264 ? decor.getKeyDispatcherState() : null, this);
4265 }
4266
4267 /**
4268 * Called to process a key shortcut event.
4269 * You can override this to intercept all key shortcut events before they are
4270 * dispatched to the window. Be sure to call this implementation for key shortcut
4271 * events that should be handled normally.
4272 *
4273 * @param event The key shortcut event.
4274 * @return True if this event was consumed.
4275 */
4276 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4277 onUserInteraction();
4278 if (getWindow().superDispatchKeyShortcutEvent(event)) {
4279 return true;
4280 }
4281 return onKeyShortcut(event.getKeyCode(), event);
4282 }
4283
4284 /**
4285 * Called to process touch screen events. You can override this to
4286 * intercept all touch screen events before they are dispatched to the
4287 * window. Be sure to call this implementation for touch screen events
4288 * that should be handled normally.
4289 *
4290 * @param ev The touch screen event.
4291 *
4292 * @return boolean Return true if this event was consumed.
4293 */
4294 public boolean dispatchTouchEvent(MotionEvent ev) {
4295 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
4296 onUserInteraction();
4297 }
4298 if (getWindow().superDispatchTouchEvent(ev)) {
4299 return true;
4300 }
4301 return onTouchEvent(ev);
4302 }
4303
4304 /**
4305 * Called to process trackball events. You can override this to
4306 * intercept all trackball events before they are dispatched to the
4307 * window. Be sure to call this implementation for trackball events
4308 * that should be handled normally.
4309 *
4310 * @param ev The trackball event.
4311 *
4312 * @return boolean Return true if this event was consumed.
4313 */
4314 public boolean dispatchTrackballEvent(MotionEvent ev) {
4315 onUserInteraction();
4316 if (getWindow().superDispatchTrackballEvent(ev)) {
4317 return true;
4318 }
4319 return onTrackballEvent(ev);
4320 }
4321
4322 /**
4323 * Called to process generic motion events. You can override this to
4324 * intercept all generic motion events before they are dispatched to the
4325 * window. Be sure to call this implementation for generic motion events
4326 * that should be handled normally.
4327 *
4328 * @param ev The generic motion event.
4329 *
4330 * @return boolean Return true if this event was consumed.
4331 */
4332 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
4333 onUserInteraction();
4334 if (getWindow().superDispatchGenericMotionEvent(ev)) {
4335 return true;
4336 }
4337 return onGenericMotionEvent(ev);
4338 }
4339
4340 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4341 event.setClassName(getClass().getName());
4342 event.setPackageName(getPackageName());
4343
4344 LayoutParams params = getWindow().getAttributes();
4345 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
4346 (params.height == LayoutParams.MATCH_PARENT);
4347 event.setFullScreen(isFullScreen);
4348
4349 CharSequence title = getTitle();
4350 if (!TextUtils.isEmpty(title)) {
4351 event.getText().add(title);
4352 }
4353
4354 return true;
4355 }
4356
4357 /**
4358 * Default implementation of
4359 * {@link android.view.Window.Callback#onCreatePanelView}
4360 * for activities. This
4361 * simply returns null so that all panel sub-windows will have the default
4362 * menu behavior.
4363 */
4364 @Nullable
4365 public View onCreatePanelView(int featureId) {
4366 return null;
4367 }
4368
4369 /**
4370 * Default implementation of
4371 * {@link android.view.Window.Callback#onCreatePanelMenu}
4372 * for activities. This calls through to the new
4373 * {@link #onCreateOptionsMenu} method for the
4374 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
4375 * so that subclasses of Activity don't need to deal with feature codes.
4376 */
4377 public boolean onCreatePanelMenu(int featureId, @NonNull Menu menu) {
4378 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
4379 boolean show = onCreateOptionsMenu(menu);
4380 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
4381 return show;
4382 }
4383 return false;
4384 }
4385
4386 /**
4387 * Default implementation of
4388 * {@link android.view.Window.Callback#onPreparePanel}
4389 * for activities. This
4390 * calls through to the new {@link #onPrepareOptionsMenu} method for the
4391 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
4392 * panel, so that subclasses of
4393 * Activity don't need to deal with feature codes.
4394 */
4395 public boolean onPreparePanel(int featureId, @Nullable View view, @NonNull Menu menu) {
4396 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
4397 boolean goforit = onPrepareOptionsMenu(menu);
4398 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
4399 return goforit;
4400 }
4401 return true;
4402 }
4403
4404 /**
4405 * {@inheritDoc}
4406 *
4407 * @return The default implementation returns true.
4408 */
4409 @Override
4410 public boolean onMenuOpened(int featureId, @NonNull Menu menu) {
4411 if (featureId == Window.FEATURE_ACTION_BAR) {
4412 initWindowDecorActionBar();
4413 if (mActionBar != null) {
4414 mActionBar.dispatchMenuVisibilityChanged(true);
4415 } else {
4416 Log.e(TAG, "Tried to open action bar menu with no action bar");
4417 }
4418 }
4419 return true;
4420 }
4421
4422 /**
4423 * Default implementation of
4424 * {@link android.view.Window.Callback#onMenuItemSelected}
4425 * for activities. This calls through to the new
4426 * {@link #onOptionsItemSelected} method for the
4427 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
4428 * panel, so that subclasses of
4429 * Activity don't need to deal with feature codes.
4430 */
4431 public boolean onMenuItemSelected(int featureId, @NonNull MenuItem item) {
4432 CharSequence titleCondensed = item.getTitleCondensed();
4433
4434 switch (featureId) {
4435 case Window.FEATURE_OPTIONS_PANEL:
4436 // Put event logging here so it gets called even if subclass
4437 // doesn't call through to superclass's implmeentation of each
4438 // of these methods below
4439 if(titleCondensed != null) {
4440 EventLog.writeEvent(50000, 0, titleCondensed.toString());
4441 }
4442 if (onOptionsItemSelected(item)) {
4443 return true;
4444 }
4445 if (mFragments.dispatchOptionsItemSelected(item)) {
4446 return true;
4447 }
4448 if (item.getItemId() == android.R.id.home && mActionBar != null &&
4449 (mActionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
4450 if (mParent == null) {
4451 return onNavigateUp();
4452 } else {
4453 return mParent.onNavigateUpFromChild(this);
4454 }
4455 }
4456 return false;
4457
4458 case Window.FEATURE_CONTEXT_MENU:
4459 if(titleCondensed != null) {
4460 EventLog.writeEvent(50000, 1, titleCondensed.toString());
4461 }
4462 if (onContextItemSelected(item)) {
4463 return true;
4464 }
4465 return mFragments.dispatchContextItemSelected(item);
4466
4467 default:
4468 return false;
4469 }
4470 }
4471
4472 /**
4473 * Default implementation of
4474 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
4475 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
4476 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
4477 * so that subclasses of Activity don't need to deal with feature codes.
4478 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
4479 * {@link #onContextMenuClosed(Menu)} will be called.
4480 */
4481 public void onPanelClosed(int featureId, @NonNull Menu menu) {
4482 switch (featureId) {
4483 case Window.FEATURE_OPTIONS_PANEL:
4484 mFragments.dispatchOptionsMenuClosed(menu);
4485 onOptionsMenuClosed(menu);
4486 break;
4487
4488 case Window.FEATURE_CONTEXT_MENU:
4489 onContextMenuClosed(menu);
4490 break;
4491
4492 case Window.FEATURE_ACTION_BAR:
4493 initWindowDecorActionBar();
4494 mActionBar.dispatchMenuVisibilityChanged(false);
4495 break;
4496 }
4497 }
4498
4499 /**
4500 * Declare that the options menu has changed, so should be recreated.
4501 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
4502 * time it needs to be displayed.
4503 */
4504 public void invalidateOptionsMenu() {
4505 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
4506 (mActionBar == null || !mActionBar.invalidateOptionsMenu())) {
4507 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
4508 }
4509 }
4510
4511 /**
4512 * Initialize the contents of the Activity's standard options menu. You
4513 * should place your menu items in to <var>menu</var>.
4514 *
4515 * <p>This is only called once, the first time the options menu is
4516 * displayed. To update the menu every time it is displayed, see
4517 * {@link #onPrepareOptionsMenu}.
4518 *
4519 * <p>The default implementation populates the menu with standard system
4520 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
4521 * they will be correctly ordered with application-defined menu items.
4522 * Deriving classes should always call through to the base implementation.
4523 *
4524 * <p>You can safely hold on to <var>menu</var> (and any items created
4525 * from it), making modifications to it as desired, until the next
4526 * time onCreateOptionsMenu() is called.
4527 *
4528 * <p>When you add items to the menu, you can implement the Activity's
4529 * {@link #onOptionsItemSelected} method to handle them there.
4530 *
4531 * @param menu The options menu in which you place your items.
4532 *
4533 * @return You must return true for the menu to be displayed;
4534 * if you return false it will not be shown.
4535 *
4536 * @see #onPrepareOptionsMenu
4537 * @see #onOptionsItemSelected
4538 */
4539 public boolean onCreateOptionsMenu(Menu menu) {
4540 if (mParent != null) {
4541 return mParent.onCreateOptionsMenu(menu);
4542 }
4543 return true;
4544 }
4545
4546 /**
4547 * Prepare the Screen's standard options menu to be displayed. This is
4548 * called right before the menu is shown, every time it is shown. You can
4549 * use this method to efficiently enable/disable items or otherwise
4550 * dynamically modify the contents.
4551 *
4552 * <p>The default implementation updates the system menu items based on the
4553 * activity's state. Deriving classes should always call through to the
4554 * base class implementation.
4555 *
4556 * @param menu The options menu as last shown or first initialized by
4557 * onCreateOptionsMenu().
4558 *
4559 * @return You must return true for the menu to be displayed;
4560 * if you return false it will not be shown.
4561 *
4562 * @see #onCreateOptionsMenu
4563 */
4564 public boolean onPrepareOptionsMenu(Menu menu) {
4565 if (mParent != null) {
4566 return mParent.onPrepareOptionsMenu(menu);
4567 }
4568 return true;
4569 }
4570
4571 /**
4572 * This hook is called whenever an item in your options menu is selected.
4573 * The default implementation simply returns false to have the normal
4574 * processing happen (calling the item's Runnable or sending a message to
4575 * its Handler as appropriate). You can use this method for any items
4576 * for which you would like to do processing without those other
4577 * facilities.
4578 *
4579 * <p>Derived classes should call through to the base class for it to
4580 * perform the default menu handling.</p>
4581 *
4582 * @param item The menu item that was selected.
4583 *
4584 * @return boolean Return false to allow normal menu processing to
4585 * proceed, true to consume it here.
4586 *
4587 * @see #onCreateOptionsMenu
4588 */
4589 public boolean onOptionsItemSelected(@NonNull MenuItem item) {
4590 if (mParent != null) {
4591 return mParent.onOptionsItemSelected(item);
4592 }
4593 return false;
4594 }
4595
4596 /**
4597 * This method is called whenever the user chooses to navigate Up within your application's
4598 * activity hierarchy from the action bar.
4599 *
4600 * <p>If the attribute {@link android.R.attr#parentActivityName parentActivityName}
4601 * was specified in the manifest for this activity or an activity-alias to it,
4602 * default Up navigation will be handled automatically. If any activity
4603 * along the parent chain requires extra Intent arguments, the Activity subclass
4604 * should override the method {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}
4605 * to supply those arguments.</p>
4606 *
4607 * <p>See <a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>
4608 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
4609 * from the design guide for more information about navigating within your app.</p>
4610 *
4611 * <p>See the {@link TaskStackBuilder} class and the Activity methods
4612 * {@link #getParentActivityIntent()}, {@link #shouldUpRecreateTask(Intent)}, and
4613 * {@link #navigateUpTo(Intent)} for help implementing custom Up navigation.
4614 * The AppNavigation sample application in the Android SDK is also available for reference.</p>
4615 *
4616 * @return true if Up navigation completed successfully and this Activity was finished,
4617 * false otherwise.
4618 */
4619 public boolean onNavigateUp() {
4620 // Automatically handle hierarchical Up navigation if the proper
4621 // metadata is available.
4622 Intent upIntent = getParentActivityIntent();
4623 if (upIntent != null) {
4624 if (mActivityInfo.taskAffinity == null) {
4625 // Activities with a null affinity are special; they really shouldn't
4626 // specify a parent activity intent in the first place. Just finish
4627 // the current activity and call it a day.
4628 finish();
4629 } else if (shouldUpRecreateTask(upIntent)) {
4630 TaskStackBuilder b = TaskStackBuilder.create(this);
4631 onCreateNavigateUpTaskStack(b);
4632 onPrepareNavigateUpTaskStack(b);
4633 b.startActivities();
4634
4635 // We can't finishAffinity if we have a result.
4636 // Fall back and simply finish the current activity instead.
4637 if (mResultCode != RESULT_CANCELED || mResultData != null) {
4638 // Tell the developer what's going on to avoid hair-pulling.
4639 Log.i(TAG, "onNavigateUp only finishing topmost activity to return a result");
4640 finish();
4641 } else {
4642 finishAffinity();
4643 }
4644 } else {
4645 navigateUpTo(upIntent);
4646 }
4647 return true;
4648 }
4649 return false;
4650 }
4651
4652 /**
4653 * This is called when a child activity of this one attempts to navigate up.
4654 * The default implementation simply calls onNavigateUp() on this activity (the parent).
4655 *
4656 * @param child The activity making the call.
4657 * @deprecated Use {@link #onNavigateUp()} instead.
4658 */
4659 @Deprecated
4660 public boolean onNavigateUpFromChild(Activity child) {
4661 return onNavigateUp();
4662 }
4663
4664 /**
4665 * Define the synthetic task stack that will be generated during Up navigation from
4666 * a different task.
4667 *
4668 * <p>The default implementation of this method adds the parent chain of this activity
4669 * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications
4670 * may choose to override this method to construct the desired task stack in a different
4671 * way.</p>
4672 *
4673 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
4674 * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent
4675 * returned by {@link #getParentActivityIntent()}.</p>
4676 *
4677 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
4678 * by the manifest should override {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}.</p>
4679 *
4680 * @param builder An empty TaskStackBuilder - the application should add intents representing
4681 * the desired task stack
4682 */
4683 public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) {
4684 builder.addParentStack(this);
4685 }
4686
4687 /**
4688 * Prepare the synthetic task stack that will be generated during Up navigation
4689 * from a different task.
4690 *
4691 * <p>This method receives the {@link TaskStackBuilder} with the constructed series of
4692 * Intents as generated by {@link #onCreateNavigateUpTaskStack(TaskStackBuilder)}.
4693 * If any extra data should be added to these intents before launching the new task,
4694 * the application should override this method and add that data here.</p>
4695 *
4696 * @param builder A TaskStackBuilder that has been populated with Intents by
4697 * onCreateNavigateUpTaskStack.
4698 */
4699 public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) {
4700 }
4701
4702 /**
4703 * This hook is called whenever the options menu is being closed (either by the user canceling
4704 * the menu with the back/menu button, or when an item is selected).
4705 *
4706 * @param menu The options menu as last shown or first initialized by
4707 * onCreateOptionsMenu().
4708 */
4709 public void onOptionsMenuClosed(Menu menu) {
4710 if (mParent != null) {
4711 mParent.onOptionsMenuClosed(menu);
4712 }
4713 }
4714
4715 /**
4716 * Programmatically opens the options menu. If the options menu is already
4717 * open, this method does nothing.
4718 */
4719 public void openOptionsMenu() {
4720 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
4721 (mActionBar == null || !mActionBar.openOptionsMenu())) {
4722 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
4723 }
4724 }
4725
4726 /**
4727 * Progammatically closes the options menu. If the options menu is already
4728 * closed, this method does nothing.
4729 */
4730 public void closeOptionsMenu() {
4731 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
4732 (mActionBar == null || !mActionBar.closeOptionsMenu())) {
4733 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
4734 }
4735 }
4736
4737 /**
4738 * Called when a context menu for the {@code view} is about to be shown.
4739 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
4740 * time the context menu is about to be shown and should be populated for
4741 * the view (or item inside the view for {@link AdapterView} subclasses,
4742 * this can be found in the {@code menuInfo})).
4743 * <p>
4744 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
4745 * item has been selected.
4746 * <p>
4747 * It is not safe to hold onto the context menu after this method returns.
4748 *
4749 */
4750 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
4751 }
4752
4753 /**
4754 * Registers a context menu to be shown for the given view (multiple views
4755 * can show the context menu). This method will set the
4756 * {@link OnCreateContextMenuListener} on the view to this activity, so
4757 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
4758 * called when it is time to show the context menu.
4759 *
4760 * @see #unregisterForContextMenu(View)
4761 * @param view The view that should show a context menu.
4762 */
4763 public void registerForContextMenu(View view) {
4764 view.setOnCreateContextMenuListener(this);
4765 }
4766
4767 /**
4768 * Prevents a context menu to be shown for the given view. This method will remove the
4769 * {@link OnCreateContextMenuListener} on the view.
4770 *
4771 * @see #registerForContextMenu(View)
4772 * @param view The view that should stop showing a context menu.
4773 */
4774 public void unregisterForContextMenu(View view) {
4775 view.setOnCreateContextMenuListener(null);
4776 }
4777
4778 /**
4779 * Programmatically opens the context menu for a particular {@code view}.
4780 * The {@code view} should have been added via
4781 * {@link #registerForContextMenu(View)}.
4782 *
4783 * @param view The view to show the context menu for.
4784 */
4785 public void openContextMenu(View view) {
4786 view.showContextMenu();
4787 }
4788
4789 /**
4790 * Programmatically closes the most recently opened context menu, if showing.
4791 */
4792 public void closeContextMenu() {
4793 if (mWindow.hasFeature(Window.FEATURE_CONTEXT_MENU)) {
4794 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
4795 }
4796 }
4797
4798 /**
4799 * This hook is called whenever an item in a context menu is selected. The
4800 * default implementation simply returns false to have the normal processing
4801 * happen (calling the item's Runnable or sending a message to its Handler
4802 * as appropriate). You can use this method for any items for which you
4803 * would like to do processing without those other facilities.
4804 * <p>
4805 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
4806 * View that added this menu item.
4807 * <p>
4808 * Derived classes should call through to the base class for it to perform
4809 * the default menu handling.
4810 *
4811 * @param item The context menu item that was selected.
4812 * @return boolean Return false to allow normal context menu processing to
4813 * proceed, true to consume it here.
4814 */
4815 public boolean onContextItemSelected(@NonNull MenuItem item) {
4816 if (mParent != null) {
4817 return mParent.onContextItemSelected(item);
4818 }
4819 return false;
4820 }
4821
4822 /**
4823 * This hook is called whenever the context menu is being closed (either by
4824 * the user canceling the menu with the back/menu button, or when an item is
4825 * selected).
4826 *
4827 * @param menu The context menu that is being closed.
4828 */
4829 public void onContextMenuClosed(@NonNull Menu menu) {
4830 if (mParent != null) {
4831 mParent.onContextMenuClosed(menu);
4832 }
4833 }
4834
4835 /**
4836 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
4837 */
4838 @Deprecated
4839 protected Dialog onCreateDialog(int id) {
4840 return null;
4841 }
4842
4843 /**
4844 * Callback for creating dialogs that are managed (saved and restored) for you
4845 * by the activity. The default implementation calls through to
4846 * {@link #onCreateDialog(int)} for compatibility.
4847 *
4848 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
4849 * or later, consider instead using a {@link DialogFragment} instead.</em>
4850 *
4851 * <p>If you use {@link #showDialog(int)}, the activity will call through to
4852 * this method the first time, and hang onto it thereafter. Any dialog
4853 * that is created by this method will automatically be saved and restored
4854 * for you, including whether it is showing.
4855 *
4856 * <p>If you would like the activity to manage saving and restoring dialogs
4857 * for you, you should override this method and handle any ids that are
4858 * passed to {@link #showDialog}.
4859 *
4860 * <p>If you would like an opportunity to prepare your dialog before it is shown,
4861 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
4862 *
4863 * @param id The id of the dialog.
4864 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
4865 * @return The dialog. If you return null, the dialog will not be created.
4866 *
4867 * @see #onPrepareDialog(int, Dialog, Bundle)
4868 * @see #showDialog(int, Bundle)
4869 * @see #dismissDialog(int)
4870 * @see #removeDialog(int)
4871 *
4872 * @deprecated Use the new {@link DialogFragment} class with
4873 * {@link FragmentManager} instead; this is also
4874 * available on older platforms through the Android compatibility package.
4875 */
4876 @Nullable
4877 @Deprecated
4878 protected Dialog onCreateDialog(int id, Bundle args) {
4879 return onCreateDialog(id);
4880 }
4881
4882 /**
4883 * @deprecated Old no-arguments version of
4884 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
4885 */
4886 @Deprecated
4887 protected void onPrepareDialog(int id, Dialog dialog) {
4888 dialog.setOwnerActivity(this);
4889 }
4890
4891 /**
4892 * Provides an opportunity to prepare a managed dialog before it is being
4893 * shown. The default implementation calls through to
4894 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
4895 *
4896 * <p>
4897 * Override this if you need to update a managed dialog based on the state
4898 * of the application each time it is shown. For example, a time picker
4899 * dialog might want to be updated with the current time. You should call
4900 * through to the superclass's implementation. The default implementation
4901 * will set this Activity as the owner activity on the Dialog.
4902 *
4903 * @param id The id of the managed dialog.
4904 * @param dialog The dialog.
4905 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
4906 * @see #onCreateDialog(int, Bundle)
4907 * @see #showDialog(int)
4908 * @see #dismissDialog(int)
4909 * @see #removeDialog(int)
4910 *
4911 * @deprecated Use the new {@link DialogFragment} class with
4912 * {@link FragmentManager} instead; this is also
4913 * available on older platforms through the Android compatibility package.
4914 */
4915 @Deprecated
4916 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
4917 onPrepareDialog(id, dialog);
4918 }
4919
4920 /**
4921 * Simple version of {@link #showDialog(int, Bundle)} that does not
4922 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
4923 * with null arguments.
4924 *
4925 * @deprecated Use the new {@link DialogFragment} class with
4926 * {@link FragmentManager} instead; this is also
4927 * available on older platforms through the Android compatibility package.
4928 */
4929 @Deprecated
4930 public final void showDialog(int id) {
4931 showDialog(id, null);
4932 }
4933
4934 /**
4935 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
4936 * will be made with the same id the first time this is called for a given
4937 * id. From thereafter, the dialog will be automatically saved and restored.
4938 *
4939 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
4940 * or later, consider instead using a {@link DialogFragment} instead.</em>
4941 *
4942 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
4943 * be made to provide an opportunity to do any timely preparation.
4944 *
4945 * @param id The id of the managed dialog.
4946 * @param args Arguments to pass through to the dialog. These will be saved
4947 * and restored for you. Note that if the dialog is already created,
4948 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
4949 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
4950 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
4951 * @return Returns true if the Dialog was created; false is returned if
4952 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
4953 *
4954 * @see Dialog
4955 * @see #onCreateDialog(int, Bundle)
4956 * @see #onPrepareDialog(int, Dialog, Bundle)
4957 * @see #dismissDialog(int)
4958 * @see #removeDialog(int)
4959 *
4960 * @deprecated Use the new {@link DialogFragment} class with
4961 * {@link FragmentManager} instead; this is also
4962 * available on older platforms through the Android compatibility package.
4963 */
4964 @Deprecated
4965 public final boolean showDialog(int id, Bundle args) {
4966 if (mManagedDialogs == null) {
4967 mManagedDialogs = new SparseArray<ManagedDialog>();
4968 }
4969 ManagedDialog md = mManagedDialogs.get(id);
4970 if (md == null) {
4971 md = new ManagedDialog();
4972 md.mDialog = createDialog(id, null, args);
4973 if (md.mDialog == null) {
4974 return false;
4975 }
4976 mManagedDialogs.put(id, md);
4977 }
4978
4979 md.mArgs = args;
4980 onPrepareDialog(id, md.mDialog, args);
4981 md.mDialog.show();
4982 return true;
4983 }
4984
4985 /**
4986 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
4987 *
4988 * @param id The id of the managed dialog.
4989 *
4990 * @throws IllegalArgumentException if the id was not previously shown via
4991 * {@link #showDialog(int)}.
4992 *
4993 * @see #onCreateDialog(int, Bundle)
4994 * @see #onPrepareDialog(int, Dialog, Bundle)
4995 * @see #showDialog(int)
4996 * @see #removeDialog(int)
4997 *
4998 * @deprecated Use the new {@link DialogFragment} class with
4999 * {@link FragmentManager} instead; this is also
5000 * available on older platforms through the Android compatibility package.
5001 */
5002 @Deprecated
5003 public final void dismissDialog(int id) {
5004 if (mManagedDialogs == null) {
5005 throw missingDialog(id);
5006 }
5007
5008 final ManagedDialog md = mManagedDialogs.get(id);
5009 if (md == null) {
5010 throw missingDialog(id);
5011 }
5012 md.mDialog.dismiss();
5013 }
5014
5015 /**
5016 * Creates an exception to throw if a user passed in a dialog id that is
5017 * unexpected.
5018 */
5019 private IllegalArgumentException missingDialog(int id) {
5020 return new IllegalArgumentException("no dialog with id " + id + " was ever "
5021 + "shown via Activity#showDialog");
5022 }
5023
5024 /**
5025 * Removes any internal references to a dialog managed by this Activity.
5026 * If the dialog is showing, it will dismiss it as part of the clean up.
5027 *
5028 * <p>This can be useful if you know that you will never show a dialog again and
5029 * want to avoid the overhead of saving and restoring it in the future.
5030 *
5031 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
5032 * will not throw an exception if you try to remove an ID that does not
5033 * currently have an associated dialog.</p>
5034 *
5035 * @param id The id of the managed dialog.
5036 *
5037 * @see #onCreateDialog(int, Bundle)
5038 * @see #onPrepareDialog(int, Dialog, Bundle)
5039 * @see #showDialog(int)
5040 * @see #dismissDialog(int)
5041 *
5042 * @deprecated Use the new {@link DialogFragment} class with
5043 * {@link FragmentManager} instead; this is also
5044 * available on older platforms through the Android compatibility package.
5045 */
5046 @Deprecated
5047 public final void removeDialog(int id) {
5048 if (mManagedDialogs != null) {
5049 final ManagedDialog md = mManagedDialogs.get(id);
5050 if (md != null) {
5051 md.mDialog.dismiss();
5052 mManagedDialogs.remove(id);
5053 }
5054 }
5055 }
5056
5057 /**
5058 * This hook is called when the user signals the desire to start a search.
5059 *
5060 * <p>You can use this function as a simple way to launch the search UI, in response to a
5061 * menu item, search button, or other widgets within your activity. Unless overidden,
5062 * calling this function is the same as calling
5063 * {@link #startSearch startSearch(null, false, null, false)}, which launches
5064 * search for the current activity as specified in its manifest, see {@link SearchManager}.
5065 *
5066 * <p>You can override this function to force global search, e.g. in response to a dedicated
5067 * search key, or to block search entirely (by simply returning false).
5068 *
5069 * <p>Note: when running in a {@link Configuration#UI_MODE_TYPE_TELEVISION} or
5070 * {@link Configuration#UI_MODE_TYPE_WATCH}, the default implementation changes to simply
5071 * return false and you must supply your own custom implementation if you want to support
5072 * search.
5073 *
5074 * @param searchEvent The {@link SearchEvent} that signaled this search.
5075 * @return Returns {@code true} if search launched, and {@code false} if the activity does
5076 * not respond to search. The default implementation always returns {@code true}, except
5077 * when in {@link Configuration#UI_MODE_TYPE_TELEVISION} mode where it returns false.
5078 *
5079 * @see android.app.SearchManager
5080 */
5081 public boolean onSearchRequested(@Nullable SearchEvent searchEvent) {
5082 mSearchEvent = searchEvent;
5083 boolean result = onSearchRequested();
5084 mSearchEvent = null;
5085 return result;
5086 }
5087
5088 /**
5089 * @see #onSearchRequested(SearchEvent)
5090 */
5091 public boolean onSearchRequested() {
5092 final int uiMode = getResources().getConfiguration().uiMode
5093 & Configuration.UI_MODE_TYPE_MASK;
5094 if (uiMode != Configuration.UI_MODE_TYPE_TELEVISION
5095 && uiMode != Configuration.UI_MODE_TYPE_WATCH) {
5096 startSearch(null, false, null, false);
5097 return true;
5098 } else {
5099 return false;
5100 }
5101 }
5102
5103 /**
5104 * During the onSearchRequested() callbacks, this function will return the
5105 * {@link SearchEvent} that triggered the callback, if it exists.
5106 *
5107 * @return SearchEvent The SearchEvent that triggered the {@link
5108 * #onSearchRequested} callback.
5109 */
5110 public final SearchEvent getSearchEvent() {
5111 return mSearchEvent;
5112 }
5113
5114 /**
5115 * This hook is called to launch the search UI.
5116 *
5117 * <p>It is typically called from onSearchRequested(), either directly from
5118 * Activity.onSearchRequested() or from an overridden version in any given
5119 * Activity. If your goal is simply to activate search, it is preferred to call
5120 * onSearchRequested(), which may have been overridden elsewhere in your Activity. If your goal
5121 * is to inject specific data such as context data, it is preferred to <i>override</i>
5122 * onSearchRequested(), so that any callers to it will benefit from the override.
5123 *
5124 * <p>Note: when running in a {@link Configuration#UI_MODE_TYPE_WATCH}, use of this API is
5125 * not supported.
5126 *
5127 * @param initialQuery Any non-null non-empty string will be inserted as
5128 * pre-entered text in the search query box.
5129 * @param selectInitialQuery If true, the initial query will be preselected, which means that
5130 * any further typing will replace it. This is useful for cases where an entire pre-formed
5131 * query is being inserted. If false, the selection point will be placed at the end of the
5132 * inserted query. This is useful when the inserted query is text that the user entered,
5133 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
5134 * if initialQuery is a non-empty string.</i>
5135 * @param appSearchData An application can insert application-specific
5136 * context here, in order to improve quality or specificity of its own
5137 * searches. This data will be returned with SEARCH intent(s). Null if
5138 * no extra data is required.
5139 * @param globalSearch If false, this will only launch the search that has been specifically
5140 * defined by the application (which is usually defined as a local search). If no default
5141 * search is defined in the current application or activity, global search will be launched.
5142 * If true, this will always launch a platform-global (e.g. web-based) search instead.
5143 *
5144 * @see android.app.SearchManager
5145 * @see #onSearchRequested
5146 */
5147 public void startSearch(@Nullable String initialQuery, boolean selectInitialQuery,
5148 @Nullable Bundle appSearchData, boolean globalSearch) {
5149 ensureSearchManager();
5150 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
5151 appSearchData, globalSearch);
5152 }
5153
5154 /**
5155 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
5156 * the search dialog. Made available for testing purposes.
5157 *
5158 * @param query The query to trigger. If empty, the request will be ignored.
5159 * @param appSearchData An application can insert application-specific
5160 * context here, in order to improve quality or specificity of its own
5161 * searches. This data will be returned with SEARCH intent(s). Null if
5162 * no extra data is required.
5163 */
5164 public void triggerSearch(String query, @Nullable Bundle appSearchData) {
5165 ensureSearchManager();
5166 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
5167 }
5168
5169 /**
5170 * Request that key events come to this activity. Use this if your
5171 * activity has no views with focus, but the activity still wants
5172 * a chance to process key events.
5173 *
5174 * @see android.view.Window#takeKeyEvents
5175 */
5176 public void takeKeyEvents(boolean get) {
5177 getWindow().takeKeyEvents(get);
5178 }
5179
5180 /**
5181 * Enable extended window features. This is a convenience for calling
5182 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
5183 *
5184 * @param featureId The desired feature as defined in
5185 * {@link android.view.Window}.
5186 * @return Returns true if the requested feature is supported and now
5187 * enabled.
5188 *
5189 * @see android.view.Window#requestFeature
5190 */
5191 public final boolean requestWindowFeature(int featureId) {
5192 return getWindow().requestFeature(featureId);
5193 }
5194
5195 /**
5196 * Convenience for calling
5197 * {@link android.view.Window#setFeatureDrawableResource}.
5198 */
5199 public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) {
5200 getWindow().setFeatureDrawableResource(featureId, resId);
5201 }
5202
5203 /**
5204 * Convenience for calling
5205 * {@link android.view.Window#setFeatureDrawableUri}.
5206 */
5207 public final void setFeatureDrawableUri(int featureId, Uri uri) {
5208 getWindow().setFeatureDrawableUri(featureId, uri);
5209 }
5210
5211 /**
5212 * Convenience for calling
5213 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
5214 */
5215 public final void setFeatureDrawable(int featureId, Drawable drawable) {
5216 getWindow().setFeatureDrawable(featureId, drawable);
5217 }
5218
5219 /**
5220 * Convenience for calling
5221 * {@link android.view.Window#setFeatureDrawableAlpha}.
5222 */
5223 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
5224 getWindow().setFeatureDrawableAlpha(featureId, alpha);
5225 }
5226
5227 /**
5228 * Convenience for calling
5229 * {@link android.view.Window#getLayoutInflater}.
5230 */
5231 @NonNull
5232 public LayoutInflater getLayoutInflater() {
5233 return getWindow().getLayoutInflater();
5234 }
5235
5236 /**
5237 * Returns a {@link MenuInflater} with this context.
5238 */
5239 @NonNull
5240 public MenuInflater getMenuInflater() {
5241 // Make sure that action views can get an appropriate theme.
5242 if (mMenuInflater == null) {
5243 initWindowDecorActionBar();
5244 if (mActionBar != null) {
5245 mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this);
5246 } else {
5247 mMenuInflater = new MenuInflater(this);
5248 }
5249 }
5250 return mMenuInflater;
5251 }
5252
5253 @Override
5254 public void setTheme(int resid) {
5255 super.setTheme(resid);
5256 mWindow.setTheme(resid);
5257 }
5258
5259 @Override
5260 protected void onApplyThemeResource(Resources.Theme theme, @StyleRes int resid,
5261 boolean first) {
5262 if (mParent == null) {
5263 super.onApplyThemeResource(theme, resid, first);
5264 } else {
5265 try {
5266 theme.setTo(mParent.getTheme());
5267 } catch (Exception e) {
5268 // Empty
5269 }
5270 theme.applyStyle(resid, false);
5271 }
5272
5273 // Get the primary color and update the TaskDescription for this activity
5274 TypedArray a = theme.obtainStyledAttributes(
5275 com.android.internal.R.styleable.ActivityTaskDescription);
5276 if (mTaskDescription.getPrimaryColor() == 0) {
5277 int colorPrimary = a.getColor(
5278 com.android.internal.R.styleable.ActivityTaskDescription_colorPrimary, 0);
5279 if (colorPrimary != 0 && Color.alpha(colorPrimary) == 0xFF) {
5280 mTaskDescription.setPrimaryColor(colorPrimary);
5281 }
5282 }
5283
5284 int colorBackground = a.getColor(
5285 com.android.internal.R.styleable.ActivityTaskDescription_colorBackground, 0);
5286 if (colorBackground != 0 && Color.alpha(colorBackground) == 0xFF) {
5287 mTaskDescription.setBackgroundColor(colorBackground);
5288 }
5289
5290 int colorBackgroundFloating = a.getColor(
5291 com.android.internal.R.styleable.ActivityTaskDescription_colorBackgroundFloating,
5292 0);
5293 if (colorBackgroundFloating != 0 && Color.alpha(colorBackgroundFloating) == 0xFF) {
5294 mTaskDescription.setBackgroundColorFloating(colorBackgroundFloating);
5295 }
5296
5297 final int statusBarColor = a.getColor(
5298 com.android.internal.R.styleable.ActivityTaskDescription_statusBarColor, 0);
5299 if (statusBarColor != 0) {
5300 mTaskDescription.setStatusBarColor(statusBarColor);
5301 }
5302
5303 final int navigationBarColor = a.getColor(
5304 com.android.internal.R.styleable.ActivityTaskDescription_navigationBarColor, 0);
5305 if (navigationBarColor != 0) {
5306 mTaskDescription.setNavigationBarColor(navigationBarColor);
5307 }
5308
5309 final int targetSdk = getApplicationInfo().targetSdkVersion;
5310 final boolean targetPreQ = targetSdk < Build.VERSION_CODES.Q;
5311 if (!targetPreQ) {
5312 mTaskDescription.setEnsureStatusBarContrastWhenTransparent(a.getBoolean(
5313 R.styleable.ActivityTaskDescription_enforceStatusBarContrast,
5314 false));
5315 mTaskDescription.setEnsureNavigationBarContrastWhenTransparent(a.getBoolean(
5316 R.styleable
5317 .ActivityTaskDescription_enforceNavigationBarContrast,
5318 true));
5319 }
5320
5321 a.recycle();
5322 setTaskDescription(mTaskDescription);
5323 }
5324
5325 /**
5326 * Requests permissions to be granted to this application. These permissions
5327 * must be requested in your manifest, they should not be granted to your app,
5328 * and they should have protection level {@link
5329 * android.content.pm.PermissionInfo#PROTECTION_DANGEROUS dangerous}, regardless
5330 * whether they are declared by the platform or a third-party app.
5331 * <p>
5332 * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
5333 * are granted at install time if requested in the manifest. Signature permissions
5334 * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
5335 * install time if requested in the manifest and the signature of your app matches
5336 * the signature of the app declaring the permissions.
5337 * </p>
5338 * <p>
5339 * Call {@link #shouldShowRequestPermissionRationale(String)} before calling this API to
5340 * check if the system recommends to show a rationale UI before asking for a permission.
5341 * </p>
5342 * <p>
5343 * If your app does not have the requested permissions the user will be presented
5344 * with UI for accepting them. After the user has accepted or rejected the
5345 * requested permissions you will receive a callback on {@link
5346 * #onRequestPermissionsResult(int, String[], int[])} reporting whether the
5347 * permissions were granted or not.
5348 * </p>
5349 * <p>
5350 * Note that requesting a permission does not guarantee it will be granted and
5351 * your app should be able to run without having this permission.
5352 * </p>
5353 * <p>
5354 * This method may start an activity allowing the user to choose which permissions
5355 * to grant and which to reject. Hence, you should be prepared that your activity
5356 * may be paused and resumed. Further, granting some permissions may require
5357 * a restart of you application. In such a case, the system will recreate the
5358 * activity stack before delivering the result to {@link
5359 * #onRequestPermissionsResult(int, String[], int[])}.
5360 * </p>
5361 * <p>
5362 * When checking whether you have a permission you should use {@link
5363 * #checkSelfPermission(String)}.
5364 * </p>
5365 * <p>
5366 * You cannot request a permission if your activity sets {@link
5367 * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
5368 * <code>true</code> because in this case the activity would not receive
5369 * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}.
5370 * </p>
5371 * <p>
5372 * The <a href="https://github.com/android/permissions-samples">
5373 * RuntimePermissions</a> sample apps demonstrate how to use this method to
5374 * request permissions at run time.
5375 * </p>
5376 *
5377 * @param permissions The requested permissions. Must me non-null and not empty.
5378 * @param requestCode Application specific request code to match with a result
5379 * reported to {@link #onRequestPermissionsResult(int, String[], int[])}.
5380 * Should be >= 0.
5381 *
5382 * @throws IllegalArgumentException if requestCode is negative.
5383 *
5384 * @see #onRequestPermissionsResult(int, String[], int[])
5385 * @see #checkSelfPermission(String)
5386 * @see #shouldShowRequestPermissionRationale(String)
5387 */
5388 public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
5389 if (requestCode < 0) {
5390 throw new IllegalArgumentException("requestCode should be >= 0");
5391 }
5392
5393 if (mHasCurrentPermissionsRequest) {
5394 Log.w(TAG, "Can request only one set of permissions at a time");
5395 // Dispatch the callback with empty arrays which means a cancellation.
5396 onRequestPermissionsResult(requestCode, new String[0], new int[0]);
5397 return;
5398 }
5399
5400 if (!getAttributionSource().getRenouncedPermissions().isEmpty()) {
5401 final int permissionCount = permissions.length;
5402 for (int i = 0; i < permissionCount; i++) {
5403 if (getAttributionSource().getRenouncedPermissions().contains(permissions[i])) {
5404 throw new IllegalArgumentException("Cannot request renounced permission: "
5405 + permissions[i]);
5406 }
5407 }
5408 }
5409
5410 final Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
5411 startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
5412 mHasCurrentPermissionsRequest = true;
5413 }
5414
5415 /**
5416 * Callback for the result from requesting permissions. This method
5417 * is invoked for every call on {@link #requestPermissions(String[], int)}.
5418 * <p>
5419 * <strong>Note:</strong> It is possible that the permissions request interaction
5420 * with the user is interrupted. In this case you will receive empty permissions
5421 * and results arrays which should be treated as a cancellation.
5422 * </p>
5423 *
5424 * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
5425 * @param permissions The requested permissions. Never null.
5426 * @param grantResults The grant results for the corresponding permissions
5427 * which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
5428 * or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
5429 *
5430 * @see #requestPermissions(String[], int)
5431 */
5432 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
5433 @NonNull int[] grantResults) {
5434 /* callback - no nothing */
5435 }
5436
5437 /**
5438 * Gets whether you should show UI with rationale before requesting a permission.
5439 *
5440 * @param permission A permission your app wants to request.
5441 * @return Whether you should show permission rationale UI.
5442 *
5443 * @see #checkSelfPermission(String)
5444 * @see #requestPermissions(String[], int)
5445 * @see #onRequestPermissionsResult(int, String[], int[])
5446 */
5447 public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
5448 return getPackageManager().shouldShowRequestPermissionRationale(permission);
5449 }
5450
5451 /**
5452 * Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
5453 * with no options.
5454 *
5455 * @param intent The intent to start.
5456 * @param requestCode If >= 0, this code will be returned in
5457 * onActivityResult() when the activity exits.
5458 *
5459 * @throws android.content.ActivityNotFoundException
5460 *
5461 * @see #startActivity
5462 */
5463 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
5464 startActivityForResult(intent, requestCode, null);
5465 }
5466
5467 /**
5468 * Launch an activity for which you would like a result when it finished.
5469 * When this activity exits, your
5470 * onActivityResult() method will be called with the given requestCode.
5471 * Using a negative requestCode is the same as calling
5472 * {@link #startActivity} (the activity is not launched as a sub-activity).
5473 *
5474 * <p>Note that this method should only be used with Intent protocols
5475 * that are defined to return a result. In other protocols (such as
5476 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
5477 * not get the result when you expect. For example, if the activity you
5478 * are launching uses {@link Intent#FLAG_ACTIVITY_NEW_TASK}, it will not
5479 * run in your task and thus you will immediately receive a cancel result.
5480 *
5481 * <p>As a special case, if you call startActivityForResult() with a requestCode
5482 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
5483 * activity, then your window will not be displayed until a result is
5484 * returned back from the started activity. This is to avoid visible
5485 * flickering when redirecting to another activity.
5486 *
5487 * <p>This method throws {@link android.content.ActivityNotFoundException}
5488 * if there was no Activity found to run the given Intent.
5489 *
5490 * @param intent The intent to start.
5491 * @param requestCode If >= 0, this code will be returned in
5492 * onActivityResult() when the activity exits.
5493 * @param options Additional options for how the Activity should be started.
5494 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5495 * Context.startActivity(Intent, Bundle)} for more details.
5496 *
5497 * @throws android.content.ActivityNotFoundException
5498 *
5499 * @see #startActivity
5500 */
5501 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
5502 @Nullable Bundle options) {
5503 if (mParent == null) {
5504 options = transferSpringboardActivityOptions(options);
5505 Instrumentation.ActivityResult ar =
5506 mInstrumentation.execStartActivity(
5507 this, mMainThread.getApplicationThread(), mToken, this,
5508 intent, requestCode, options);
5509 if (ar != null) {
5510 mMainThread.sendActivityResult(
5511 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
5512 ar.getResultData());
5513 }
5514 if (requestCode >= 0) {
5515 // If this start is requesting a result, we can avoid making
5516 // the activity visible until the result is received. Setting
5517 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
5518 // activity hidden during this time, to avoid flickering.
5519 // This can only be done when a result is requested because
5520 // that guarantees we will get information back when the
5521 // activity is finished, no matter what happens to it.
5522 mStartedActivity = true;
5523 }
5524
5525 cancelInputsAndStartExitTransition(options);
5526 // TODO Consider clearing/flushing other event sources and events for child windows.
5527 } else {
5528 if (options != null) {
5529 mParent.startActivityFromChild(this, intent, requestCode, options);
5530 } else {
5531 // Note we want to go through this method for compatibility with
5532 // existing applications that may have overridden it.
5533 mParent.startActivityFromChild(this, intent, requestCode);
5534 }
5535 }
5536 }
5537
5538 /**
5539 * Cancels pending inputs and if an Activity Transition is to be run, starts the transition.
5540 *
5541 * @param options The ActivityOptions bundle used to start an Activity.
5542 */
5543 private void cancelInputsAndStartExitTransition(Bundle options) {
5544 final View decor = mWindow != null ? mWindow.peekDecorView() : null;
5545 if (decor != null) {
5546 decor.cancelPendingInputEvents();
5547 }
5548 if (options != null) {
5549 mActivityTransitionState.startExitOutTransition(this, options);
5550 }
5551 }
5552
5553 /**
5554 * Returns whether there are any activity transitions currently running on this
5555 * activity. A return value of {@code true} can mean that either an enter or
5556 * exit transition is running, including whether the background of the activity
5557 * is animating as a part of that transition.
5558 *
5559 * @return true if a transition is currently running on this activity, false otherwise.
5560 */
5561 public boolean isActivityTransitionRunning() {
5562 return mActivityTransitionState.isTransitionRunning();
5563 }
5564
5565 private Bundle transferSpringboardActivityOptions(@Nullable Bundle options) {
5566 if (options == null && (mWindow != null && !mWindow.isActive())) {
5567 final ActivityOptions activityOptions = getActivityOptions();
5568 if (activityOptions != null &&
5569 activityOptions.getAnimationType() == ActivityOptions.ANIM_SCENE_TRANSITION) {
5570 return activityOptions.toBundle();
5571 }
5572 }
5573 return options;
5574 }
5575
5576 /**
5577 * Launch an activity for which you would like a result when it finished.
5578 * When this activity exits, your
5579 * onActivityResult() method will be called with the given requestCode.
5580 * Using a negative requestCode is the same as calling
5581 * {@link #startActivity} (the activity is not launched as a sub-activity).
5582 *
5583 * <p>Note that this method should only be used with Intent protocols
5584 * that are defined to return a result. In other protocols (such as
5585 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
5586 * not get the result when you expect. For example, if the activity you
5587 * are launching uses {@link Intent#FLAG_ACTIVITY_NEW_TASK}, it will not
5588 * run in your task and thus you will immediately receive a cancel result.
5589 *
5590 * <p>As a special case, if you call startActivityForResult() with a requestCode
5591 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
5592 * activity, then your window will not be displayed until a result is
5593 * returned back from the started activity. This is to avoid visible
5594 * flickering when redirecting to another activity.
5595 *
5596 * <p>This method throws {@link android.content.ActivityNotFoundException}
5597 * if there was no Activity found to run the given Intent.
5598 *
5599 * @param intent The intent to start.
5600 * @param requestCode If >= 0, this code will be returned in
5601 * onActivityResult() when the activity exits.
5602 * @param user The user to start the intent as.
5603 * @hide Implement to provide correct calling token.
5604 */
5605 @SystemApi
5606 @RequiresPermission(anyOf = {INTERACT_ACROSS_USERS, INTERACT_ACROSS_USERS_FULL})
5607 public void startActivityForResultAsUser(@NonNull Intent intent, int requestCode,
5608 @NonNull UserHandle user) {
5609 startActivityForResultAsUser(intent, requestCode, null, user);
5610 }
5611
5612 /**
5613 * Launch an activity for which you would like a result when it finished.
5614 * When this activity exits, your
5615 * onActivityResult() method will be called with the given requestCode.
5616 * Using a negative requestCode is the same as calling
5617 * {@link #startActivity} (the activity is not launched as a sub-activity).
5618 *
5619 * <p>Note that this method should only be used with Intent protocols
5620 * that are defined to return a result. In other protocols (such as
5621 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
5622 * not get the result when you expect. For example, if the activity you
5623 * are launching uses {@link Intent#FLAG_ACTIVITY_NEW_TASK}, it will not
5624 * run in your task and thus you will immediately receive a cancel result.
5625 *
5626 * <p>As a special case, if you call startActivityForResult() with a requestCode
5627 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
5628 * activity, then your window will not be displayed until a result is
5629 * returned back from the started activity. This is to avoid visible
5630 * flickering when redirecting to another activity.
5631 *
5632 * <p>This method throws {@link android.content.ActivityNotFoundException}
5633 * if there was no Activity found to run the given Intent.
5634 *
5635 * @param intent The intent to start.
5636 * @param requestCode If >= 0, this code will be returned in
5637 * onActivityResult() when the activity exits.
5638 * @param options Additional options for how the Activity should be started. See {@link
5639 * android.content.Context#startActivity(Intent, Bundle)} for more details.
5640 * @param user The user to start the intent as.
5641 * @hide Implement to provide correct calling token.
5642 */
5643 @SystemApi
5644 @RequiresPermission(anyOf = {INTERACT_ACROSS_USERS, INTERACT_ACROSS_USERS_FULL})
5645 public void startActivityForResultAsUser(@NonNull Intent intent, int requestCode,
5646 @Nullable Bundle options, @NonNull UserHandle user) {
5647 startActivityForResultAsUser(intent, mEmbeddedID, requestCode, options, user);
5648 }
5649
5650 /**
5651 * Launch an activity for which you would like a result when it finished.
5652 * When this activity exits, your
5653 * onActivityResult() method will be called with the given requestCode.
5654 * Using a negative requestCode is the same as calling
5655 * {@link #startActivity} (the activity is not launched as a sub-activity).
5656 *
5657 * <p>Note that this method should only be used with Intent protocols
5658 * that are defined to return a result. In other protocols (such as
5659 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
5660 * not get the result when you expect. For example, if the activity you
5661 * are launching uses {@link Intent#FLAG_ACTIVITY_NEW_TASK}, it will not
5662 * run in your task and thus you will immediately receive a cancel result.
5663 *
5664 * <p>As a special case, if you call startActivityForResult() with a requestCode
5665 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
5666 * activity, then your window will not be displayed until a result is
5667 * returned back from the started activity. This is to avoid visible
5668 * flickering when redirecting to another activity.
5669 *
5670 * <p>This method throws {@link android.content.ActivityNotFoundException}
5671 * if there was no Activity found to run the given Intent.
5672 *
5673 * @param intent The intent to start.
5674 * @param requestCode If >= 0, this code will be returned in
5675 * onActivityResult() when the activity exits.
5676 * @param options Additional options for how the Activity should be started. See {@link
5677 * android.content.Context#startActivity(Intent, Bundle)} for more details.
5678 * @param user The user to start the intent as.
5679 * @hide Implement to provide correct calling token.
5680 */
5681 @SystemApi
5682 @RequiresPermission(anyOf = {INTERACT_ACROSS_USERS, INTERACT_ACROSS_USERS_FULL})
5683 public void startActivityForResultAsUser(@NonNull Intent intent, @NonNull String resultWho,
5684 int requestCode,
5685 @Nullable Bundle options, @NonNull UserHandle user) {
5686 if (mParent != null) {
5687 throw new RuntimeException("Can't be called from a child");
5688 }
5689 options = transferSpringboardActivityOptions(options);
5690 Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
5691 this, mMainThread.getApplicationThread(), mToken, resultWho, intent, requestCode,
5692 options, user);
5693 if (ar != null) {
5694 mMainThread.sendActivityResult(
5695 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
5696 }
5697 if (requestCode >= 0) {
5698 // If this start is requesting a result, we can avoid making
5699 // the activity visible until the result is received. Setting
5700 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
5701 // activity hidden during this time, to avoid flickering.
5702 // This can only be done when a result is requested because
5703 // that guarantees we will get information back when the
5704 // activity is finished, no matter what happens to it.
5705 mStartedActivity = true;
5706 }
5707
5708 cancelInputsAndStartExitTransition(options);
5709 }
5710
5711 /**
5712 * @hide Implement to provide correct calling token.
5713 */
5714 @Override
5715 public void startActivityAsUser(Intent intent, UserHandle user) {
5716 startActivityAsUser(intent, null, user);
5717 }
5718
5719 /**
5720 * Version of {@link #startActivity(Intent, Bundle)} that allows you to specify the
5721 * user the activity will be started for. This is not available to applications
5722 * that are not pre-installed on the system image.
5723 * @param intent The description of the activity to start.
5724 *
5725 * @param user The UserHandle of the user to start this activity for.
5726 * @param options Additional options for how the Activity should be started.
5727 * May be null if there are no options. See {@link android.app.ActivityOptions}
5728 * for how to build the Bundle supplied here; there are no supported definitions
5729 * for building it manually.
5730 * @throws ActivityNotFoundException &nbsp;
5731 * @hide
5732 */
5733 @RequiresPermission(anyOf = {INTERACT_ACROSS_USERS, INTERACT_ACROSS_USERS_FULL})
5734 public void startActivityAsUser(@NonNull Intent intent,
5735 @Nullable Bundle options, @NonNull UserHandle user) {
5736 if (mParent != null) {
5737 throw new RuntimeException("Can't be called from a child");
5738 }
5739 options = transferSpringboardActivityOptions(options);
5740 Instrumentation.ActivityResult ar =
5741 mInstrumentation.execStartActivity(
5742 this, mMainThread.getApplicationThread(), mToken, mEmbeddedID,
5743 intent, -1, options, user);
5744 if (ar != null) {
5745 mMainThread.sendActivityResult(
5746 mToken, mEmbeddedID, -1, ar.getResultCode(),
5747 ar.getResultData());
5748 }
5749 cancelInputsAndStartExitTransition(options);
5750 }
5751
5752 /**
5753 * Start a new activity as if it was started by the activity that started our
5754 * current activity. This is for the resolver and chooser activities, which operate
5755 * as intermediaries that dispatch their intent to the target the user selects -- to
5756 * do this, they must perform all security checks including permission grants as if
5757 * their launch had come from the original activity.
5758 * @param intent The Intent to start.
5759 * @param options ActivityOptions or null.
5760 * @param ignoreTargetSecurity If true, the activity manager will not check whether the
5761 * caller it is doing the start is, is actually allowed to start the target activity.
5762 * If you set this to true, you must set an explicit component in the Intent and do any
5763 * appropriate security checks yourself.
5764 * @param userId The user the new activity should run as.
5765 * @hide
5766 */
5767 public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
5768 boolean ignoreTargetSecurity, int userId) {
5769 startActivityAsCaller(intent, options, ignoreTargetSecurity, userId, -1);
5770 }
5771
5772 /**
5773 * @see #startActivityAsCaller(Intent, Bundle, boolean, int)
5774 * @param requestCode The request code used for returning a result or -1 if no result should be
5775 * returned.
5776 * @hide
5777 */
5778 public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
5779 boolean ignoreTargetSecurity, int userId, int requestCode) {
5780 if (mParent != null) {
5781 throw new RuntimeException("Can't be called from a child");
5782 }
5783 options = transferSpringboardActivityOptions(options);
5784 Instrumentation.ActivityResult ar =
5785 mInstrumentation.execStartActivityAsCaller(
5786 this, mMainThread.getApplicationThread(), mToken, this,
5787 intent, requestCode, options, ignoreTargetSecurity, userId);
5788 if (ar != null) {
5789 mMainThread.sendActivityResult(
5790 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
5791 }
5792 cancelInputsAndStartExitTransition(options);
5793 }
5794
5795 /**
5796 * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
5797 * Intent, int, int, int, Bundle)} with no options.
5798 *
5799 * @param intent The IntentSender to launch.
5800 * @param requestCode If >= 0, this code will be returned in
5801 * onActivityResult() when the activity exits.
5802 * @param fillInIntent If non-null, this will be provided as the
5803 * intent parameter to {@link IntentSender#sendIntent}.
5804 * @param flagsMask Intent flags in the original IntentSender that you
5805 * would like to change.
5806 * @param flagsValues Desired values for any bits set in
5807 * <var>flagsMask</var>
5808 * @param extraFlags Always set to 0.
5809 */
5810 public void startIntentSenderForResult(IntentSender intent, int requestCode,
5811 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
5812 throws IntentSender.SendIntentException {
5813 startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
5814 flagsValues, extraFlags, null);
5815 }
5816
5817 /**
5818 * Like {@link #startIntentSenderForResult} but taking {@code who} as an additional identifier.
5819 *
5820 * @hide
5821 */
5822 public void startIntentSenderForResult(IntentSender intent, String who, int requestCode,
5823 Intent fillInIntent, int flagsMask, int flagsValues, Bundle options)
5824 throws IntentSender.SendIntentException {
5825 startIntentSenderForResultInner(intent, who, requestCode, fillInIntent, flagsMask,
5826 flagsValues, options);
5827 }
5828
5829 /**
5830 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
5831 * to use a IntentSender to describe the activity to be started. If
5832 * the IntentSender is for an activity, that activity will be started
5833 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
5834 * here; otherwise, its associated action will be executed (such as
5835 * sending a broadcast) as if you had called
5836 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
5837 *
5838 * @param intent The IntentSender to launch.
5839 * @param requestCode If >= 0, this code will be returned in
5840 * onActivityResult() when the activity exits.
5841 * @param fillInIntent If non-null, this will be provided as the
5842 * intent parameter to {@link IntentSender#sendIntent}.
5843 * @param flagsMask Intent flags in the original IntentSender that you
5844 * would like to change.
5845 * @param flagsValues Desired values for any bits set in
5846 * <var>flagsMask</var>
5847 * @param extraFlags Always set to 0.
5848 * @param options Additional options for how the Activity should be started.
5849 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5850 * Context.startActivity(Intent, Bundle)} for more details. If options
5851 * have also been supplied by the IntentSender, options given here will
5852 * override any that conflict with those given by the IntentSender.
5853 */
5854 public void startIntentSenderForResult(IntentSender intent, int requestCode,
5855 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
5856 @Nullable Bundle options) throws IntentSender.SendIntentException {
5857 if (mParent == null) {
5858 startIntentSenderForResultInner(intent, mEmbeddedID, requestCode, fillInIntent,
5859 flagsMask, flagsValues, options);
5860 } else if (options != null) {
5861 mParent.startIntentSenderFromChild(this, intent, requestCode,
5862 fillInIntent, flagsMask, flagsValues, extraFlags, options);
5863 } else {
5864 // Note we want to go through this call for compatibility with
5865 // existing applications that may have overridden the method.
5866 mParent.startIntentSenderFromChild(this, intent, requestCode,
5867 fillInIntent, flagsMask, flagsValues, extraFlags);
5868 }
5869 }
5870
5871 /**
5872 * @hide
5873 */
5874 public void startIntentSenderForResultInner(IntentSender intent, String who, int requestCode,
5875 Intent fillInIntent, int flagsMask, int flagsValues,
5876 @Nullable Bundle options)
5877 throws IntentSender.SendIntentException {
5878 try {
5879 options = transferSpringboardActivityOptions(options);
5880 String resolvedType = null;
5881 if (fillInIntent != null) {
5882 fillInIntent.migrateExtraStreamToClipData(this);
5883 fillInIntent.prepareToLeaveProcess(this);
5884 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
5885 }
5886 int result = ActivityTaskManager.getService()
5887 .startActivityIntentSender(mMainThread.getApplicationThread(),
5888 intent != null ? intent.getTarget() : null,
5889 intent != null ? intent.getWhitelistToken() : null,
5890 fillInIntent, resolvedType, mToken, who,
5891 requestCode, flagsMask, flagsValues, options);
5892 if (result == ActivityManager.START_CANCELED) {
5893 throw new IntentSender.SendIntentException();
5894 }
5895 Instrumentation.checkStartActivityResult(result, null);
5896
5897 if (options != null) {
5898 // Only when the options are not null, as the intent can point to something other
5899 // than an Activity.
5900 cancelInputsAndStartExitTransition(options);
5901 }
5902 } catch (RemoteException e) {
5903 }
5904 if (requestCode >= 0) {
5905 // If this start is requesting a result, we can avoid making
5906 // the activity visible until the result is received. Setting
5907 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
5908 // activity hidden during this time, to avoid flickering.
5909 // This can only be done when a result is requested because
5910 // that guarantees we will get information back when the
5911 // activity is finished, no matter what happens to it.
5912 mStartedActivity = true;
5913 }
5914 }
5915
5916 /**
5917 * Same as {@link #startActivity(Intent, Bundle)} with no options
5918 * specified.
5919 *
5920 * @param intent The intent to start.
5921 *
5922 * @throws android.content.ActivityNotFoundException
5923 *
5924 * @see #startActivity(Intent, Bundle)
5925 * @see #startActivityForResult
5926 */
5927 @Override
5928 public void startActivity(Intent intent) {
5929 this.startActivity(intent, null);
5930 }
5931
5932 /**
5933 * Launch a new activity. You will not receive any information about when
5934 * the activity exits. This implementation overrides the base version,
5935 * providing information about
5936 * the activity performing the launch. Because of this additional
5937 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
5938 * required; if not specified, the new activity will be added to the
5939 * task of the caller.
5940 *
5941 * <p>This method throws {@link android.content.ActivityNotFoundException}
5942 * if there was no Activity found to run the given Intent.
5943 *
5944 * @param intent The intent to start.
5945 * @param options Additional options for how the Activity should be started.
5946 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5947 * Context.startActivity(Intent, Bundle)} for more details.
5948 *
5949 * @throws android.content.ActivityNotFoundException
5950 *
5951 * @see #startActivity(Intent)
5952 * @see #startActivityForResult
5953 */
5954 @Override
5955 public void startActivity(Intent intent, @Nullable Bundle options) {
5956 getAutofillClientController().onStartActivity(intent, mIntent);
5957 if (options != null) {
5958 startActivityForResult(intent, -1, options);
5959 } else {
5960 // Note we want to go through this call for compatibility with
5961 // applications that may have overridden the method.
5962 startActivityForResult(intent, -1);
5963 }
5964 }
5965
5966 /**
5967 * Same as {@link #startActivities(Intent[], Bundle)} with no options
5968 * specified.
5969 *
5970 * @param intents The intents to start.
5971 *
5972 * @throws android.content.ActivityNotFoundException
5973 *
5974 * @see #startActivities(Intent[], Bundle)
5975 * @see #startActivityForResult
5976 */
5977 @Override
5978 public void startActivities(Intent[] intents) {
5979 startActivities(intents, null);
5980 }
5981
5982 /**
5983 * Launch a new activity. You will not receive any information about when
5984 * the activity exits. This implementation overrides the base version,
5985 * providing information about
5986 * the activity performing the launch. Because of this additional
5987 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
5988 * required; if not specified, the new activity will be added to the
5989 * task of the caller.
5990 *
5991 * <p>This method throws {@link android.content.ActivityNotFoundException}
5992 * if there was no Activity found to run the given Intent.
5993 *
5994 * @param intents The intents to start.
5995 * @param options Additional options for how the Activity should be started.
5996 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5997 * Context.startActivity(Intent, Bundle)} for more details.
5998 *
5999 * @throws android.content.ActivityNotFoundException
6000 *
6001 * @see #startActivities(Intent[])
6002 * @see #startActivityForResult
6003 */
6004 @Override
6005 public void startActivities(Intent[] intents, @Nullable Bundle options) {
6006 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
6007 mToken, this, intents, options);
6008 }
6009
6010 /**
6011 * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
6012 * with no options.
6013 *
6014 * @param intent The IntentSender to launch.
6015 * @param fillInIntent If non-null, this will be provided as the
6016 * intent parameter to {@link IntentSender#sendIntent}.
6017 * @param flagsMask Intent flags in the original IntentSender that you
6018 * would like to change.
6019 * @param flagsValues Desired values for any bits set in
6020 * <var>flagsMask</var>
6021 * @param extraFlags Always set to 0.
6022 */
6023 @Override
6024 public void startIntentSender(IntentSender intent,
6025 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
6026 throws IntentSender.SendIntentException {
6027 startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
6028 extraFlags, null);
6029 }
6030
6031 /**
6032 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
6033 * to start; see
6034 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
6035 * for more information.
6036 *
6037 * @param intent The IntentSender to launch.
6038 * @param fillInIntent If non-null, this will be provided as the
6039 * intent parameter to {@link IntentSender#sendIntent}.
6040 * @param flagsMask Intent flags in the original IntentSender that you
6041 * would like to change.
6042 * @param flagsValues Desired values for any bits set in
6043 * <var>flagsMask</var>
6044 * @param extraFlags Always set to 0.
6045 * @param options Additional options for how the Activity should be started.
6046 * See {@link android.content.Context#startActivity(Intent, Bundle)}
6047 * Context.startActivity(Intent, Bundle)} for more details. If options
6048 * have also been supplied by the IntentSender, options given here will
6049 * override any that conflict with those given by the IntentSender.
6050 */
6051 @Override
6052 public void startIntentSender(IntentSender intent,
6053 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
6054 @Nullable Bundle options) throws IntentSender.SendIntentException {
6055 if (options != null) {
6056 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
6057 flagsValues, extraFlags, options);
6058 } else {
6059 // Note we want to go through this call for compatibility with
6060 // applications that may have overridden the method.
6061 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
6062 flagsValues, extraFlags);
6063 }
6064 }
6065
6066 /**
6067 * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
6068 * with no options.
6069 *
6070 * @param intent The intent to start.
6071 * @param requestCode If >= 0, this code will be returned in
6072 * onActivityResult() when the activity exits, as described in
6073 * {@link #startActivityForResult}.
6074 *
6075 * @return If a new activity was launched then true is returned; otherwise
6076 * false is returned and you must handle the Intent yourself.
6077 *
6078 * @see #startActivity
6079 * @see #startActivityForResult
6080 */
6081 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
6082 int requestCode) {
6083 return startActivityIfNeeded(intent, requestCode, null);
6084 }
6085
6086 /**
6087 * A special variation to launch an activity only if a new activity
6088 * instance is needed to handle the given Intent. In other words, this is
6089 * just like {@link #startActivityForResult(Intent, int)} except: if you are
6090 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
6091 * singleTask or singleTop
6092 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
6093 * and the activity
6094 * that handles <var>intent</var> is the same as your currently running
6095 * activity, then a new instance is not needed. In this case, instead of
6096 * the normal behavior of calling {@link #onNewIntent} this function will
6097 * return and you can handle the Intent yourself.
6098 *
6099 * <p>This function can only be called from a top-level activity; if it is
6100 * called from a child activity, a runtime exception will be thrown.
6101 *
6102 * @param intent The intent to start.
6103 * @param requestCode If >= 0, this code will be returned in
6104 * onActivityResult() when the activity exits, as described in
6105 * {@link #startActivityForResult}.
6106 * @param options Additional options for how the Activity should be started.
6107 * See {@link android.content.Context#startActivity(Intent, Bundle)}
6108 * Context.startActivity(Intent, Bundle)} for more details.
6109 *
6110 * @return If a new activity was launched then true is returned; otherwise
6111 * false is returned and you must handle the Intent yourself.
6112 *
6113 * @see #startActivity
6114 * @see #startActivityForResult
6115 */
6116 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
6117 int requestCode, @Nullable Bundle options) {
6118 if (mParent == null) {
6119 int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
6120 try {
6121 Uri referrer = onProvideReferrer();
6122 if (referrer != null) {
6123 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
6124 }
6125 intent.migrateExtraStreamToClipData(this);
6126 intent.prepareToLeaveProcess(this);
6127 result = ActivityTaskManager.getService()
6128 .startActivity(mMainThread.getApplicationThread(), getOpPackageName(),
6129 getAttributionTag(), intent,
6130 intent.resolveTypeIfNeeded(getContentResolver()), mToken, mEmbeddedID,
6131 requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED, null, options);
6132 } catch (RemoteException e) {
6133 // Empty
6134 }
6135
6136 Instrumentation.checkStartActivityResult(result, intent);
6137
6138 if (requestCode >= 0) {
6139 // If this start is requesting a result, we can avoid making
6140 // the activity visible until the result is received. Setting
6141 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
6142 // activity hidden during this time, to avoid flickering.
6143 // This can only be done when a result is requested because
6144 // that guarantees we will get information back when the
6145 // activity is finished, no matter what happens to it.
6146 mStartedActivity = true;
6147 }
6148 return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
6149 }
6150
6151 throw new UnsupportedOperationException(
6152 "startActivityIfNeeded can only be called from a top-level activity");
6153 }
6154
6155 /**
6156 * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
6157 * no options.
6158 *
6159 * @param intent The intent to dispatch to the next activity. For
6160 * correct behavior, this must be the same as the Intent that started
6161 * your own activity; the only changes you can make are to the extras
6162 * inside of it.
6163 *
6164 * @return Returns a boolean indicating whether there was another Activity
6165 * to start: true if there was a next activity to start, false if there
6166 * wasn't. In general, if true is returned you will then want to call
6167 * finish() on yourself.
6168 */
6169 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent) {
6170 return startNextMatchingActivity(intent, null);
6171 }
6172
6173 /**
6174 * Special version of starting an activity, for use when you are replacing
6175 * other activity components. You can use this to hand the Intent off
6176 * to the next Activity that can handle it. You typically call this in
6177 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
6178 *
6179 * @param intent The intent to dispatch to the next activity. For
6180 * correct behavior, this must be the same as the Intent that started
6181 * your own activity; the only changes you can make are to the extras
6182 * inside of it.
6183 * @param options Additional options for how the Activity should be started.
6184 * See {@link android.content.Context#startActivity(Intent, Bundle)}
6185 * Context.startActivity(Intent, Bundle)} for more details.
6186 *
6187 * @return Returns a boolean indicating whether there was another Activity
6188 * to start: true if there was a next activity to start, false if there
6189 * wasn't. In general, if true is returned you will then want to call
6190 * finish() on yourself.
6191 */
6192 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent,
6193 @Nullable Bundle options) {
6194 if (mParent == null) {
6195 try {
6196 intent.migrateExtraStreamToClipData(this);
6197 intent.prepareToLeaveProcess(this);
6198 return ActivityTaskManager.getService()
6199 .startNextMatchingActivity(mToken, intent, options);
6200 } catch (RemoteException e) {
6201 // Empty
6202 }
6203 return false;
6204 }
6205
6206 throw new UnsupportedOperationException(
6207 "startNextMatchingActivity can only be called from a top-level activity");
6208 }
6209
6210 /**
6211 * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
6212 * with no options.
6213 *
6214 * @param child The activity making the call.
6215 * @param intent The intent to start.
6216 * @param requestCode Reply request code. < 0 if reply is not requested.
6217 *
6218 * @throws android.content.ActivityNotFoundException
6219 *
6220 * @see #startActivity
6221 * @see #startActivityForResult
6222 * @deprecated Use {@code androidx.fragment.app.FragmentActivity#startActivityFromFragment(
6223 * androidx.fragment.app.Fragment,Intent,int)}
6224 */
6225 @Deprecated
6226 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
6227 int requestCode) {
6228 startActivityFromChild(child, intent, requestCode, null);
6229 }
6230
6231 /**
6232 * This is called when a child activity of this one calls its
6233 * {@link #startActivity} or {@link #startActivityForResult} method.
6234 *
6235 * <p>This method throws {@link android.content.ActivityNotFoundException}
6236 * if there was no Activity found to run the given Intent.
6237 *
6238 * @param child The activity making the call.
6239 * @param intent The intent to start.
6240 * @param requestCode Reply request code. < 0 if reply is not requested.
6241 * @param options Additional options for how the Activity should be started.
6242 * See {@link android.content.Context#startActivity(Intent, Bundle)}
6243 * Context.startActivity(Intent, Bundle)} for more details.
6244 *
6245 * @throws android.content.ActivityNotFoundException
6246 *
6247 * @see #startActivity
6248 * @see #startActivityForResult
6249 * @deprecated Use {@code androidx.fragment.app.FragmentActivity#startActivityFromFragment(
6250 * androidx.fragment.app.Fragment,Intent,int,Bundle)}
6251 */
6252 @Deprecated
6253 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
6254 int requestCode, @Nullable Bundle options) {
6255 options = transferSpringboardActivityOptions(options);
6256 Instrumentation.ActivityResult ar =
6257 mInstrumentation.execStartActivity(
6258 this, mMainThread.getApplicationThread(), mToken, child,
6259 intent, requestCode, options);
6260 if (ar != null) {
6261 mMainThread.sendActivityResult(
6262 mToken, child.mEmbeddedID, requestCode,
6263 ar.getResultCode(), ar.getResultData());
6264 }
6265 cancelInputsAndStartExitTransition(options);
6266 }
6267
6268 /**
6269 * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
6270 * with no options.
6271 *
6272 * @param fragment The fragment making the call.
6273 * @param intent The intent to start.
6274 * @param requestCode Reply request code. < 0 if reply is not requested.
6275 *
6276 * @throws android.content.ActivityNotFoundException
6277 *
6278 * @see Fragment#startActivity
6279 * @see Fragment#startActivityForResult
6280 *
6281 * @deprecated Use {@code androidx.fragment.app.FragmentActivity#startActivityFromFragment(
6282 * androidx.fragment.app.Fragment,Intent,int)}
6283 */
6284 @Deprecated
6285 public void startActivityFromFragment(@NonNull Fragment fragment,
6286 @RequiresPermission Intent intent, int requestCode) {
6287 startActivityFromFragment(fragment, intent, requestCode, null);
6288 }
6289
6290 /**
6291 * This is called when a Fragment in this activity calls its
6292 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
6293 * method.
6294 *
6295 * <p>This method throws {@link android.content.ActivityNotFoundException}
6296 * if there was no Activity found to run the given Intent.
6297 *
6298 * @param fragment The fragment making the call.
6299 * @param intent The intent to start.
6300 * @param requestCode Reply request code. < 0 if reply is not requested.
6301 * @param options Additional options for how the Activity should be started.
6302 * See {@link android.content.Context#startActivity(Intent, Bundle)}
6303 * Context.startActivity(Intent, Bundle)} for more details.
6304 *
6305 * @throws android.content.ActivityNotFoundException
6306 *
6307 * @see Fragment#startActivity
6308 * @see Fragment#startActivityForResult
6309 *
6310 * @deprecated Use {@code androidx.fragment.app.FragmentActivity#startActivityFromFragment(
6311 * androidx.fragment.app.Fragment,Intent,int,Bundle)}
6312 */
6313 @Deprecated
6314 public void startActivityFromFragment(@NonNull Fragment fragment,
6315 @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
6316 startActivityForResult(fragment.mWho, intent, requestCode, options);
6317 }
6318
6319 private void startActivityAsUserFromFragment(@NonNull Fragment fragment,
6320 @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options,
6321 UserHandle user) {
6322 startActivityForResultAsUser(intent, fragment.mWho, requestCode, options, user);
6323 }
6324
6325 /**
6326 * @hide
6327 */
6328 @Override
6329 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
6330 public void startActivityForResult(
6331 String who, Intent intent, int requestCode, @Nullable Bundle options) {
6332 Uri referrer = onProvideReferrer();
6333 if (referrer != null) {
6334 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
6335 }
6336 options = transferSpringboardActivityOptions(options);
6337 Instrumentation.ActivityResult ar =
6338 mInstrumentation.execStartActivity(
6339 this, mMainThread.getApplicationThread(), mToken, who,
6340 intent, requestCode, options);
6341 if (ar != null) {
6342 mMainThread.sendActivityResult(
6343 mToken, who, requestCode,
6344 ar.getResultCode(), ar.getResultData());
6345 }
6346 cancelInputsAndStartExitTransition(options);
6347 }
6348
6349 /**
6350 * @hide
6351 */
6352 @Override
6353 public boolean canStartActivityForResult() {
6354 return true;
6355 }
6356
6357 /**
6358 * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
6359 * int, Intent, int, int, int, Bundle)} with no options.
6360 * @deprecated Use {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
6361 * instead.
6362 */
6363 @Deprecated
6364 public void startIntentSenderFromChild(Activity child, IntentSender intent,
6365 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
6366 int extraFlags)
6367 throws IntentSender.SendIntentException {
6368 startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
6369 flagsMask, flagsValues, extraFlags, null);
6370 }
6371
6372 /**
6373 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
6374 * taking a IntentSender; see
6375 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
6376 * for more information.
6377 * @deprecated Use
6378 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
6379 * instead.
6380 */
6381 @Deprecated
6382 public void startIntentSenderFromChild(Activity child, IntentSender intent,
6383 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
6384 int extraFlags, @Nullable Bundle options)
6385 throws IntentSender.SendIntentException {
6386 startIntentSenderForResultInner(intent, child.mEmbeddedID, requestCode, fillInIntent,
6387 flagsMask, flagsValues, options);
6388 }
6389
6390 /**
6391 * Like {@link #startIntentSender}, but taking a Fragment; see
6392 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
6393 * for more information.
6394 */
6395 private void startIntentSenderFromFragment(Fragment fragment, IntentSender intent,
6396 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
6397 @Nullable Bundle options)
6398 throws IntentSender.SendIntentException {
6399 startIntentSenderForResultInner(intent, fragment.mWho, requestCode, fillInIntent,
6400 flagsMask, flagsValues, options);
6401 }
6402
6403 /**
6404 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
6405 * or {@link #finish} to specify an explicit transition animation to
6406 * perform next.
6407 *
6408 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
6409 * to using this with starting activities is to supply the desired animation
6410 * information through a {@link ActivityOptions} bundle to
6411 * {@link #startActivity(Intent, Bundle)} or a related function. This allows
6412 * you to specify a custom animation even when starting an activity from
6413 * outside the context of the current top activity.
6414 *
6415 * <p>Af of {@link android.os.Build.VERSION_CODES#S} application can only specify
6416 * a transition animation when the transition happens within the same task. System
6417 * default animation is used for cross-task transition animations.
6418 *
6419 * @param enterAnim A resource ID of the animation resource to use for
6420 * the incoming activity. Use 0 for no animation.
6421 * @param exitAnim A resource ID of the animation resource to use for
6422 * the outgoing activity. Use 0 for no animation.
6423 */
6424 public void overridePendingTransition(int enterAnim, int exitAnim) {
6425 overridePendingTransition(enterAnim, exitAnim, 0);
6426 }
6427
6428 /**
6429 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
6430 * or {@link #finish} to specify an explicit transition animation to
6431 * perform next.
6432 *
6433 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
6434 * to using this with starting activities is to supply the desired animation
6435 * information through a {@link ActivityOptions} bundle to
6436 * {@link #startActivity(Intent, Bundle)} or a related function. This allows
6437 * you to specify a custom animation even when starting an activity from
6438 * outside the context of the current top activity.
6439 *
6440 * @param enterAnim A resource ID of the animation resource to use for
6441 * the incoming activity. Use 0 for no animation.
6442 * @param exitAnim A resource ID of the animation resource to use for
6443 * the outgoing activity. Use 0 for no animation.
6444 * @param backgroundColor The background color to use for the background during the animation if
6445 * the animation requires a background. Set to 0 to not override the default color.
6446 */
6447 public void overridePendingTransition(int enterAnim, int exitAnim, int backgroundColor) {
6448 ActivityClient.getInstance().overridePendingTransition(mToken, getPackageName(), enterAnim,
6449 exitAnim, backgroundColor);
6450 }
6451
6452 /**
6453 * Call this to set the result that your activity will return to its
6454 * caller.
6455 *
6456 * @param resultCode The result code to propagate back to the originating
6457 * activity, often RESULT_CANCELED or RESULT_OK
6458 *
6459 * @see #RESULT_CANCELED
6460 * @see #RESULT_OK
6461 * @see #RESULT_FIRST_USER
6462 * @see #setResult(int, Intent)
6463 */
6464 public final void setResult(int resultCode) {
6465 synchronized (this) {
6466 mResultCode = resultCode;
6467 mResultData = null;
6468 }
6469 }
6470
6471 /**
6472 * Ensures the activity's result is immediately returned to the caller when {@link #finish()}
6473 * is invoked
6474 *
6475 * <p>Should be invoked alongside {@link #setResult(int, Intent)}, so the provided results are
6476 * in place before finishing. Must only be invoked during MediaProjection setup.
6477 *
6478 * @hide
6479 */
6480 @RequiresPermission(android.Manifest.permission.MANAGE_MEDIA_PROJECTION)
6481 public final void setForceSendResultForMediaProjection() {
6482 ActivityClient.getInstance().setForceSendResultForMediaProjection(mToken);
6483 }
6484
6485 /**
6486 * Call this to set the result that your activity will return to its
6487 * caller.
6488 *
6489 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
6490 * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
6491 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
6492 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the
6493 * Activity receiving the result access to the specific URIs in the Intent.
6494 * Access will remain until the Activity has finished (it will remain across the hosting
6495 * process being killed and other temporary destruction) and will be added
6496 * to any existing set of URI permissions it already holds.
6497 *
6498 * @param resultCode The result code to propagate back to the originating
6499 * activity, often RESULT_CANCELED or RESULT_OK
6500 * @param data The data to propagate back to the originating activity.
6501 *
6502 * @see #RESULT_CANCELED
6503 * @see #RESULT_OK
6504 * @see #RESULT_FIRST_USER
6505 * @see #setResult(int)
6506 */
6507 public final void setResult(int resultCode, Intent data) {
6508 synchronized (this) {
6509 mResultCode = resultCode;
6510 mResultData = data;
6511 }
6512 }
6513
6514 /**
6515 * Return information about who launched this activity. If the launching Intent
6516 * contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
6517 * that will be returned as-is; otherwise, if known, an
6518 * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
6519 * package name that started the Intent will be returned. This may return null if no
6520 * referrer can be identified -- it is neither explicitly specified, nor is it known which
6521 * application package was involved.
6522 *
6523 * <p>If called while inside the handling of {@link #onNewIntent}, this function will
6524 * return the referrer that submitted that new intent to the activity. Otherwise, it
6525 * always returns the referrer of the original Intent.</p>
6526 *
6527 * <p>Note that this is <em>not</em> a security feature -- you can not trust the
6528 * referrer information, applications can spoof it.</p>
6529 */
6530 @Nullable
6531 public Uri getReferrer() {
6532 Intent intent = getIntent();
6533 if (intent != null) {
6534 try {
6535 Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
6536 if (referrer != null) {
6537 return referrer;
6538 }
6539 String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
6540 if (referrerName != null) {
6541 return Uri.parse(referrerName);
6542 }
6543 } catch (BadParcelableException e) {
6544 Log.w(TAG, "Cannot read referrer from intent;"
6545 + " intent extras contain unknown custom Parcelable objects");
6546 }
6547 }
6548 if (mReferrer != null) {
6549 return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
6550 }
6551 return null;
6552 }
6553
6554 /**
6555 * Override to generate the desired referrer for the content currently being shown
6556 * by the app. The default implementation returns null, meaning the referrer will simply
6557 * be the android-app: of the package name of this activity. Return a non-null Uri to
6558 * have that supplied as the {@link Intent#EXTRA_REFERRER} of any activities started from it.
6559 */
6560 public Uri onProvideReferrer() {
6561 return null;
6562 }
6563
6564 /**
6565 * Return the name of the package that invoked this activity. This is who
6566 * the data in {@link #setResult setResult()} will be sent to. You can
6567 * use this information to validate that the recipient is allowed to
6568 * receive the data.
6569 *
6570 * <p class="note">Note: if the calling activity is not expecting a result (that is it
6571 * did not use the {@link #startActivityForResult}
6572 * form that includes a request code), then the calling package will be
6573 * null.</p>
6574 *
6575 * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
6576 * the result from this method was unstable. If the process hosting the calling
6577 * package was no longer running, it would return null instead of the proper package
6578 * name. You can use {@link #getCallingActivity()} and retrieve the package name
6579 * from that instead.</p>
6580 *
6581 * @return The package of the activity that will receive your
6582 * reply, or null if none.
6583 */
6584 @Nullable
6585 public String getCallingPackage() {
6586 return ActivityClient.getInstance().getCallingPackage(mToken);
6587 }
6588
6589 /**
6590 * Return the name of the activity that invoked this activity. This is
6591 * who the data in {@link #setResult setResult()} will be sent to. You
6592 * can use this information to validate that the recipient is allowed to
6593 * receive the data.
6594 *
6595 * <p class="note">Note: if the calling activity is not expecting a result (that is it
6596 * did not use the {@link #startActivityForResult}
6597 * form that includes a request code), then the calling package will be
6598 * null.
6599 *
6600 * @return The ComponentName of the activity that will receive your
6601 * reply, or null if none.
6602 */
6603 @Nullable
6604 public ComponentName getCallingActivity() {
6605 return ActivityClient.getInstance().getCallingActivity(mToken);
6606 }
6607
6608 /**
6609 * Returns the uid who started this activity.
6610 * @hide
6611 */
6612 public int getLaunchedFromUid() {
6613 return ActivityClient.getInstance().getLaunchedFromUid(getActivityToken());
6614 }
6615
6616 /**
6617 * Returns the package who started this activity.
6618 * @hide
6619 */
6620 @Nullable
6621 public String getLaunchedFromPackage() {
6622 return ActivityClient.getInstance().getLaunchedFromPackage(getActivityToken());
6623 }
6624
6625 /**
6626 * Control whether this activity's main window is visible. This is intended
6627 * only for the special case of an activity that is not going to show a
6628 * UI itself, but can't just finish prior to onResume() because it needs
6629 * to wait for a service binding or such. Setting this to false allows
6630 * you to prevent your UI from being shown during that time.
6631 *
6632 * <p>The default value for this is taken from the
6633 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
6634 */
6635 public void setVisible(boolean visible) {
6636 if (mVisibleFromClient != visible) {
6637 mVisibleFromClient = visible;
6638 if (mVisibleFromServer) {
6639 if (visible) makeVisible();
6640 else mDecor.setVisibility(View.INVISIBLE);
6641 }
6642 }
6643 }
6644
6645 void makeVisible() {
6646 if (!mWindowAdded) {
6647 ViewManager wm = getWindowManager();
6648 wm.addView(mDecor, getWindow().getAttributes());
6649 mWindowAdded = true;
6650 }
6651 mDecor.setVisibility(View.VISIBLE);
6652 }
6653
6654 /**
6655 * Check to see whether this activity is in the process of finishing,
6656 * either because you called {@link #finish} on it or someone else
6657 * has requested that it finished. This is often used in
6658 * {@link #onPause} to determine whether the activity is simply pausing or
6659 * completely finishing.
6660 *
6661 * @return If the activity is finishing, returns true; else returns false.
6662 *
6663 * @see #finish
6664 */
6665 public boolean isFinishing() {
6666 return mFinished;
6667 }
6668
6669 /**
6670 * Returns true if the final {@link #onDestroy()} call has been made
6671 * on the Activity, so this instance is now dead.
6672 */
6673 public boolean isDestroyed() {
6674 return mDestroyed;
6675 }
6676
6677 /**
6678 * Check to see whether this activity is in the process of being destroyed in order to be
6679 * recreated with a new configuration. This is often used in
6680 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
6681 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
6682 *
6683 * @return If the activity is being torn down in order to be recreated with a new configuration,
6684 * returns true; else returns false.
6685 */
6686 public boolean isChangingConfigurations() {
6687 return mChangingConfigurations;
6688 }
6689
6690 /**
6691 * Cause this Activity to be recreated with a new instance. This results
6692 * in essentially the same flow as when the Activity is created due to
6693 * a configuration change -- the current instance will go through its
6694 * lifecycle to {@link #onDestroy} and a new instance then created after it.
6695 */
6696 public void recreate() {
6697 if (mParent != null) {
6698 throw new IllegalStateException("Can only be called on top-level activity");
6699 }
6700 if (Looper.myLooper() != mMainThread.getLooper()) {
6701 throw new IllegalStateException("Must be called from main thread");
6702 }
6703 mMainThread.scheduleRelaunchActivity(mToken);
6704 }
6705
6706 /**
6707 * Finishes the current activity and specifies whether to remove the task associated with this
6708 * activity.
6709 */
6710 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
6711 private void finish(int finishTask) {
6712 if (mParent == null) {
6713 int resultCode;
6714 Intent resultData;
6715 synchronized (this) {
6716 resultCode = mResultCode;
6717 resultData = mResultData;
6718 }
6719 if (false) Log.v(TAG, "Finishing self: token=" + mToken);
6720 if (resultData != null) {
6721 resultData.prepareToLeaveProcess(this);
6722 }
6723 if (ActivityClient.getInstance().finishActivity(mToken, resultCode, resultData,
6724 finishTask)) {
6725 mFinished = true;
6726 }
6727 } else {
6728 mParent.finishFromChild(this);
6729 }
6730
6731 getAutofillClientController().onActivityFinish(mIntent);
6732 }
6733
6734 /**
6735 * Call this when your activity is done and should be closed. The
6736 * ActivityResult is propagated back to whoever launched you via
6737 * onActivityResult().
6738 */
6739 public void finish() {
6740 finish(DONT_FINISH_TASK_WITH_ACTIVITY);
6741 }
6742
6743 /**
6744 * Finish this activity as well as all activities immediately below it
6745 * in the current task that have the same affinity. This is typically
6746 * used when an application can be launched on to another task (such as
6747 * from an ACTION_VIEW of a content type it understands) and the user
6748 * has used the up navigation to switch out of the current task and in
6749 * to its own task. In this case, if the user has navigated down into
6750 * any other activities of the second application, all of those should
6751 * be removed from the original task as part of the task switch.
6752 *
6753 * <p>Note that this finish does <em>not</em> allow you to deliver results
6754 * to the previous activity, and an exception will be thrown if you are trying
6755 * to do so.</p>
6756 */
6757 public void finishAffinity() {
6758 if (mParent != null) {
6759 throw new IllegalStateException("Can not be called from an embedded activity");
6760 }
6761 if (mResultCode != RESULT_CANCELED || mResultData != null) {
6762 throw new IllegalStateException("Can not be called to deliver a result");
6763 }
6764 if (ActivityClient.getInstance().finishActivityAffinity(mToken)) {
6765 mFinished = true;
6766 }
6767 }
6768
6769 /**
6770 * This is called when a child activity of this one calls its
6771 * {@link #finish} method. The default implementation simply calls
6772 * finish() on this activity (the parent), finishing the entire group.
6773 *
6774 * @param child The activity making the call.
6775 *
6776 * @see #finish
6777 * @deprecated Use {@link #finish()} instead.
6778 */
6779 @Deprecated
6780 public void finishFromChild(Activity child) {
6781 finish();
6782 }
6783
6784 /**
6785 * Reverses the Activity Scene entry Transition and triggers the calling Activity
6786 * to reverse its exit Transition. When the exit Transition completes,
6787 * {@link #finish()} is called. If no entry Transition was used, finish() is called
6788 * immediately and the Activity exit Transition is run.
6789 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, android.util.Pair[])
6790 */
6791 public void finishAfterTransition() {
6792 if (!mActivityTransitionState.startExitBackTransition(this)) {
6793 finish();
6794 }
6795 }
6796
6797 /**
6798 * Force finish another activity that you had previously started with
6799 * {@link #startActivityForResult}.
6800 *
6801 * @param requestCode The request code of the activity that you had
6802 * given to startActivityForResult(). If there are multiple
6803 * activities started with this request code, they
6804 * will all be finished.
6805 */
6806 public void finishActivity(int requestCode) {
6807 if (mParent == null) {
6808 ActivityClient.getInstance().finishSubActivity(mToken, mEmbeddedID, requestCode);
6809 } else {
6810 mParent.finishActivityFromChild(this, requestCode);
6811 }
6812 }
6813
6814 /**
6815 * This is called when a child activity of this one calls its
6816 * finishActivity().
6817 *
6818 * @param child The activity making the call.
6819 * @param requestCode Request code that had been used to start the
6820 * activity.
6821 * @deprecated Use {@link #finishActivity(int)} instead.
6822 */
6823 @Deprecated
6824 public void finishActivityFromChild(@NonNull Activity child, int requestCode) {
6825 ActivityClient.getInstance().finishSubActivity(mToken, child.mEmbeddedID, requestCode);
6826 }
6827
6828 /**
6829 * Call this when your activity is done and should be closed and the task should be completely
6830 * removed as a part of finishing the root activity of the task.
6831 */
6832 public void finishAndRemoveTask() {
6833 finish(FINISH_TASK_WITH_ROOT_ACTIVITY);
6834 }
6835
6836 /**
6837 * Ask that the local app instance of this activity be released to free up its memory.
6838 * This is asking for the activity to be destroyed, but does <b>not</b> finish the activity --
6839 * a new instance of the activity will later be re-created if needed due to the user
6840 * navigating back to it.
6841 *
6842 * @return Returns true if the activity was in a state that it has started the process
6843 * of destroying its current instance; returns false if for any reason this could not
6844 * be done: it is currently visible to the user, it is already being destroyed, it is
6845 * being finished, it hasn't yet saved its state, etc.
6846 */
6847 public boolean releaseInstance() {
6848 return ActivityClient.getInstance().releaseActivityInstance(mToken);
6849 }
6850
6851 /**
6852 * Called when an activity you launched exits, giving you the requestCode
6853 * you started it with, the resultCode it returned, and any additional
6854 * data from it. The <var>resultCode</var> will be
6855 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
6856 * didn't return any result, or crashed during its operation.
6857 *
6858 * <p>An activity can never receive a result in the resumed state. You can count on
6859 * {@link #onResume} being called after this method, though not necessarily immediately after.
6860 * If the activity was resumed, it will be paused and the result will be delivered, followed
6861 * by {@link #onResume}. If the activity wasn't in the resumed state, then the result will
6862 * be delivered, with {@link #onResume} called sometime later when the activity becomes active
6863 * again.
6864 *
6865 * <p>This method is never invoked if your activity sets
6866 * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
6867 * <code>true</code>.
6868 *
6869 * @param requestCode The integer request code originally supplied to
6870 * startActivityForResult(), allowing you to identify who this
6871 * result came from.
6872 * @param resultCode The integer result code returned by the child activity
6873 * through its setResult().
6874 * @param data An Intent, which can return result data to the caller
6875 * (various data can be attached to Intent "extras").
6876 *
6877 * @see #startActivityForResult
6878 * @see #createPendingResult
6879 * @see #setResult(int)
6880 */
6881 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
6882 }
6883
6884 /**
6885 * Called when an activity you launched with an activity transition exposes this
6886 * Activity through a returning activity transition, giving you the resultCode
6887 * and any additional data from it. This method will only be called if the activity
6888 * set a result code other than {@link #RESULT_CANCELED} and it supports activity
6889 * transitions with {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6890 *
6891 * <p>The purpose of this function is to let the called Activity send a hint about
6892 * its state so that this underlying Activity can prepare to be exposed. A call to
6893 * this method does not guarantee that the called Activity has or will be exiting soon.
6894 * It only indicates that it will expose this Activity's Window and it has
6895 * some data to pass to prepare it.</p>
6896 *
6897 * @param resultCode The integer result code returned by the child activity
6898 * through its setResult().
6899 * @param data An Intent, which can return result data to the caller
6900 * (various data can be attached to Intent "extras").
6901 */
6902 public void onActivityReenter(int resultCode, Intent data) {
6903 }
6904
6905 /**
6906 * Create a new PendingIntent object which you can hand to others
6907 * for them to use to send result data back to your
6908 * {@link #onActivityResult} callback. The created object will be either
6909 * one-shot (becoming invalid after a result is sent back) or multiple
6910 * (allowing any number of results to be sent through it).
6911 *
6912 * @param requestCode Private request code for the sender that will be
6913 * associated with the result data when it is returned. The sender can not
6914 * modify this value, allowing you to identify incoming results.
6915 * @param data Default data to supply in the result, which may be modified
6916 * by the sender.
6917 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
6918 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
6919 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
6920 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
6921 * or any of the flags as supported by
6922 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
6923 * of the intent that can be supplied when the actual send happens.
6924 *
6925 * @return Returns an existing or new PendingIntent matching the given
6926 * parameters. May return null only if
6927 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
6928 * supplied.
6929 *
6930 * @see PendingIntent
6931 */
6932 public PendingIntent createPendingResult(int requestCode, @NonNull Intent data,
6933 @PendingIntent.Flags int flags) {
6934 String packageName = getPackageName();
6935 try {
6936 data.prepareToLeaveProcess(this);
6937 IIntentSender target = ActivityManager.getService().getIntentSenderWithFeature(
6938 ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName, getAttributionTag(),
6939 mParent == null ? mToken : mParent.mToken, mEmbeddedID, requestCode,
6940 new Intent[]{data}, null, flags, null, getUserId());
6941 return target != null ? new PendingIntent(target) : null;
6942 } catch (RemoteException e) {
6943 // Empty
6944 }
6945 return null;
6946 }
6947
6948 /**
6949 * Change the desired orientation of this activity. If the activity
6950 * is currently in the foreground or otherwise impacting the screen
6951 * orientation, the screen will immediately be changed (possibly causing
6952 * the activity to be restarted). Otherwise, this will be used the next
6953 * time the activity is visible.
6954 *
6955 * @param requestedOrientation An orientation constant as used in
6956 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
6957 */
6958 public void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) {
6959 if (mParent == null) {
6960 ActivityClient.getInstance().setRequestedOrientation(mToken, requestedOrientation);
6961 } else {
6962 mParent.setRequestedOrientation(requestedOrientation);
6963 }
6964 }
6965
6966 /**
6967 * Return the current requested orientation of the activity. This will
6968 * either be the orientation requested in its component's manifest, or
6969 * the last requested orientation given to
6970 * {@link #setRequestedOrientation(int)}.
6971 *
6972 * @return Returns an orientation constant as used in
6973 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
6974 */
6975 @ActivityInfo.ScreenOrientation
6976 public int getRequestedOrientation() {
6977 if (mParent == null) {
6978 return ActivityClient.getInstance().getRequestedOrientation(mToken);
6979 } else {
6980 return mParent.getRequestedOrientation();
6981 }
6982 }
6983
6984 /**
6985 * Return the identifier of the task this activity is in. This identifier
6986 * will remain the same for the lifetime of the activity.
6987 *
6988 * @return Task identifier, an opaque integer.
6989 */
6990 public int getTaskId() {
6991 return ActivityClient.getInstance().getTaskForActivity(mToken, false /* onlyRoot */);
6992 }
6993
6994 /**
6995 * Return whether this activity is the root of a task. The root is the
6996 * first activity in a task.
6997 *
6998 * @return True if this is the root activity, else false.
6999 */
7000 public boolean isTaskRoot() {
7001 return mWindowControllerCallback.isTaskRoot();
7002 }
7003
7004 /**
7005 * Move the task containing this activity to the back of the activity
7006 * stack. The activity's order within the task is unchanged.
7007 *
7008 * @param nonRoot If false then this only works if the activity is the root
7009 * of a task; if true it will work for any activity in
7010 * a task.
7011 *
7012 * @return If the task was moved (or it was already at the
7013 * back) true is returned, else false.
7014 */
7015 public boolean moveTaskToBack(boolean nonRoot) {
7016 return ActivityClient.getInstance().moveActivityTaskToBack(mToken, nonRoot);
7017 }
7018
7019 /**
7020 * Returns class name for this activity with the package prefix removed.
7021 * This is the default name used to read and write settings.
7022 *
7023 * @return The local class name.
7024 */
7025 @NonNull
7026 public String getLocalClassName() {
7027 final String pkg = getPackageName();
7028 final String cls = mComponent.getClassName();
7029 int packageLen = pkg.length();
7030 if (!cls.startsWith(pkg) || cls.length() <= packageLen
7031 || cls.charAt(packageLen) != '.') {
7032 return cls;
7033 }
7034 return cls.substring(packageLen+1);
7035 }
7036
7037 /**
7038 * Returns the complete component name of this activity.
7039 *
7040 * @return Returns the complete component name for this activity
7041 */
7042 public ComponentName getComponentName() {
7043 return mComponent;
7044 }
7045
7046 /** @hide */
7047 @Override
7048 public final ComponentName contentCaptureClientGetComponentName() {
7049 return getComponentName();
7050 }
7051
7052 /**
7053 * Retrieve a {@link SharedPreferences} object for accessing preferences
7054 * that are private to this activity. This simply calls the underlying
7055 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
7056 * class name as the preferences name.
7057 *
7058 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
7059 * operation.
7060 *
7061 * @return Returns the single SharedPreferences instance that can be used
7062 * to retrieve and modify the preference values.
7063 */
7064 public SharedPreferences getPreferences(@Context.PreferencesMode int mode) {
7065 return getSharedPreferences(getLocalClassName(), mode);
7066 }
7067
7068 /**
7069 * Indicates whether this activity is launched from a bubble. A bubble is a floating shortcut
7070 * on the screen that expands to show an activity.
7071 *
7072 * If your activity can be used normally or as a bubble, you might use this method to check
7073 * if the activity is bubbled to modify any behaviour that might be different between the
7074 * normal activity and the bubbled activity. For example, if you normally cancel the
7075 * notification associated with the activity when you open the activity, you might not want to
7076 * do that when you're bubbled as that would remove the bubble.
7077 *
7078 * @return {@code true} if the activity is launched from a bubble.
7079 *
7080 * @see Notification.Builder#setBubbleMetadata(Notification.BubbleMetadata)
7081 * @see Notification.BubbleMetadata.Builder#Builder(String)
7082 */
7083 public boolean isLaunchedFromBubble() {
7084 return mLaunchedFromBubble;
7085 }
7086
7087 private void ensureSearchManager() {
7088 if (mSearchManager != null) {
7089 return;
7090 }
7091
7092 try {
7093 mSearchManager = new SearchManager(this, null);
7094 } catch (ServiceNotFoundException e) {
7095 throw new IllegalStateException(e);
7096 }
7097 }
7098
7099 @Override
7100 public Object getSystemService(@ServiceName @NonNull String name) {
7101 if (getBaseContext() == null) {
7102 throw new IllegalStateException(
7103 "System services not available to Activities before onCreate()");
7104 }
7105
7106 if (WINDOW_SERVICE.equals(name)) {
7107 return mWindowManager;
7108 } else if (SEARCH_SERVICE.equals(name)) {
7109 ensureSearchManager();
7110 return mSearchManager;
7111 }
7112 return super.getSystemService(name);
7113 }
7114
7115 /**
7116 * Change the title associated with this activity. If this is a
7117 * top-level activity, the title for its window will change. If it
7118 * is an embedded activity, the parent can do whatever it wants
7119 * with it.
7120 */
7121 public void setTitle(CharSequence title) {
7122 mTitle = title;
7123 onTitleChanged(title, mTitleColor);
7124
7125 if (mParent != null) {
7126 mParent.onChildTitleChanged(this, title);
7127 }
7128 }
7129
7130 /**
7131 * Change the title associated with this activity. If this is a
7132 * top-level activity, the title for its window will change. If it
7133 * is an embedded activity, the parent can do whatever it wants
7134 * with it.
7135 */
7136 public void setTitle(int titleId) {
7137 setTitle(getText(titleId));
7138 }
7139
7140 /**
7141 * Change the color of the title associated with this activity.
7142 * <p>
7143 * This method is deprecated starting in API Level 11 and replaced by action
7144 * bar styles. For information on styling the Action Bar, read the <a
7145 * href="{@docRoot} guide/topics/ui/actionbar.html">Action Bar</a> developer
7146 * guide.
7147 *
7148 * @deprecated Use action bar styles instead.
7149 */
7150 @Deprecated
7151 public void setTitleColor(int textColor) {
7152 mTitleColor = textColor;
7153 onTitleChanged(mTitle, textColor);
7154 }
7155
7156 public final CharSequence getTitle() {
7157 return mTitle;
7158 }
7159
7160 public final int getTitleColor() {
7161 return mTitleColor;
7162 }
7163
7164 protected void onTitleChanged(CharSequence title, int color) {
7165 if (mTitleReady) {
7166 final Window win = getWindow();
7167 if (win != null) {
7168 win.setTitle(title);
7169 if (color != 0) {
7170 win.setTitleColor(color);
7171 }
7172 }
7173 if (mActionBar != null) {
7174 mActionBar.setWindowTitle(title);
7175 }
7176 }
7177 }
7178
7179 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
7180 }
7181
7182 /**
7183 * Sets information describing the task with this activity for presentation inside the Recents
7184 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
7185 * are traversed in order from the topmost activity to the bottommost. The traversal continues
7186 * for each property until a suitable value is found. For each task the taskDescription will be
7187 * returned in {@link android.app.ActivityManager.TaskDescription}.
7188 *
7189 * @see ActivityManager#getRecentTasks
7190 * @see android.app.ActivityManager.TaskDescription
7191 *
7192 * @param taskDescription The TaskDescription properties that describe the task with this activity
7193 */
7194 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
7195 if (mTaskDescription != taskDescription) {
7196 mTaskDescription.copyFromPreserveHiddenFields(taskDescription);
7197 // Scale the icon down to something reasonable if it is provided
7198 if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
7199 final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
7200 final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size,
7201 true);
7202 mTaskDescription.setIcon(Icon.createWithBitmap(icon));
7203 }
7204 }
7205 ActivityClient.getInstance().setTaskDescription(mToken, mTaskDescription);
7206 }
7207
7208 /**
7209 * Sets the visibility of the progress bar in the title.
7210 * <p>
7211 * In order for the progress bar to be shown, the feature must be requested
7212 * via {@link #requestWindowFeature(int)}.
7213 *
7214 * @param visible Whether to show the progress bars in the title.
7215 * @deprecated No longer supported starting in API 21.
7216 */
7217 @Deprecated
7218 public final void setProgressBarVisibility(boolean visible) {
7219 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
7220 Window.PROGRESS_VISIBILITY_OFF);
7221 }
7222
7223 /**
7224 * Sets the visibility of the indeterminate progress bar in the title.
7225 * <p>
7226 * In order for the progress bar to be shown, the feature must be requested
7227 * via {@link #requestWindowFeature(int)}.
7228 *
7229 * @param visible Whether to show the progress bars in the title.
7230 * @deprecated No longer supported starting in API 21.
7231 */
7232 @Deprecated
7233 public final void setProgressBarIndeterminateVisibility(boolean visible) {
7234 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
7235 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
7236 }
7237
7238 /**
7239 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
7240 * is always indeterminate).
7241 * <p>
7242 * In order for the progress bar to be shown, the feature must be requested
7243 * via {@link #requestWindowFeature(int)}.
7244 *
7245 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
7246 * @deprecated No longer supported starting in API 21.
7247 */
7248 @Deprecated
7249 public final void setProgressBarIndeterminate(boolean indeterminate) {
7250 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
7251 indeterminate ? Window.PROGRESS_INDETERMINATE_ON
7252 : Window.PROGRESS_INDETERMINATE_OFF);
7253 }
7254
7255 /**
7256 * Sets the progress for the progress bars in the title.
7257 * <p>
7258 * In order for the progress bar to be shown, the feature must be requested
7259 * via {@link #requestWindowFeature(int)}.
7260 *
7261 * @param progress The progress for the progress bar. Valid ranges are from
7262 * 0 to 10000 (both inclusive). If 10000 is given, the progress
7263 * bar will be completely filled and will fade out.
7264 * @deprecated No longer supported starting in API 21.
7265 */
7266 @Deprecated
7267 public final void setProgress(int progress) {
7268 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
7269 }
7270
7271 /**
7272 * Sets the secondary progress for the progress bar in the title. This
7273 * progress is drawn between the primary progress (set via
7274 * {@link #setProgress(int)} and the background. It can be ideal for media
7275 * scenarios such as showing the buffering progress while the default
7276 * progress shows the play progress.
7277 * <p>
7278 * In order for the progress bar to be shown, the feature must be requested
7279 * via {@link #requestWindowFeature(int)}.
7280 *
7281 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
7282 * 0 to 10000 (both inclusive).
7283 * @deprecated No longer supported starting in API 21.
7284 */
7285 @Deprecated
7286 public final void setSecondaryProgress(int secondaryProgress) {
7287 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
7288 secondaryProgress + Window.PROGRESS_SECONDARY_START);
7289 }
7290
7291 /**
7292 * Suggests an audio stream whose volume should be changed by the hardware
7293 * volume controls.
7294 * <p>
7295 * The suggested audio stream will be tied to the window of this Activity.
7296 * Volume requests which are received while the Activity is in the
7297 * foreground will affect this stream.
7298 * <p>
7299 * It is not guaranteed that the hardware volume controls will always change
7300 * this stream's volume (for example, if a call is in progress, its stream's
7301 * volume may be changed instead). To reset back to the default, use
7302 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
7303 *
7304 * @param streamType The type of the audio stream whose volume should be
7305 * changed by the hardware volume controls.
7306 */
7307 public final void setVolumeControlStream(int streamType) {
7308 getWindow().setVolumeControlStream(streamType);
7309 }
7310
7311 /**
7312 * Gets the suggested audio stream whose volume should be changed by the
7313 * hardware volume controls.
7314 *
7315 * @return The suggested audio stream type whose volume should be changed by
7316 * the hardware volume controls.
7317 * @see #setVolumeControlStream(int)
7318 */
7319 public final int getVolumeControlStream() {
7320 return getWindow().getVolumeControlStream();
7321 }
7322
7323 /**
7324 * Sets a {@link MediaController} to send media keys and volume changes to.
7325 * <p>
7326 * The controller will be tied to the window of this Activity. Media key and
7327 * volume events which are received while the Activity is in the foreground
7328 * will be forwarded to the controller and used to invoke transport controls
7329 * or adjust the volume. This may be used instead of or in addition to
7330 * {@link #setVolumeControlStream} to affect a specific session instead of a
7331 * specific stream.
7332 * <p>
7333 * It is not guaranteed that the hardware volume controls will always change
7334 * this session's volume (for example, if a call is in progress, its
7335 * stream's volume may be changed instead). To reset back to the default use
7336 * null as the controller.
7337 *
7338 * @param controller The controller for the session which should receive
7339 * media keys and volume changes.
7340 */
7341 public final void setMediaController(MediaController controller) {
7342 getWindow().setMediaController(controller);
7343 }
7344
7345 /**
7346 * Gets the controller which should be receiving media key and volume events
7347 * while this activity is in the foreground.
7348 *
7349 * @return The controller which should receive events.
7350 * @see #setMediaController(android.media.session.MediaController)
7351 */
7352 public final MediaController getMediaController() {
7353 return getWindow().getMediaController();
7354 }
7355
7356 /**
7357 * Runs the specified action on the UI thread. If the current thread is the UI
7358 * thread, then the action is executed immediately. If the current thread is
7359 * not the UI thread, the action is posted to the event queue of the UI thread.
7360 *
7361 * @param action the action to run on the UI thread
7362 */
7363 public final void runOnUiThread(Runnable action) {
7364 if (Thread.currentThread() != mUiThread) {
7365 mHandler.post(action);
7366 } else {
7367 action.run();
7368 }
7369 }
7370
7371 /**
7372 * Standard implementation of
7373 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
7374 * inflating with the LayoutInflater returned by {@link #getSystemService}.
7375 * This implementation does nothing and is for
7376 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
7377 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
7378 *
7379 * @see android.view.LayoutInflater#createView
7380 * @see android.view.Window#getLayoutInflater
7381 */
7382 @Nullable
7383 public View onCreateView(@NonNull String name, @NonNull Context context,
7384 @NonNull AttributeSet attrs) {
7385 return null;
7386 }
7387
7388 /**
7389 * Standard implementation of
7390 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
7391 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
7392 * This implementation handles <fragment> tags to embed fragments inside
7393 * of the activity.
7394 *
7395 * @see android.view.LayoutInflater#createView
7396 * @see android.view.Window#getLayoutInflater
7397 */
7398 @Nullable
7399 public View onCreateView(@Nullable View parent, @NonNull String name,
7400 @NonNull Context context, @NonNull AttributeSet attrs) {
7401 if (!"fragment".equals(name)) {
7402 return onCreateView(name, context, attrs);
7403 }
7404
7405 return mFragments.onCreateView(parent, name, context, attrs);
7406 }
7407
7408 /**
7409 * Print the Activity's state into the given stream. This gets invoked if
7410 * you run <code>adb shell dumpsys activity &lt;activity_component_name&gt;</code>.
7411 *
7412 * <p>This method won't be called if the app targets
7413 * {@link android.os.Build.VERSION_CODES#TIRAMISU} or later if the dump request starts with one
7414 * of the following arguments:
7415 * <ul>
7416 * <li>--autofill
7417 * <li>--contentcapture
7418 * <li>--translation
7419 * <li>--list-dumpables
7420 * <li>--dump-dumpable
7421 * </ul>
7422 *
7423 * @param prefix Desired prefix to prepend at each line of output.
7424 * @param fd The raw file descriptor that the dump is being sent to.
7425 * @param writer The PrintWriter to which you should dump your state. This will be
7426 * closed for you after you return.
7427 * @param args additional arguments to the dump request.
7428 */
7429 public void dump(@NonNull String prefix, @Nullable FileDescriptor fd,
7430 @NonNull PrintWriter writer, @Nullable String[] args) {
7431 dumpInner(prefix, fd, writer, args);
7432 }
7433
7434 /**
7435 * See {@link android.util.DumpableContainer#addDumpable(Dumpable)}.
7436 *
7437 * @hide
7438 */
7439 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
7440 @TestApi
7441 public final boolean addDumpable(@NonNull Dumpable dumpable) {
7442 if (mDumpableContainer == null) {
7443 mDumpableContainer = new DumpableContainerImpl();
7444 }
7445 return mDumpableContainer.addDumpable(dumpable);
7446 }
7447
7448 /**
7449 * This is the real method called by {@code ActivityThread}, but it's also exposed so
7450 * CTS can test for the special args cases.
7451 *
7452 * @hide
7453 */
7454 @TestApi
7455 @VisibleForTesting
7456 @SuppressLint("OnNameExpected")
7457 public void dumpInternal(@NonNull String prefix,
7458 @SuppressLint("UseParcelFileDescriptor") @Nullable FileDescriptor fd,
7459 @NonNull PrintWriter writer, @Nullable String[] args) {
7460
7461 // Lazy-load mDumpableContainer with Dumpables activity might already have a reference to
7462 if (mAutofillClientController != null) {
7463 addDumpable(mAutofillClientController);
7464 }
7465 if (mUiTranslationController != null) {
7466 addDumpable(mUiTranslationController);
7467 }
7468 if (mContentCaptureManager != null) {
7469 mContentCaptureManager.addDumpable(this);
7470 }
7471
7472 boolean dumpInternalState = true;
7473 String arg = null;
7474 if (args != null && args.length > 0) {
7475 arg = args[0];
7476 boolean isSpecialCase = true;
7477 // Handle special cases
7478 switch (arg) {
7479 case DUMP_ARG_AUTOFILL:
7480 dumpLegacyDumpable(prefix, writer, arg,
7481 AutofillClientController.DUMPABLE_NAME);
7482 return;
7483 case DUMP_ARG_CONTENT_CAPTURE:
7484 dumpLegacyDumpable(prefix, writer, arg,
7485 ContentCaptureManager.DUMPABLE_NAME);
7486 return;
7487 case DUMP_ARG_TRANSLATION:
7488 dumpLegacyDumpable(prefix, writer, arg,
7489 UiTranslationController.DUMPABLE_NAME);
7490 return;
7491 case DUMP_ARG_LIST_DUMPABLES:
7492 if (mDumpableContainer == null) {
7493 writer.print(prefix); writer.println("No dumpables");
7494 } else {
7495 mDumpableContainer.listDumpables(prefix, writer);
7496 }
7497 return;
7498 case DUMP_ARG_DUMP_DUMPABLE:
7499 if (args.length == 1) {
7500 writer.print(DUMP_ARG_DUMP_DUMPABLE);
7501 writer.println(" requires the dumpable name");
7502 } else if (mDumpableContainer == null) {
7503 writer.println("no dumpables");
7504 } else {
7505 // Strips --dump-dumpable NAME
7506 String[] prunedArgs = new String[args.length - 2];
7507 System.arraycopy(args, 2, prunedArgs, 0, prunedArgs.length);
7508 mDumpableContainer.dumpOneDumpable(prefix, writer, args[1], prunedArgs);
7509 }
7510 break;
7511 default:
7512 isSpecialCase = false;
7513 break;
7514 }
7515 if (isSpecialCase) {
7516 dumpInternalState = !CompatChanges.isChangeEnabled(DUMP_IGNORES_SPECIAL_ARGS);
7517 }
7518 }
7519
7520 if (dumpInternalState) {
7521 dump(prefix, fd, writer, args);
7522 } else {
7523 Log.i(TAG, "Not calling dump() on " + this + " because of special argument " + arg);
7524 }
7525 }
7526
7527 void dumpInner(@NonNull String prefix, @Nullable FileDescriptor fd,
7528 @NonNull PrintWriter writer, @Nullable String[] args) {
7529 String innerPrefix = prefix + " ";
7530
7531 writer.print(prefix); writer.print("Local Activity ");
7532 writer.print(Integer.toHexString(System.identityHashCode(this)));
7533 writer.println(" State:");
7534 writer.print(innerPrefix); writer.print("mResumed=");
7535 writer.print(mResumed); writer.print(" mStopped=");
7536 writer.print(mStopped); writer.print(" mFinished=");
7537 writer.println(mFinished);
7538 writer.print(innerPrefix); writer.print("mIsInMultiWindowMode=");
7539 writer.print(mIsInMultiWindowMode);
7540 writer.print(" mIsInPictureInPictureMode=");
7541 writer.println(mIsInPictureInPictureMode);
7542 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
7543 writer.println(mChangingConfigurations);
7544 writer.print(innerPrefix); writer.print("mCurrentConfig=");
7545 writer.println(mCurrentConfig);
7546
7547 mFragments.dumpLoaders(innerPrefix, fd, writer, args);
7548 mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args);
7549 if (mVoiceInteractor != null) {
7550 mVoiceInteractor.dump(innerPrefix, fd, writer, args);
7551 }
7552
7553 if (getWindow() != null &&
7554 getWindow().peekDecorView() != null &&
7555 getWindow().peekDecorView().getViewRootImpl() != null) {
7556 getWindow().peekDecorView().getViewRootImpl().dump(prefix, writer);
7557 }
7558
7559 mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix);
7560
7561 ResourcesManager.getInstance().dump(prefix, writer);
7562
7563 if (mDumpableContainer != null) {
7564 mDumpableContainer.dumpAllDumpables(prefix, writer, args);
7565 }
7566 }
7567
7568 private void dumpLegacyDumpable(String prefix, PrintWriter writer, String legacyOption,
7569 String dumpableName) {
7570 writer.printf("%s%s option deprecated. Use %s %s instead\n", prefix, legacyOption,
7571 DUMP_ARG_DUMP_DUMPABLE, dumpableName);
7572 }
7573
7574 /**
7575 * Bit indicating that this activity is "immersive" and should not be
7576 * interrupted by notifications if possible.
7577 *
7578 * This value is initially set by the manifest property
7579 * <code>android:immersive</code> but may be changed at runtime by
7580 * {@link #setImmersive}.
7581 *
7582 * @see #setImmersive(boolean)
7583 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
7584 */
7585 public boolean isImmersive() {
7586 return ActivityClient.getInstance().isImmersive(mToken);
7587 }
7588
7589 /**
7590 * Indication of whether this is the highest level activity in this task. Can be used to
7591 * determine whether an activity launched by this activity was placed in the same task or
7592 * another task.
7593 *
7594 * @return true if this is the topmost, non-finishing activity in its task.
7595 */
7596 final boolean isTopOfTask() {
7597 if (mToken == null || mWindow == null) {
7598 return false;
7599 }
7600 return ActivityClient.getInstance().isTopOfTask(getActivityToken());
7601 }
7602
7603 /**
7604 * Convert an activity, which particularly with {@link android.R.attr#windowIsTranslucent} or
7605 * {@link android.R.attr#windowIsFloating} attribute, to a fullscreen opaque activity, or
7606 * convert it from opaque back to translucent.
7607 *
7608 * @param translucent {@code true} convert from opaque to translucent.
7609 * {@code false} convert from translucent to opaque.
7610 * @return The result of setting translucency. Return {@code true} if set successfully,
7611 * {@code false} otherwise.
7612 */
7613 public boolean setTranslucent(boolean translucent) {
7614 if (translucent) {
7615 return convertToTranslucent(null /* callback */, null /* options */);
7616 } else {
7617 return convertFromTranslucentInternal();
7618 }
7619 }
7620
7621 /**
7622 * Convert an activity to a fullscreen opaque activity.
7623 * <p>
7624 * Call this whenever the background of a translucent activity has changed to become opaque.
7625 * Doing so will allow the {@link android.view.Surface} of the activity behind to be released.
7626 *
7627 * @see #convertToTranslucent(android.app.Activity.TranslucentConversionListener,
7628 * ActivityOptions)
7629 * @see TranslucentConversionListener
7630 *
7631 * @hide
7632 */
7633 @SystemApi
7634 public void convertFromTranslucent() {
7635 convertFromTranslucentInternal();
7636 }
7637
7638 private boolean convertFromTranslucentInternal() {
7639 mTranslucentCallback = null;
7640 if (ActivityClient.getInstance().convertFromTranslucent(mToken)) {
7641 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true /* opaque */);
7642 return true;
7643 }
7644 return false;
7645 }
7646
7647 /**
7648 * Convert an activity to a translucent activity.
7649 * <p>
7650 * Calling this allows the activity behind this one to be seen again. Once all such activities
7651 * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
7652 * be called indicating that it is safe to make this activity translucent again. Until
7653 * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
7654 * behind the frontmost activity will be indeterminate.
7655 *
7656 * @param callback the method to call when all visible activities behind this one have been
7657 * drawn and it is safe to make this activity translucent again.
7658 * @param options activity options delivered to the activity below this one. The options
7659 * are retrieved using {@link #getActivityOptions}.
7660 * @return <code>true</code> if Window was opaque and will become translucent or
7661 * <code>false</code> if window was translucent and no change needed to be made.
7662 *
7663 * @see #convertFromTranslucent()
7664 * @see TranslucentConversionListener
7665 *
7666 * @hide
7667 */
7668 @SystemApi
7669 public boolean convertToTranslucent(TranslucentConversionListener callback,
7670 ActivityOptions options) {
7671 mTranslucentCallback = callback;
7672 mChangeCanvasToTranslucent = ActivityClient.getInstance().convertToTranslucent(
7673 mToken, options == null ? null : options.toBundle());
7674 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
7675
7676 if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) {
7677 // Window is already translucent.
7678 mTranslucentCallback.onTranslucentConversionComplete(true /* drawComplete */);
7679 }
7680 return mChangeCanvasToTranslucent;
7681 }
7682
7683 /** @hide */
7684 void onTranslucentConversionComplete(boolean drawComplete) {
7685 if (mTranslucentCallback != null) {
7686 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
7687 mTranslucentCallback = null;
7688 }
7689 if (mChangeCanvasToTranslucent) {
7690 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
7691 }
7692 }
7693
7694 /** @hide */
7695 public void onNewActivityOptions(ActivityOptions options) {
7696 mActivityTransitionState.setEnterActivityOptions(this, options);
7697 if (!mStopped) {
7698 mActivityTransitionState.enterReady(this);
7699 }
7700 }
7701
7702 /**
7703 * Takes the ActivityOptions passed in from the launching activity or passed back
7704 * from an activity launched by this activity in its call to {@link
7705 * #convertToTranslucent(TranslucentConversionListener, ActivityOptions)}
7706 *
7707 * @return The ActivityOptions passed to {@link #convertToTranslucent}.
7708 * @hide
7709 */
7710 @UnsupportedAppUsage
7711 ActivityOptions getActivityOptions() {
7712 final ActivityOptions options = mPendingOptions;
7713 // The option only applies once.
7714 mPendingOptions = null;
7715 return options;
7716 }
7717
7718 /**
7719 * Activities that want to remain visible behind a translucent activity above them must call
7720 * this method anytime between the start of {@link #onResume()} and the return from
7721 * {@link #onPause()}. If this call is successful then the activity will remain visible after
7722 * {@link #onPause()} is called, and is allowed to continue playing media in the background.
7723 *
7724 * <p>The actions of this call are reset each time that this activity is brought to the
7725 * front. That is, every time {@link #onResume()} is called the activity will be assumed
7726 * to not have requested visible behind. Therefore, if you want this activity to continue to
7727 * be visible in the background you must call this method again.
7728 *
7729 * <p>Only fullscreen opaque activities may make this call. I.e. this call is a nop
7730 * for dialog and translucent activities.
7731 *
7732 * <p>Under all circumstances, the activity must stop playing and release resources prior to or
7733 * within a call to {@link #onVisibleBehindCanceled()} or if this call returns false.
7734 *
7735 * <p>False will be returned any time this method is called between the return of onPause and
7736 * the next call to onResume.
7737 *
7738 * @deprecated This method's functionality is no longer supported as of
7739 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
7740 *
7741 * @param visible true to notify the system that the activity wishes to be visible behind other
7742 * translucent activities, false to indicate otherwise. Resources must be
7743 * released when passing false to this method.
7744 *
7745 * @return the resulting visibiity state. If true the activity will remain visible beyond
7746 * {@link #onPause()} if the next activity is translucent or not fullscreen. If false
7747 * then the activity may not count on being visible behind other translucent activities,
7748 * and must stop any media playback and release resources.
7749 * Returning false may occur in lieu of a call to {@link #onVisibleBehindCanceled()} so
7750 * the return value must be checked.
7751 *
7752 * @see #onVisibleBehindCanceled()
7753 */
7754 @Deprecated
7755 public boolean requestVisibleBehind(boolean visible) {
7756 return false;
7757 }
7758
7759 /**
7760 * Called when a translucent activity over this activity is becoming opaque or another
7761 * activity is being launched. Activities that override this method must call
7762 * <code>super.onVisibleBehindCanceled()</code> or a SuperNotCalledException will be thrown.
7763 *
7764 * <p>When this method is called the activity has 500 msec to release any resources it may be
7765 * using while visible in the background.
7766 * If the activity has not returned from this method in 500 msec the system will destroy
7767 * the activity and kill the process in order to recover the resources for another
7768 * process. Otherwise {@link #onStop()} will be called following return.
7769 *
7770 * @see #requestVisibleBehind(boolean)
7771 *
7772 * @deprecated This method's functionality is no longer supported as of
7773 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
7774 */
7775 @Deprecated
7776 @CallSuper
7777 public void onVisibleBehindCanceled() {
7778 mCalled = true;
7779 }
7780
7781 /**
7782 * Translucent activities may call this to determine if there is an activity below them that
7783 * is currently set to be visible in the background.
7784 *
7785 * @deprecated This method's functionality is no longer supported as of
7786 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
7787 *
7788 * @return true if an activity below is set to visible according to the most recent call to
7789 * {@link #requestVisibleBehind(boolean)}, false otherwise.
7790 *
7791 * @see #requestVisibleBehind(boolean)
7792 * @see #onVisibleBehindCanceled()
7793 * @see #onBackgroundVisibleBehindChanged(boolean)
7794 * @hide
7795 */
7796 @Deprecated
7797 @SystemApi
7798 public boolean isBackgroundVisibleBehind() {
7799 return false;
7800 }
7801
7802 /**
7803 * The topmost foreground activity will receive this call when the background visibility state
7804 * of the activity below it changes.
7805 *
7806 * This call may be a consequence of {@link #requestVisibleBehind(boolean)} or might be
7807 * due to a background activity finishing itself.
7808 *
7809 * @deprecated This method's functionality is no longer supported as of
7810 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
7811 *
7812 * @param visible true if a background activity is visible, false otherwise.
7813 *
7814 * @see #requestVisibleBehind(boolean)
7815 * @see #onVisibleBehindCanceled()
7816 * @hide
7817 */
7818 @Deprecated
7819 @SystemApi
7820 public void onBackgroundVisibleBehindChanged(boolean visible) {
7821 }
7822
7823 /**
7824 * Activities cannot draw during the period that their windows are animating in. In order
7825 * to know when it is safe to begin drawing they can override this method which will be
7826 * called when the entering animation has completed.
7827 */
7828 public void onEnterAnimationComplete() {
7829 }
7830
7831 /**
7832 * @hide
7833 */
7834 public void dispatchEnterAnimationComplete() {
7835 mEnterAnimationComplete = true;
7836 mInstrumentation.onEnterAnimationComplete();
7837 onEnterAnimationComplete();
7838 if (getWindow() != null && getWindow().getDecorView() != null) {
7839 View decorView = getWindow().getDecorView();
7840 decorView.getViewTreeObserver().dispatchOnEnterAnimationComplete();
7841 }
7842 }
7843
7844 /**
7845 * Adjust the current immersive mode setting.
7846 *
7847 * Note that changing this value will have no effect on the activity's
7848 * {@link android.content.pm.ActivityInfo} structure; that is, if
7849 * <code>android:immersive</code> is set to <code>true</code>
7850 * in the application's manifest entry for this activity, the {@link
7851 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
7852 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
7853 * FLAG_IMMERSIVE} bit set.
7854 *
7855 * @see #isImmersive()
7856 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
7857 */
7858 public void setImmersive(boolean i) {
7859 ActivityClient.getInstance().setImmersive(mToken, i);
7860 }
7861
7862 /**
7863 * Enable or disable virtual reality (VR) mode for this Activity.
7864 *
7865 * <p>VR mode is a hint to Android system to switch to a mode optimized for VR applications
7866 * while this Activity has user focus.</p>
7867 *
7868 * <p>It is recommended that applications additionally declare
7869 * {@link android.R.attr#enableVrMode} in their manifest to allow for smooth activity
7870 * transitions when switching between VR activities.</p>
7871 *
7872 * <p>If the requested {@link android.service.vr.VrListenerService} component is not available,
7873 * VR mode will not be started. Developers can handle this case as follows:</p>
7874 *
7875 * <pre>
7876 * String servicePackage = "com.whatever.app";
7877 * String serviceClass = "com.whatever.app.MyVrListenerService";
7878 *
7879 * // Name of the component of the VrListenerService to start.
7880 * ComponentName serviceComponent = new ComponentName(servicePackage, serviceClass);
7881 *
7882 * try {
7883 * setVrModeEnabled(true, myComponentName);
7884 * } catch (PackageManager.NameNotFoundException e) {
7885 * List&lt;ApplicationInfo> installed = getPackageManager().getInstalledApplications(0);
7886 * boolean isInstalled = false;
7887 * for (ApplicationInfo app : installed) {
7888 * if (app.packageName.equals(servicePackage)) {
7889 * isInstalled = true;
7890 * break;
7891 * }
7892 * }
7893 * if (isInstalled) {
7894 * // Package is installed, but not enabled in Settings. Let user enable it.
7895 * startActivity(new Intent(Settings.ACTION_VR_LISTENER_SETTINGS));
7896 * } else {
7897 * // Package is not installed. Send an intent to download this.
7898 * sentIntentToLaunchAppStore(servicePackage);
7899 * }
7900 * }
7901 * </pre>
7902 *
7903 * @param enabled {@code true} to enable this mode.
7904 * @param requestedComponent the name of the component to use as a
7905 * {@link android.service.vr.VrListenerService} while VR mode is enabled.
7906 *
7907 * @throws android.content.pm.PackageManager.NameNotFoundException if the given component
7908 * to run as a {@link android.service.vr.VrListenerService} is not installed, or has
7909 * not been enabled in user settings.
7910 *
7911 * @see android.content.pm.PackageManager#FEATURE_VR_MODE_HIGH_PERFORMANCE
7912 * @see android.service.vr.VrListenerService
7913 * @see android.provider.Settings#ACTION_VR_LISTENER_SETTINGS
7914 * @see android.R.attr#enableVrMode
7915 */
7916 public void setVrModeEnabled(boolean enabled, @NonNull ComponentName requestedComponent)
7917 throws PackageManager.NameNotFoundException {
7918 if (ActivityClient.getInstance().setVrMode(mToken, enabled, requestedComponent) != 0) {
7919 throw new PackageManager.NameNotFoundException(requestedComponent.flattenToString());
7920 }
7921 }
7922
7923 /**
7924 * Start an action mode of the default type {@link ActionMode#TYPE_PRIMARY}.
7925 *
7926 * @param callback Callback that will manage lifecycle events for this action mode
7927 * @return The ActionMode that was started, or null if it was canceled
7928 *
7929 * @see ActionMode
7930 */
7931 @Nullable
7932 public ActionMode startActionMode(ActionMode.Callback callback) {
7933 return mWindow.getDecorView().startActionMode(callback);
7934 }
7935
7936 /**
7937 * Start an action mode of the given type.
7938 *
7939 * @param callback Callback that will manage lifecycle events for this action mode
7940 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
7941 * @return The ActionMode that was started, or null if it was canceled
7942 *
7943 * @see ActionMode
7944 */
7945 @Nullable
7946 public ActionMode startActionMode(ActionMode.Callback callback, int type) {
7947 return mWindow.getDecorView().startActionMode(callback, type);
7948 }
7949
7950 /**
7951 * Give the Activity a chance to control the UI for an action mode requested
7952 * by the system.
7953 *
7954 * <p>Note: If you are looking for a notification callback that an action mode
7955 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
7956 *
7957 * @param callback The callback that should control the new action mode
7958 * @return The new action mode, or <code>null</code> if the activity does not want to
7959 * provide special handling for this action mode. (It will be handled by the system.)
7960 */
7961 @Nullable
7962 @Override
7963 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
7964 // Only Primary ActionModes are represented in the ActionBar.
7965 if (mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
7966 initWindowDecorActionBar();
7967 if (mActionBar != null) {
7968 return mActionBar.startActionMode(callback);
7969 }
7970 }
7971 return null;
7972 }
7973
7974 /**
7975 * {@inheritDoc}
7976 */
7977 @Nullable
7978 @Override
7979 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
7980 try {
7981 mActionModeTypeStarting = type;
7982 return onWindowStartingActionMode(callback);
7983 } finally {
7984 mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
7985 }
7986 }
7987
7988 /**
7989 * Notifies the Activity that an action mode has been started.
7990 * Activity subclasses overriding this method should call the superclass implementation.
7991 *
7992 * @param mode The new action mode.
7993 */
7994 @CallSuper
7995 @Override
7996 public void onActionModeStarted(ActionMode mode) {
7997 }
7998
7999 /**
8000 * Notifies the activity that an action mode has finished.
8001 * Activity subclasses overriding this method should call the superclass implementation.
8002 *
8003 * @param mode The action mode that just finished.
8004 */
8005 @CallSuper
8006 @Override
8007 public void onActionModeFinished(ActionMode mode) {
8008 }
8009
8010 /**
8011 * Returns true if the app should recreate the task when navigating 'up' from this activity
8012 * by using targetIntent.
8013 *
8014 * <p>If this method returns false the app can trivially call
8015 * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
8016 * up navigation. If this method returns false, the app should synthesize a new task stack
8017 * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
8018 *
8019 * @param targetIntent An intent representing the target destination for up navigation
8020 * @return true if navigating up should recreate a new task stack, false if the same task
8021 * should be used for the destination
8022 */
8023 public boolean shouldUpRecreateTask(Intent targetIntent) {
8024 try {
8025 PackageManager pm = getPackageManager();
8026 ComponentName cn = targetIntent.getComponent();
8027 if (cn == null) {
8028 cn = targetIntent.resolveActivity(pm);
8029 }
8030 ActivityInfo info = pm.getActivityInfo(cn, 0);
8031 if (info.taskAffinity == null) {
8032 return false;
8033 }
8034 return ActivityClient.getInstance().shouldUpRecreateTask(mToken, info.taskAffinity);
8035 } catch (NameNotFoundException e) {
8036 return false;
8037 }
8038 }
8039
8040 /**
8041 * Navigate from this activity to the activity specified by upIntent, finishing this activity
8042 * in the process. If the activity indicated by upIntent already exists in the task's history,
8043 * this activity and all others before the indicated activity in the history stack will be
8044 * finished.
8045 *
8046 * <p>If the indicated activity does not appear in the history stack, this will finish
8047 * each activity in this task until the root activity of the task is reached, resulting in
8048 * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
8049 * when an activity may be reached by a path not passing through a canonical parent
8050 * activity.</p>
8051 *
8052 * <p>This method should be used when performing up navigation from within the same task
8053 * as the destination. If up navigation should cross tasks in some cases, see
8054 * {@link #shouldUpRecreateTask(Intent)}.</p>
8055 *
8056 * @param upIntent An intent representing the target destination for up navigation
8057 *
8058 * @return true if up navigation successfully reached the activity indicated by upIntent and
8059 * upIntent was delivered to it. false if an instance of the indicated activity could
8060 * not be found and this activity was simply finished normally.
8061 */
8062 public boolean navigateUpTo(Intent upIntent) {
8063 if (mParent == null) {
8064 ComponentName destInfo = upIntent.getComponent();
8065 if (destInfo == null) {
8066 destInfo = upIntent.resolveActivity(getPackageManager());
8067 if (destInfo == null) {
8068 return false;
8069 }
8070 upIntent = new Intent(upIntent);
8071 upIntent.setComponent(destInfo);
8072 }
8073 int resultCode;
8074 Intent resultData;
8075 synchronized (this) {
8076 resultCode = mResultCode;
8077 resultData = mResultData;
8078 }
8079 if (resultData != null) {
8080 resultData.prepareToLeaveProcess(this);
8081 }
8082 upIntent.prepareToLeaveProcess(this);
8083 String resolvedType = upIntent.resolveTypeIfNeeded(getContentResolver());
8084 return ActivityClient.getInstance().navigateUpTo(mToken, upIntent, resolvedType,
8085 resultCode, resultData);
8086 } else {
8087 return mParent.navigateUpToFromChild(this, upIntent);
8088 }
8089 }
8090
8091 /**
8092 * This is called when a child activity of this one calls its
8093 * {@link #navigateUpTo} method. The default implementation simply calls
8094 * navigateUpTo(upIntent) on this activity (the parent).
8095 *
8096 * @param child The activity making the call.
8097 * @param upIntent An intent representing the target destination for up navigation
8098 *
8099 * @return true if up navigation successfully reached the activity indicated by upIntent and
8100 * upIntent was delivered to it. false if an instance of the indicated activity could
8101 * not be found and this activity was simply finished normally.
8102 * @deprecated Use {@link #navigateUpTo(Intent)} instead.
8103 */
8104 @Deprecated
8105 public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
8106 return navigateUpTo(upIntent);
8107 }
8108
8109 /**
8110 * Obtain an {@link Intent} that will launch an explicit target activity specified by
8111 * this activity's logical parent. The logical parent is named in the application's manifest
8112 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
8113 * Activity subclasses may override this method to modify the Intent returned by
8114 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
8115 * the parent intent entirely.
8116 *
8117 * @return a new Intent targeting the defined parent of this activity or null if
8118 * there is no valid parent.
8119 */
8120 @Nullable
8121 public Intent getParentActivityIntent() {
8122 final String parentName = mActivityInfo.parentActivityName;
8123 if (TextUtils.isEmpty(parentName)) {
8124 return null;
8125 }
8126
8127 // If the parent itself has no parent, generate a main activity intent.
8128 final ComponentName target = new ComponentName(this, parentName);
8129 try {
8130 final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
8131 final String parentActivity = parentInfo.parentActivityName;
8132 final Intent parentIntent = parentActivity == null
8133 ? Intent.makeMainActivity(target)
8134 : new Intent().setComponent(target);
8135 return parentIntent;
8136 } catch (NameNotFoundException e) {
8137 Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
8138 "' in manifest");
8139 return null;
8140 }
8141 }
8142
8143 /**
8144 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
8145 * android.view.View, String)} was used to start an Activity, <var>callback</var>
8146 * will be called to handle shared elements on the <i>launched</i> Activity. This requires
8147 * {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
8148 *
8149 * @param callback Used to manipulate shared element transitions on the launched Activity.
8150 */
8151 public void setEnterSharedElementCallback(SharedElementCallback callback) {
8152 if (callback == null) {
8153 callback = SharedElementCallback.NULL_CALLBACK;
8154 }
8155 mEnterTransitionListener = callback;
8156 }
8157
8158 /**
8159 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
8160 * android.view.View, String)} was used to start an Activity, <var>callback</var>
8161 * will be called to handle shared elements on the <i>launching</i> Activity. Most
8162 * calls will only come when returning from the started Activity.
8163 * This requires {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
8164 *
8165 * @param callback Used to manipulate shared element transitions on the launching Activity.
8166 */
8167 public void setExitSharedElementCallback(SharedElementCallback callback) {
8168 if (callback == null) {
8169 callback = SharedElementCallback.NULL_CALLBACK;
8170 }
8171 mExitTransitionListener = callback;
8172 }
8173
8174 /**
8175 * Postpone the entering activity transition when Activity was started with
8176 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
8177 * android.util.Pair[])}.
8178 * <p>This method gives the Activity the ability to delay starting the entering and
8179 * shared element transitions until all data is loaded. Until then, the Activity won't
8180 * draw into its window, leaving the window transparent. This may also cause the
8181 * returning animation to be delayed until data is ready. This method should be
8182 * called in {@link #onCreate(android.os.Bundle)} or in
8183 * {@link #onActivityReenter(int, android.content.Intent)}.
8184 * {@link #startPostponedEnterTransition()} must be called to allow the Activity to
8185 * start the transitions. If the Activity did not use
8186 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
8187 * android.util.Pair[])}, then this method does nothing.</p>
8188 */
8189 public void postponeEnterTransition() {
8190 mActivityTransitionState.postponeEnterTransition();
8191 }
8192
8193 /**
8194 * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
8195 * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
8196 * to have your Activity start drawing.
8197 */
8198 public void startPostponedEnterTransition() {
8199 mActivityTransitionState.startPostponedEnterTransition();
8200 }
8201
8202 /**
8203 * Create {@link DragAndDropPermissions} object bound to this activity and controlling the
8204 * access permissions for content URIs associated with the {@link DragEvent}.
8205 * @param event Drag event
8206 * @return The {@link DragAndDropPermissions} object used to control access to the content URIs.
8207 * Null if no content URIs are associated with the event or if permissions could not be granted.
8208 */
8209 public DragAndDropPermissions requestDragAndDropPermissions(DragEvent event) {
8210 DragAndDropPermissions dragAndDropPermissions = DragAndDropPermissions.obtain(event);
8211 if (dragAndDropPermissions != null && dragAndDropPermissions.take(getActivityToken())) {
8212 return dragAndDropPermissions;
8213 }
8214 return null;
8215 }
8216
8217 // ------------------ Internal API ------------------
8218
8219 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
8220 final void setParent(Activity parent) {
8221 mParent = parent;
8222 }
8223
8224 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
8225 final void attach(Context context, ActivityThread aThread,
8226 Instrumentation instr, IBinder token, int ident,
8227 Application application, Intent intent, ActivityInfo info,
8228 CharSequence title, Activity parent, String id,
8229 NonConfigurationInstances lastNonConfigurationInstances,
8230 Configuration config, String referrer, IVoiceInteractor voiceInteractor,
8231 Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken,
8232 IBinder shareableActivityToken) {
8233 attachBaseContext(context);
8234
8235 mFragments.attachHost(null /*parent*/);
8236
8237 mWindow = new PhoneWindow(this, window, activityConfigCallback);
8238 mWindow.setWindowControllerCallback(mWindowControllerCallback);
8239 mWindow.setCallback(this);
8240 mWindow.setOnWindowDismissedCallback(this);
8241 mWindow.getLayoutInflater().setPrivateFactory(this);
8242 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
8243 mWindow.setSoftInputMode(info.softInputMode);
8244 }
8245 if (info.uiOptions != 0) {
8246 mWindow.setUiOptions(info.uiOptions);
8247 }
8248 mUiThread = Thread.currentThread();
8249
8250 mMainThread = aThread;
8251 mInstrumentation = instr;
8252 mToken = token;
8253 mAssistToken = assistToken;
8254 mShareableActivityToken = shareableActivityToken;
8255 mIdent = ident;
8256 mApplication = application;
8257 mIntent = intent;
8258 mReferrer = referrer;
8259 mComponent = intent.getComponent();
8260 mActivityInfo = info;
8261 mTitle = title;
8262 mParent = parent;
8263 mEmbeddedID = id;
8264 mLastNonConfigurationInstances = lastNonConfigurationInstances;
8265 if (voiceInteractor != null) {
8266 if (lastNonConfigurationInstances != null) {
8267 mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
8268 } else {
8269 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
8270 Looper.myLooper());
8271 }
8272 }
8273
8274 mWindow.setWindowManager(
8275 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
8276 mToken, mComponent.flattenToString(),
8277 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
8278 if (mParent != null) {
8279 mWindow.setContainer(mParent.getWindow());
8280 }
8281 mWindowManager = mWindow.getWindowManager();
8282 mCurrentConfig = config;
8283
8284 mWindow.setColorMode(info.colorMode);
8285 mWindow.setPreferMinimalPostProcessing(
8286 (info.flags & ActivityInfo.FLAG_PREFER_MINIMAL_POST_PROCESSING) != 0);
8287
8288 getAutofillClientController().onActivityAttached(application);
8289 setContentCaptureOptions(application.getContentCaptureOptions());
8290 }
8291
8292 /** @hide */
8293 @UnsupportedAppUsage
8294 public final IBinder getActivityToken() {
8295 return mParent != null ? mParent.getActivityToken() : mToken;
8296 }
8297
8298 /** @hide */
8299 public final IBinder getAssistToken() {
8300 return mParent != null ? mParent.getAssistToken() : mAssistToken;
8301 }
8302
8303 /** @hide */
8304 public final IBinder getShareableActivityToken() {
8305 return mParent != null ? mParent.getShareableActivityToken() : mShareableActivityToken;
8306 }
8307
8308 /** @hide */
8309 @VisibleForTesting
8310 public final ActivityThread getActivityThread() {
8311 return mMainThread;
8312 }
8313
8314 /** @hide */
8315 public final ActivityInfo getActivityInfo() {
8316 return mActivityInfo;
8317 }
8318
8319 final void performCreate(Bundle icicle) {
8320 performCreate(icicle, null);
8321 }
8322
8323 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
8324 final void performCreate(Bundle icicle, PersistableBundle persistentState) {
8325 if (Trace.isTagEnabled(Trace.TRACE_TAG_WINDOW_MANAGER)) {
8326 Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "performCreate:"
8327 + mComponent.getClassName());
8328 }
8329 dispatchActivityPreCreated(icicle);
8330 mCanEnterPictureInPicture = true;
8331 // initialize mIsInMultiWindowMode and mIsInPictureInPictureMode before onCreate
8332 final int windowingMode = getResources().getConfiguration().windowConfiguration
8333 .getWindowingMode();
8334 mIsInMultiWindowMode = inMultiWindowMode(windowingMode);
8335 mIsInPictureInPictureMode = windowingMode == WINDOWING_MODE_PINNED;
8336 mShouldDockBigOverlays = getResources().getBoolean(R.bool.config_dockBigOverlayWindows);
8337 restoreHasCurrentPermissionRequest(icicle);
8338 if (persistentState != null) {
8339 onCreate(icicle, persistentState);
8340 } else {
8341 onCreate(icicle);
8342 }
8343 EventLogTags.writeWmOnCreateCalled(mIdent, getComponentName().getClassName(),
8344 "performCreate");
8345 mActivityTransitionState.readState(icicle);
8346
8347 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
8348 com.android.internal.R.styleable.Window_windowNoDisplay, false);
8349 mFragments.dispatchActivityCreated();
8350 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
8351 dispatchActivityPostCreated(icicle);
8352 Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
8353 }
8354
8355 final void performNewIntent(@NonNull Intent intent) {
8356 mCanEnterPictureInPicture = true;
8357 onNewIntent(intent);
8358 }
8359
8360 final void performStart(String reason) {
8361 dispatchActivityPreStarted();
8362 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
8363 mFragments.noteStateNotSaved();
8364 mCalled = false;
8365 mFragments.execPendingActions();
8366 mInstrumentation.callActivityOnStart(this);
8367 EventLogTags.writeWmOnStartCalled(mIdent, getComponentName().getClassName(), reason);
8368
8369 if (!mCalled) {
8370 throw new SuperNotCalledException(
8371 "Activity " + mComponent.toShortString() +
8372 " did not call through to super.onStart()");
8373 }
8374 mFragments.dispatchStart();
8375 mFragments.reportLoaderStart();
8376
8377 // Warn app developers if the dynamic linker logged anything during startup.
8378 boolean isAppDebuggable =
8379 (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8380 if (isAppDebuggable) {
8381 String dlwarning = getDlWarning();
8382 if (dlwarning != null) {
8383 String appName = getApplicationInfo().loadLabel(getPackageManager())
8384 .toString();
8385 String warning = "Detected problems with app native libraries\n" +
8386 "(please consult log for detail):\n" + dlwarning;
8387 if (isAppDebuggable) {
8388 new AlertDialog.Builder(this).
8389 setTitle(appName).
8390 setMessage(warning).
8391 setPositiveButton(android.R.string.ok, null).
8392 setCancelable(false).
8393 show();
8394 } else {
8395 Toast.makeText(this, appName + "\n" + warning, Toast.LENGTH_LONG).show();
8396 }
8397 }
8398 }
8399
8400 GraphicsEnvironment.getInstance().showAngleInUseDialogBox(this);
8401
8402 mActivityTransitionState.enterReady(this);
8403 dispatchActivityPostStarted();
8404 }
8405
8406 /**
8407 * Restart the activity.
8408 * @param start Indicates whether the activity should also be started after restart.
8409 * The option to not start immediately is needed in case a transaction with
8410 * multiple lifecycle transitions is in progress.
8411 */
8412 final void performRestart(boolean start, String reason) {
8413 mCanEnterPictureInPicture = true;
8414 mFragments.noteStateNotSaved();
8415
8416 if (mToken != null && mParent == null) {
8417 // No need to check mStopped, the roots will check if they were actually stopped.
8418 WindowManagerGlobal.getInstance().setStoppedState(mToken, false /* stopped */);
8419 }
8420
8421 if (mStopped) {
8422 mStopped = false;
8423
8424 synchronized (mManagedCursors) {
8425 final int N = mManagedCursors.size();
8426 for (int i=0; i<N; i++) {
8427 ManagedCursor mc = mManagedCursors.get(i);
8428 if (mc.mReleased || mc.mUpdated) {
8429 if (!mc.mCursor.requery()) {
8430 if (getApplicationInfo().targetSdkVersion
8431 >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
8432 throw new IllegalStateException(
8433 "trying to requery an already closed cursor "
8434 + mc.mCursor);
8435 }
8436 }
8437 mc.mReleased = false;
8438 mc.mUpdated = false;
8439 }
8440 }
8441 }
8442
8443 mCalled = false;
8444 mInstrumentation.callActivityOnRestart(this);
8445 EventLogTags.writeWmOnRestartCalled(mIdent, getComponentName().getClassName(), reason);
8446 if (!mCalled) {
8447 throw new SuperNotCalledException(
8448 "Activity " + mComponent.toShortString() +
8449 " did not call through to super.onRestart()");
8450 }
8451 if (start) {
8452 performStart(reason);
8453 }
8454 }
8455 }
8456
8457 final void performResume(boolean followedByPause, String reason) {
8458 if (Trace.isTagEnabled(Trace.TRACE_TAG_WINDOW_MANAGER)) {
8459 Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "performResume:"
8460 + mComponent.getClassName());
8461 }
8462 dispatchActivityPreResumed();
8463 performRestart(true /* start */, reason);
8464
8465 mFragments.execPendingActions();
8466
8467 mLastNonConfigurationInstances = null;
8468
8469 getAutofillClientController().onActivityPerformResume(followedByPause);
8470
8471 mCalled = false;
8472 // mResumed is set by the instrumentation
8473 mInstrumentation.callActivityOnResume(this);
8474 EventLogTags.writeWmOnResumeCalled(mIdent, getComponentName().getClassName(), reason);
8475 if (!mCalled) {
8476 throw new SuperNotCalledException(
8477 "Activity " + mComponent.toShortString() +
8478 " did not call through to super.onResume()");
8479 }
8480
8481 // invisible activities must be finished before onResume) completes
8482 if (!mVisibleFromClient && !mFinished) {
8483 Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
8484 if (getApplicationInfo().targetSdkVersion
8485 > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
8486 throw new IllegalStateException(
8487 "Activity " + mComponent.toShortString() +
8488 " did not call finish() prior to onResume() completing");
8489 }
8490 }
8491
8492 // Now really resume, and install the current status bar and menu.
8493 mCalled = false;
8494
8495 mFragments.dispatchResume();
8496 mFragments.execPendingActions();
8497
8498 onPostResume();
8499 if (!mCalled) {
8500 throw new SuperNotCalledException(
8501 "Activity " + mComponent.toShortString() +
8502 " did not call through to super.onPostResume()");
8503 }
8504 dispatchActivityPostResumed();
8505 Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
8506 }
8507
8508 final void performPause() {
8509 if (Trace.isTagEnabled(Trace.TRACE_TAG_WINDOW_MANAGER)) {
8510 Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "performPause:"
8511 + mComponent.getClassName());
8512 }
8513 dispatchActivityPrePaused();
8514 mDoReportFullyDrawn = false;
8515 mFragments.dispatchPause();
8516 mCalled = false;
8517 onPause();
8518 EventLogTags.writeWmOnPausedCalled(mIdent, getComponentName().getClassName(),
8519 "performPause");
8520 mResumed = false;
8521 if (!mCalled && getApplicationInfo().targetSdkVersion
8522 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
8523 throw new SuperNotCalledException(
8524 "Activity " + mComponent.toShortString() +
8525 " did not call through to super.onPause()");
8526 }
8527 dispatchActivityPostPaused();
8528 Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
8529 }
8530
8531 final void performUserLeaving() {
8532 onUserInteraction();
8533 onUserLeaveHint();
8534 }
8535
8536 final void performStop(boolean preserveWindow, String reason) {
8537 if (Trace.isTagEnabled(Trace.TRACE_TAG_WINDOW_MANAGER)) {
8538 Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "performStop:"
8539 + mComponent.getClassName());
8540 }
8541 mDoReportFullyDrawn = false;
8542 mFragments.doLoaderStop(mChangingConfigurations /*retain*/);
8543
8544 // Disallow entering picture-in-picture after the activity has been stopped
8545 mCanEnterPictureInPicture = false;
8546
8547 if (!mStopped) {
8548 dispatchActivityPreStopped();
8549 if (mWindow != null) {
8550 mWindow.closeAllPanels();
8551 }
8552
8553 // If we're preserving the window, don't setStoppedState to true, since we
8554 // need the window started immediately again. Stopping the window will
8555 // destroys hardware resources and causes flicker.
8556 if (!preserveWindow && mToken != null && mParent == null) {
8557 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
8558 }
8559
8560 mFragments.dispatchStop();
8561
8562 mCalled = false;
8563 mInstrumentation.callActivityOnStop(this);
8564 EventLogTags.writeWmOnStopCalled(mIdent, getComponentName().getClassName(), reason);
8565 if (!mCalled) {
8566 throw new SuperNotCalledException(
8567 "Activity " + mComponent.toShortString() +
8568 " did not call through to super.onStop()");
8569 }
8570
8571 synchronized (mManagedCursors) {
8572 final int N = mManagedCursors.size();
8573 for (int i=0; i<N; i++) {
8574 ManagedCursor mc = mManagedCursors.get(i);
8575 if (!mc.mReleased) {
8576 mc.mCursor.deactivate();
8577 mc.mReleased = true;
8578 }
8579 }
8580 }
8581
8582 mStopped = true;
8583 dispatchActivityPostStopped();
8584 }
8585 mResumed = false;
8586 Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
8587 }
8588
8589 final void performDestroy() {
8590 if (Trace.isTagEnabled(Trace.TRACE_TAG_WINDOW_MANAGER)) {
8591 Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "performDestroy:"
8592 + mComponent.getClassName());
8593 }
8594 dispatchActivityPreDestroyed();
8595 mDestroyed = true;
8596 mWindow.destroy();
8597 mFragments.dispatchDestroy();
8598 onDestroy();
8599 EventLogTags.writeWmOnDestroyCalled(mIdent, getComponentName().getClassName(),
8600 "performDestroy");
8601 mFragments.doLoaderDestroy();
8602 if (mVoiceInteractor != null) {
8603 mVoiceInteractor.detachActivity();
8604 }
8605 dispatchActivityPostDestroyed();
8606 Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
8607 }
8608
8609 final void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode,
8610 Configuration newConfig) {
8611 if (DEBUG_LIFECYCLE) Slog.v(TAG,
8612 "dispatchMultiWindowModeChanged " + this + ": " + isInMultiWindowMode
8613 + " " + newConfig);
8614 mFragments.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
8615 if (mWindow != null) {
8616 mWindow.onMultiWindowModeChanged();
8617 }
8618 mIsInMultiWindowMode = isInMultiWindowMode;
8619 onMultiWindowModeChanged(isInMultiWindowMode, newConfig);
8620 }
8621
8622 final void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode,
8623 Configuration newConfig) {
8624 if (DEBUG_LIFECYCLE) Slog.v(TAG,
8625 "dispatchPictureInPictureModeChanged " + this + ": " + isInPictureInPictureMode
8626 + " " + newConfig);
8627 mFragments.dispatchPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
8628 if (mWindow != null) {
8629 mWindow.onPictureInPictureModeChanged(isInPictureInPictureMode);
8630 }
8631 mIsInPictureInPictureMode = isInPictureInPictureMode;
8632 onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
8633 }
8634
8635 /**
8636 * @hide
8637 */
8638 @UnsupportedAppUsage
8639 public final boolean isResumed() {
8640 return mResumed;
8641 }
8642
8643 private void storeHasCurrentPermissionRequest(Bundle bundle) {
8644 if (bundle != null && mHasCurrentPermissionsRequest) {
8645 bundle.putBoolean(HAS_CURENT_PERMISSIONS_REQUEST_KEY, true);
8646 }
8647 }
8648
8649 private void restoreHasCurrentPermissionRequest(Bundle bundle) {
8650 if (bundle != null) {
8651 mHasCurrentPermissionsRequest = bundle.getBoolean(
8652 HAS_CURENT_PERMISSIONS_REQUEST_KEY, false);
8653 }
8654 }
8655
8656 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
8657 void dispatchActivityResult(String who, int requestCode, int resultCode, Intent data,
8658 String reason) {
8659 if (false) Log.v(
8660 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
8661 + ", resCode=" + resultCode + ", data=" + data);
8662 mFragments.noteStateNotSaved();
8663 if (who == null) {
8664 onActivityResult(requestCode, resultCode, data);
8665 } else if (who.startsWith(REQUEST_PERMISSIONS_WHO_PREFIX)) {
8666 who = who.substring(REQUEST_PERMISSIONS_WHO_PREFIX.length());
8667 if (TextUtils.isEmpty(who)) {
8668 dispatchRequestPermissionsResult(requestCode, data);
8669 } else {
8670 Fragment frag = mFragments.findFragmentByWho(who);
8671 if (frag != null) {
8672 dispatchRequestPermissionsResultToFragment(requestCode, data, frag);
8673 }
8674 }
8675 } else if (who.startsWith("@android:view:")) {
8676 ArrayList<ViewRootImpl> views = WindowManagerGlobal.getInstance().getRootViews(
8677 getActivityToken());
8678 for (ViewRootImpl viewRoot : views) {
8679 if (viewRoot.getView() != null
8680 && viewRoot.getView().dispatchActivityResult(
8681 who, requestCode, resultCode, data)) {
8682 return;
8683 }
8684 }
8685 } else if (who.startsWith(AutofillClientController.AUTO_FILL_AUTH_WHO_PREFIX)) {
8686 getAutofillClientController().onDispatchActivityResult(requestCode, resultCode, data);
8687 } else {
8688 Fragment frag = mFragments.findFragmentByWho(who);
8689 if (frag != null) {
8690 frag.onActivityResult(requestCode, resultCode, data);
8691 }
8692 }
8693
8694 EventLogTags.writeWmOnActivityResultCalled(mIdent, getComponentName().getClassName(),
8695 reason);
8696 }
8697
8698 /**
8699 * Request to put this activity in a mode where the user is locked to a restricted set of
8700 * applications.
8701 *
8702 * <p>If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns {@code true}
8703 * for this component, the current task will be launched directly into LockTask mode. Only apps
8704 * allowlisted by {@link DevicePolicyManager#setLockTaskPackages(ComponentName, String[])} can
8705 * be launched while LockTask mode is active. The user will not be able to leave this mode
8706 * until this activity calls {@link #stopLockTask()}. Calling this method while the device is
8707 * already in LockTask mode has no effect.
8708 *
8709 * <p>Otherwise, the current task will be launched into screen pinning mode. In this case, the
8710 * system will prompt the user with a dialog requesting permission to use this mode.
8711 * The user can exit at any time through instructions shown on the request dialog. Calling
8712 * {@link #stopLockTask()} will also terminate this mode.
8713 *
8714 * <p><strong>Note:</strong> this method can only be called when the activity is foreground.
8715 * That is, between {@link #onResume()} and {@link #onPause()}.
8716 *
8717 * @see #stopLockTask()
8718 * @see android.R.attr#lockTaskMode
8719 */
8720 public void startLockTask() {
8721 ActivityClient.getInstance().startLockTaskModeByToken(mToken);
8722 }
8723
8724 /**
8725 * Stop the current task from being locked.
8726 *
8727 * <p>Called to end the LockTask or screen pinning mode started by {@link #startLockTask()}.
8728 * This can only be called by activities that have called {@link #startLockTask()} previously.
8729 *
8730 * <p><strong>Note:</strong> If the device is in LockTask mode that is not initially started
8731 * by this activity, then calling this method will not terminate the LockTask mode, but only
8732 * finish its own task. The device will remain in LockTask mode, until the activity which
8733 * started the LockTask mode calls this method, or until its allowlist authorization is revoked
8734 * by {@link DevicePolicyManager#setLockTaskPackages(ComponentName, String[])}.
8735 *
8736 * @see #startLockTask()
8737 * @see android.R.attr#lockTaskMode
8738 * @see ActivityManager#getLockTaskModeState()
8739 */
8740 public void stopLockTask() {
8741 ActivityClient.getInstance().stopLockTaskModeByToken(mToken);
8742 }
8743
8744 /**
8745 * Shows the user the system defined message for telling the user how to exit
8746 * lock task mode. The task containing this activity must be in lock task mode at the time
8747 * of this call for the message to be displayed.
8748 */
8749 public void showLockTaskEscapeMessage() {
8750 ActivityClient.getInstance().showLockTaskEscapeMessage(mToken);
8751 }
8752
8753 /**
8754 * Check whether the caption on freeform windows is displayed directly on the content.
8755 *
8756 * @return True if caption is displayed on content, false if it pushes the content down.
8757 *
8758 * @see #setOverlayWithDecorCaptionEnabled(boolean)
8759 * @hide
8760 */
8761 public boolean isOverlayWithDecorCaptionEnabled() {
8762 return mWindow.isOverlayWithDecorCaptionEnabled();
8763 }
8764
8765 /**
8766 * Set whether the caption should displayed directly on the content rather than push it down.
8767 *
8768 * This affects only freeform windows since they display the caption and only the main
8769 * window of the activity. The caption is used to drag the window around and also shows
8770 * maximize and close action buttons.
8771 * @hide
8772 */
8773 public void setOverlayWithDecorCaptionEnabled(boolean enabled) {
8774 mWindow.setOverlayWithDecorCaptionEnabled(enabled);
8775 }
8776
8777 /**
8778 * Interface for informing a translucent {@link Activity} once all visible activities below it
8779 * have completed drawing. This is necessary only after an {@link Activity} has been made
8780 * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
8781 * translucent again following a call to {@link
8782 * Activity#convertToTranslucent(android.app.Activity.TranslucentConversionListener,
8783 * ActivityOptions)}
8784 *
8785 * @hide
8786 */
8787 @SystemApi
8788 public interface TranslucentConversionListener {
8789 /**
8790 * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
8791 * below the top one have been redrawn. Following this callback it is safe to make the top
8792 * Activity translucent because the underlying Activity has been drawn.
8793 *
8794 * @param drawComplete True if the background Activity has drawn itself. False if a timeout
8795 * occurred waiting for the Activity to complete drawing.
8796 *
8797 * @see Activity#convertFromTranslucent()
8798 * @see Activity#convertToTranslucent(TranslucentConversionListener, ActivityOptions)
8799 */
8800 public void onTranslucentConversionComplete(boolean drawComplete);
8801 }
8802
8803 private void dispatchRequestPermissionsResult(int requestCode, Intent data) {
8804 mHasCurrentPermissionsRequest = false;
8805 // If the package installer crashed we may have not data - best effort.
8806 String[] permissions = (data != null) ? data.getStringArrayExtra(
8807 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
8808 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
8809 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
8810 onRequestPermissionsResult(requestCode, permissions, grantResults);
8811 }
8812
8813 private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data,
8814 Fragment fragment) {
8815 // If the package installer crashed we may have not data - best effort.
8816 String[] permissions = (data != null) ? data.getStringArrayExtra(
8817 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
8818 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
8819 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
8820 fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
8821 }
8822
8823 /**
8824 * @hide
8825 */
8826 public final boolean isVisibleForAutofill() {
8827 return !mStopped;
8828 }
8829
8830 /**
8831 * @hide
8832 */
8833 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.S,
8834 publicAlternatives = "Use {@link #setRecentsScreenshotEnabled(boolean)} instead.")
8835 public void setDisablePreviewScreenshots(boolean disable) {
8836 setRecentsScreenshotEnabled(!disable);
8837 }
8838
8839 /**
8840 * If set to false, this indicates to the system that it should never take a
8841 * screenshot of the activity to be used as a representation in recents screen. By default, this
8842 * value is {@code true}.
8843 * <p>
8844 * Note that the system may use the window background of the theme instead to represent
8845 * the window when it is not running.
8846 * <p>
8847 * Also note that in comparison to {@link android.view.WindowManager.LayoutParams#FLAG_SECURE},
8848 * this only affects the behavior when the activity's screenshot would be used as a
8849 * representation when the activity is not in a started state, i.e. in Overview. The system may
8850 * still take screenshots of the activity in other contexts; for example, when the user takes a
8851 * screenshot of the entire screen, or when the active
8852 * {@link android.service.voice.VoiceInteractionService} requests a screenshot via
8853 * {@link android.service.voice.VoiceInteractionSession#SHOW_WITH_SCREENSHOT}.
8854 *
8855 * @param enabled {@code true} to enable recents screenshots; {@code false} otherwise.
8856 */
8857 public void setRecentsScreenshotEnabled(boolean enabled) {
8858 ActivityClient.getInstance().setRecentsScreenshotEnabled(mToken, enabled);
8859 }
8860
8861 /**
8862 * Specifies whether an {@link Activity} should be shown on top of the lock screen whenever
8863 * the lockscreen is up and the activity is resumed. Normally an activity will be transitioned
8864 * to the stopped state if it is started while the lockscreen is up, but with this flag set the
8865 * activity will remain in the resumed state visible on-top of the lock screen. This value can
8866 * be set as a manifest attribute using {@link android.R.attr#showWhenLocked}.
8867 *
8868 * @param showWhenLocked {@code true} to show the {@link Activity} on top of the lock screen;
8869 * {@code false} otherwise.
8870 * @see #setTurnScreenOn(boolean)
8871 * @see android.R.attr#turnScreenOn
8872 * @see android.R.attr#showWhenLocked
8873 */
8874 public void setShowWhenLocked(boolean showWhenLocked) {
8875 ActivityClient.getInstance().setShowWhenLocked(mToken, showWhenLocked);
8876 }
8877
8878 /**
8879 * Specifies whether this {@link Activity} should be shown on top of the lock screen whenever
8880 * the lockscreen is up and this activity has another activity behind it with the showWhenLock
8881 * attribute set. That is, this activity is only visible on the lock screen if there is another
8882 * activity with the showWhenLock attribute visible at the same time on the lock screen. A use
8883 * case for this is permission dialogs, that should only be visible on the lock screen if their
8884 * requesting activity is also visible. This value can be set as a manifest attribute using
8885 * android.R.attr#inheritShowWhenLocked.
8886 *
8887 * @param inheritShowWhenLocked {@code true} to show the {@link Activity} on top of the lock
8888 * screen when this activity has another activity behind it with
8889 * the showWhenLock attribute set; {@code false} otherwise.
8890 * @see #setShowWhenLocked(boolean)
8891 * @see android.R.attr#inheritShowWhenLocked
8892 */
8893 public void setInheritShowWhenLocked(boolean inheritShowWhenLocked) {
8894 ActivityClient.getInstance().setInheritShowWhenLocked(mToken, inheritShowWhenLocked);
8895 }
8896
8897 /**
8898 * Specifies whether the screen should be turned on when the {@link Activity} is resumed.
8899 * Normally an activity will be transitioned to the stopped state if it is started while the
8900 * screen if off, but with this flag set the activity will cause the screen to turn on if the
8901 * activity will be visible and resumed due to the screen coming on. The screen will not be
8902 * turned on if the activity won't be visible after the screen is turned on. This flag is
8903 * normally used in conjunction with the {@link android.R.attr#showWhenLocked} flag to make sure
8904 * the activity is visible after the screen is turned on when the lockscreen is up. In addition,
8905 * if this flag is set and the activity calls {@link
8906 * KeyguardManager#requestDismissKeyguard(Activity, KeyguardManager.KeyguardDismissCallback)}
8907 * the screen will turn on.
8908 *
8909 * @param turnScreenOn {@code true} to turn on the screen; {@code false} otherwise.
8910 *
8911 * @see #setShowWhenLocked(boolean)
8912 * @see android.R.attr#turnScreenOn
8913 * @see android.R.attr#showWhenLocked
8914 * @see KeyguardManager#isDeviceSecure()
8915 */
8916 public void setTurnScreenOn(boolean turnScreenOn) {
8917 ActivityClient.getInstance().setTurnScreenOn(mToken, turnScreenOn);
8918 }
8919
8920 /**
8921 * Registers remote animations per transition type for this activity.
8922 *
8923 * @param definition The remote animation definition that defines which transition whould run
8924 * which remote animation.
8925 * @hide
8926 */
8927 @RequiresPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS)
8928 public void registerRemoteAnimations(RemoteAnimationDefinition definition) {
8929 ActivityClient.getInstance().registerRemoteAnimations(mToken, definition);
8930 }
8931
8932 /**
8933 * Unregisters all remote animations for this activity.
8934 *
8935 * @hide
8936 */
8937 @RequiresPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS)
8938 public void unregisterRemoteAnimations() {
8939 ActivityClient.getInstance().unregisterRemoteAnimations(mToken);
8940 }
8941
8942 /**
8943 * Notify {@link UiTranslationController} the ui translation state is changed.
8944 * @hide
8945 */
8946 public void updateUiTranslationState(int state, TranslationSpec sourceSpec,
8947 TranslationSpec targetSpec, List<AutofillId> viewIds,
8948 UiTranslationSpec uiTranslationSpec) {
8949 if (mUiTranslationController == null) {
8950 mUiTranslationController = new UiTranslationController(this, getApplicationContext());
8951 }
8952 mUiTranslationController.updateUiTranslationState(
8953 state, sourceSpec, targetSpec, viewIds, uiTranslationSpec);
8954 }
8955
8956 class HostCallbacks extends FragmentHostCallback<Activity> {
8957 public HostCallbacks() {
8958 super(Activity.this /*activity*/);
8959 }
8960
8961 @Override
8962 public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
8963 Activity.this.dump(prefix, fd, writer, args);
8964 }
8965
8966 @Override
8967 public boolean onShouldSaveFragmentState(Fragment fragment) {
8968 return !isFinishing();
8969 }
8970
8971 @Override
8972 public LayoutInflater onGetLayoutInflater() {
8973 final LayoutInflater result = Activity.this.getLayoutInflater();
8974 if (onUseFragmentManagerInflaterFactory()) {
8975 return result.cloneInContext(Activity.this);
8976 }
8977 return result;
8978 }
8979
8980 @Override
8981 public boolean onUseFragmentManagerInflaterFactory() {
8982 // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
8983 return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
8984 }
8985
8986 @Override
8987 public Activity onGetHost() {
8988 return Activity.this;
8989 }
8990
8991 @Override
8992 public void onInvalidateOptionsMenu() {
8993 Activity.this.invalidateOptionsMenu();
8994 }
8995
8996 @Override
8997 public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
8998 Bundle options) {
8999 Activity.this.startActivityFromFragment(fragment, intent, requestCode, options);
9000 }
9001
9002 @Override
9003 public void onStartActivityAsUserFromFragment(
9004 Fragment fragment, Intent intent, int requestCode, Bundle options,
9005 UserHandle user) {
9006 Activity.this.startActivityAsUserFromFragment(
9007 fragment, intent, requestCode, options, user);
9008 }
9009
9010 @Override
9011 public void onStartIntentSenderFromFragment(Fragment fragment, IntentSender intent,
9012 int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues,
9013 int extraFlags, Bundle options) throws IntentSender.SendIntentException {
9014 if (mParent == null) {
9015 startIntentSenderForResultInner(intent, fragment.mWho, requestCode, fillInIntent,
9016 flagsMask, flagsValues, options);
9017 } else if (options != null) {
9018 mParent.startIntentSenderFromFragment(fragment, intent, requestCode,
9019 fillInIntent, flagsMask, flagsValues, options);
9020 }
9021 }
9022
9023 @Override
9024 public void onRequestPermissionsFromFragment(Fragment fragment, String[] permissions,
9025 int requestCode) {
9026 String who = REQUEST_PERMISSIONS_WHO_PREFIX + fragment.mWho;
9027 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
9028 startActivityForResult(who, intent, requestCode, null);
9029 }
9030
9031 @Override
9032 public boolean onHasWindowAnimations() {
9033 return getWindow() != null;
9034 }
9035
9036 @Override
9037 public int onGetWindowAnimations() {
9038 final Window w = getWindow();
9039 return (w == null) ? 0 : w.getAttributes().windowAnimations;
9040 }
9041
9042 @Override
9043 public void onAttachFragment(Fragment fragment) {
9044 Activity.this.onAttachFragment(fragment);
9045 }
9046
9047 @Nullable
9048 @Override
9049 public <T extends View> T onFindViewById(int id) {
9050 return Activity.this.findViewById(id);
9051 }
9052
9053 @Override
9054 public boolean onHasView() {
9055 final Window w = getWindow();
9056 return (w != null && w.peekDecorView() != null);
9057 }
9058 }
9059
9060 /**
9061 * Returns the {@link OnBackInvokedDispatcher} instance associated with the window that this
9062 * activity is attached to.
9063 *
9064 * @throws IllegalStateException if this Activity is not visual.
9065 */
9066 @NonNull
9067 public OnBackInvokedDispatcher getOnBackInvokedDispatcher() {
9068 if (mWindow == null) {
9069 throw new IllegalStateException("OnBackInvokedDispatcher are not available on "
9070 + "non-visual activities");
9071 }
9072 return mWindow.getOnBackInvokedDispatcher();
9073 }
9074 }