/services/java/com/android/server/am/ActivityRecord.java

https://github.com/aizuzi/platform_frameworks_base · Java · 1066 lines · 929 code · 80 blank · 57 comment · 285 complexity · d74914d4a010ee4698e87614d94fd11d MD5 · raw file

  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. package com.android.server.am;
  17. import android.os.Trace;
  18. import com.android.internal.R.styleable;
  19. import com.android.internal.app.ResolverActivity;
  20. import com.android.server.AttributeCache;
  21. import com.android.server.am.ActivityStack.ActivityState;
  22. import android.app.ActivityOptions;
  23. import android.app.ResultInfo;
  24. import android.content.ComponentName;
  25. import android.content.Intent;
  26. import android.content.pm.ActivityInfo;
  27. import android.content.pm.ApplicationInfo;
  28. import android.content.res.CompatibilityInfo;
  29. import android.content.res.Configuration;
  30. import android.graphics.Bitmap;
  31. import android.graphics.Rect;
  32. import android.os.Build;
  33. import android.os.Bundle;
  34. import android.os.IBinder;
  35. import android.os.Message;
  36. import android.os.Process;
  37. import android.os.RemoteException;
  38. import android.os.SystemClock;
  39. import android.os.UserHandle;
  40. import android.util.EventLog;
  41. import android.util.Log;
  42. import android.util.Slog;
  43. import android.util.TimeUtils;
  44. import android.view.IApplicationToken;
  45. import android.view.WindowManager;
  46. import java.io.PrintWriter;
  47. import java.lang.ref.WeakReference;
  48. import java.util.ArrayList;
  49. import java.util.HashSet;
  50. /**
  51. * An entry in the history stack, representing an activity.
  52. */
  53. final class ActivityRecord {
  54. static final String TAG = ActivityManagerService.TAG;
  55. static final boolean DEBUG_SAVED_STATE = ActivityStackSupervisor.DEBUG_SAVED_STATE;
  56. final public static String RECENTS_PACKAGE_NAME = "com.android.systemui.recent";
  57. final ActivityManagerService service; // owner
  58. final IApplicationToken.Stub appToken; // window manager token
  59. final ActivityInfo info; // all about me
  60. final int launchedFromUid; // always the uid who started the activity.
  61. final String launchedFromPackage; // always the package who started the activity.
  62. final int userId; // Which user is this running for?
  63. final Intent intent; // the original intent that generated us
  64. final ComponentName realActivity; // the intent component, or target of an alias.
  65. final String shortComponentName; // the short component name of the intent
  66. final String resolvedType; // as per original caller;
  67. final String packageName; // the package implementing intent's component
  68. final String processName; // process where this component wants to run
  69. final String taskAffinity; // as per ActivityInfo.taskAffinity
  70. final boolean stateNotNeeded; // As per ActivityInfo.flags
  71. boolean fullscreen; // covers the full screen?
  72. final boolean noDisplay; // activity is not displayed?
  73. final boolean componentSpecified; // did caller specifiy an explicit component?
  74. static final int APPLICATION_ACTIVITY_TYPE = 0;
  75. static final int HOME_ACTIVITY_TYPE = 1;
  76. static final int RECENTS_ACTIVITY_TYPE = 2;
  77. int mActivityType;
  78. final String baseDir; // where activity source (resources etc) located
  79. final String resDir; // where public activity source (public resources etc) located
  80. final String dataDir; // where activity data should go
  81. CharSequence nonLocalizedLabel; // the label information from the package mgr.
  82. int labelRes; // the label information from the package mgr.
  83. int icon; // resource identifier of activity's icon.
  84. int logo; // resource identifier of activity's logo.
  85. int theme; // resource identifier of activity's theme.
  86. int realTheme; // actual theme resource we will use, never 0.
  87. int windowFlags; // custom window flags for preview window.
  88. TaskRecord task; // the task this is in.
  89. ThumbnailHolder thumbHolder; // where our thumbnails should go.
  90. long displayStartTime; // when we started launching this activity
  91. long fullyDrawnStartTime; // when we started launching this activity
  92. long startTime; // last time this activity was started
  93. long lastVisibleTime; // last time this activity became visible
  94. long cpuTimeAtResume; // the cpu time of host process at the time of resuming activity
  95. long pauseTime; // last time we started pausing the activity
  96. long launchTickTime; // base time for launch tick messages
  97. Configuration configuration; // configuration activity was last running in
  98. CompatibilityInfo compat;// last used compatibility mode
  99. ActivityRecord resultTo; // who started this entry, so will get our reply
  100. final String resultWho; // additional identifier for use by resultTo.
  101. final int requestCode; // code given by requester (resultTo)
  102. ArrayList<ResultInfo> results; // pending ActivityResult objs we have received
  103. HashSet<WeakReference<PendingIntentRecord>> pendingResults; // all pending intents for this act
  104. ArrayList<Intent> newIntents; // any pending new intents for single-top mode
  105. ActivityOptions pendingOptions; // most recently given options
  106. HashSet<ConnectionRecord> connections; // All ConnectionRecord we hold
  107. UriPermissionOwner uriPermissions; // current special URI access perms.
  108. ProcessRecord app; // if non-null, hosting application
  109. ActivityState state; // current state we are in
  110. Bundle icicle; // last saved activity state
  111. boolean frontOfTask; // is this the root activity of its task?
  112. boolean launchFailed; // set if a launched failed, to abort on 2nd try
  113. boolean haveState; // have we gotten the last activity state?
  114. boolean stopped; // is activity pause finished?
  115. boolean delayedResume; // not yet resumed because of stopped app switches?
  116. boolean finishing; // activity in pending finish list?
  117. boolean configDestroy; // need to destroy due to config change?
  118. int configChangeFlags; // which config values have changed
  119. boolean keysPaused; // has key dispatching been paused for it?
  120. int launchMode; // the launch mode activity attribute.
  121. boolean visible; // does this activity's window need to be shown?
  122. boolean sleeping; // have we told the activity to sleep?
  123. boolean waitingVisible; // true if waiting for a new act to become vis
  124. boolean nowVisible; // is this activity's window visible?
  125. boolean thumbnailNeeded;// has someone requested a thumbnail?
  126. boolean idle; // has the activity gone idle?
  127. boolean hasBeenLaunched;// has this activity ever been launched?
  128. boolean frozenBeforeDestroy;// has been frozen but not yet destroyed.
  129. boolean immersive; // immersive mode (don't interrupt if possible)
  130. boolean forceNewConfig; // force re-create with new config next time
  131. int launchCount; // count of launches since last state
  132. long lastLaunchTime; // time of last lauch of this activity
  133. String stringName; // for caching of toString().
  134. private boolean inHistory; // are we in the history stack?
  135. final ActivityStackSupervisor mStackSupervisor;
  136. void dump(PrintWriter pw, String prefix) {
  137. final long now = SystemClock.uptimeMillis();
  138. pw.print(prefix); pw.print("packageName="); pw.print(packageName);
  139. pw.print(" processName="); pw.println(processName);
  140. pw.print(prefix); pw.print("launchedFromUid="); pw.print(launchedFromUid);
  141. pw.print(" launchedFromPackage="); pw.print(launchedFromPackage);
  142. pw.print(" userId="); pw.println(userId);
  143. pw.print(prefix); pw.print("app="); pw.println(app);
  144. pw.print(prefix); pw.println(intent.toInsecureStringWithClip());
  145. pw.print(prefix); pw.print("frontOfTask="); pw.print(frontOfTask);
  146. pw.print(" task="); pw.println(task);
  147. pw.print(prefix); pw.print("taskAffinity="); pw.println(taskAffinity);
  148. pw.print(prefix); pw.print("realActivity=");
  149. pw.println(realActivity.flattenToShortString());
  150. pw.print(prefix); pw.print("baseDir="); pw.println(baseDir);
  151. if (!resDir.equals(baseDir)) {
  152. pw.print(prefix); pw.print("resDir="); pw.println(resDir);
  153. }
  154. pw.print(prefix); pw.print("dataDir="); pw.println(dataDir);
  155. pw.print(prefix); pw.print("stateNotNeeded="); pw.print(stateNotNeeded);
  156. pw.print(" componentSpecified="); pw.print(componentSpecified);
  157. pw.print(" mActivityType="); pw.println(mActivityType);
  158. pw.print(prefix); pw.print("compat="); pw.print(compat);
  159. pw.print(" labelRes=0x"); pw.print(Integer.toHexString(labelRes));
  160. pw.print(" icon=0x"); pw.print(Integer.toHexString(icon));
  161. pw.print(" theme=0x"); pw.println(Integer.toHexString(theme));
  162. pw.print(prefix); pw.print("config="); pw.println(configuration);
  163. if (resultTo != null || resultWho != null) {
  164. pw.print(prefix); pw.print("resultTo="); pw.print(resultTo);
  165. pw.print(" resultWho="); pw.print(resultWho);
  166. pw.print(" resultCode="); pw.println(requestCode);
  167. }
  168. if (results != null) {
  169. pw.print(prefix); pw.print("results="); pw.println(results);
  170. }
  171. if (pendingResults != null && pendingResults.size() > 0) {
  172. pw.print(prefix); pw.println("Pending Results:");
  173. for (WeakReference<PendingIntentRecord> wpir : pendingResults) {
  174. PendingIntentRecord pir = wpir != null ? wpir.get() : null;
  175. pw.print(prefix); pw.print(" - ");
  176. if (pir == null) {
  177. pw.println("null");
  178. } else {
  179. pw.println(pir);
  180. pir.dump(pw, prefix + " ");
  181. }
  182. }
  183. }
  184. if (newIntents != null && newIntents.size() > 0) {
  185. pw.print(prefix); pw.println("Pending New Intents:");
  186. for (int i=0; i<newIntents.size(); i++) {
  187. Intent intent = newIntents.get(i);
  188. pw.print(prefix); pw.print(" - ");
  189. if (intent == null) {
  190. pw.println("null");
  191. } else {
  192. pw.println(intent.toShortString(false, true, false, true));
  193. }
  194. }
  195. }
  196. if (pendingOptions != null) {
  197. pw.print(prefix); pw.print("pendingOptions="); pw.println(pendingOptions);
  198. }
  199. if (uriPermissions != null) {
  200. if (uriPermissions.readUriPermissions != null) {
  201. pw.print(prefix); pw.print("readUriPermissions=");
  202. pw.println(uriPermissions.readUriPermissions);
  203. }
  204. if (uriPermissions.writeUriPermissions != null) {
  205. pw.print(prefix); pw.print("writeUriPermissions=");
  206. pw.println(uriPermissions.writeUriPermissions);
  207. }
  208. }
  209. pw.print(prefix); pw.print("launchFailed="); pw.print(launchFailed);
  210. pw.print(" launchCount="); pw.print(launchCount);
  211. pw.print(" lastLaunchTime=");
  212. if (lastLaunchTime == 0) pw.print("0");
  213. else TimeUtils.formatDuration(lastLaunchTime, now, pw);
  214. pw.println();
  215. pw.print(prefix); pw.print("haveState="); pw.print(haveState);
  216. pw.print(" icicle="); pw.println(icicle);
  217. pw.print(prefix); pw.print("state="); pw.print(state);
  218. pw.print(" stopped="); pw.print(stopped);
  219. pw.print(" delayedResume="); pw.print(delayedResume);
  220. pw.print(" finishing="); pw.println(finishing);
  221. pw.print(prefix); pw.print("keysPaused="); pw.print(keysPaused);
  222. pw.print(" inHistory="); pw.print(inHistory);
  223. pw.print(" visible="); pw.print(visible);
  224. pw.print(" sleeping="); pw.print(sleeping);
  225. pw.print(" idle="); pw.println(idle);
  226. pw.print(prefix); pw.print("fullscreen="); pw.print(fullscreen);
  227. pw.print(" noDisplay="); pw.print(noDisplay);
  228. pw.print(" immersive="); pw.print(immersive);
  229. pw.print(" launchMode="); pw.println(launchMode);
  230. pw.print(prefix); pw.print("frozenBeforeDestroy="); pw.print(frozenBeforeDestroy);
  231. pw.print(" thumbnailNeeded="); pw.print(thumbnailNeeded);
  232. pw.print(" forceNewConfig="); pw.println(forceNewConfig);
  233. pw.print(prefix); pw.print("mActivityType=");
  234. pw.println(activityTypeToString(mActivityType));
  235. pw.print(prefix); pw.print("thumbHolder: ");
  236. pw.print(Integer.toHexString(System.identityHashCode(thumbHolder)));
  237. if (thumbHolder != null) {
  238. pw.print(" bm="); pw.print(thumbHolder.lastThumbnail);
  239. pw.print(" desc="); pw.print(thumbHolder.lastDescription);
  240. }
  241. pw.println();
  242. if (displayStartTime != 0 || startTime != 0) {
  243. pw.print(prefix); pw.print("displayStartTime=");
  244. if (displayStartTime == 0) pw.print("0");
  245. else TimeUtils.formatDuration(displayStartTime, now, pw);
  246. pw.print(" startTime=");
  247. if (startTime == 0) pw.print("0");
  248. else TimeUtils.formatDuration(startTime, now, pw);
  249. pw.println();
  250. }
  251. if (lastVisibleTime != 0 || waitingVisible || nowVisible) {
  252. pw.print(prefix); pw.print("waitingVisible="); pw.print(waitingVisible);
  253. pw.print(" nowVisible="); pw.print(nowVisible);
  254. pw.print(" lastVisibleTime=");
  255. if (lastVisibleTime == 0) pw.print("0");
  256. else TimeUtils.formatDuration(lastVisibleTime, now, pw);
  257. pw.println();
  258. }
  259. if (configDestroy || configChangeFlags != 0) {
  260. pw.print(prefix); pw.print("configDestroy="); pw.print(configDestroy);
  261. pw.print(" configChangeFlags=");
  262. pw.println(Integer.toHexString(configChangeFlags));
  263. }
  264. if (connections != null) {
  265. pw.print(prefix); pw.print("connections="); pw.println(connections);
  266. }
  267. }
  268. static class Token extends IApplicationToken.Stub {
  269. final WeakReference<ActivityRecord> weakActivity;
  270. Token(ActivityRecord activity) {
  271. weakActivity = new WeakReference<ActivityRecord>(activity);
  272. }
  273. @Override public void windowsDrawn() {
  274. ActivityRecord activity = weakActivity.get();
  275. if (activity != null) {
  276. activity.windowsDrawn();
  277. }
  278. }
  279. @Override public void windowsVisible() {
  280. ActivityRecord activity = weakActivity.get();
  281. if (activity != null) {
  282. activity.windowsVisible();
  283. }
  284. }
  285. @Override public void windowsGone() {
  286. ActivityRecord activity = weakActivity.get();
  287. if (activity != null) {
  288. activity.windowsGone();
  289. }
  290. }
  291. @Override public boolean keyDispatchingTimedOut(String reason) {
  292. ActivityRecord activity = weakActivity.get();
  293. return activity != null && activity.keyDispatchingTimedOut(reason);
  294. }
  295. @Override public long getKeyDispatchingTimeout() {
  296. ActivityRecord activity = weakActivity.get();
  297. if (activity != null) {
  298. return activity.getKeyDispatchingTimeout();
  299. }
  300. return 0;
  301. }
  302. @Override
  303. public String toString() {
  304. StringBuilder sb = new StringBuilder(128);
  305. sb.append("Token{");
  306. sb.append(Integer.toHexString(System.identityHashCode(this)));
  307. sb.append(' ');
  308. sb.append(weakActivity.get());
  309. sb.append('}');
  310. return sb.toString();
  311. }
  312. }
  313. static ActivityRecord forToken(IBinder token) {
  314. try {
  315. return token != null ? ((Token)token).weakActivity.get() : null;
  316. } catch (ClassCastException e) {
  317. Slog.w(ActivityManagerService.TAG, "Bad activity token: " + token, e);
  318. return null;
  319. }
  320. }
  321. boolean isNotResolverActivity() {
  322. return !ResolverActivity.class.getName().equals(realActivity.getClassName());
  323. }
  324. ActivityRecord(ActivityManagerService _service, ProcessRecord _caller,
  325. int _launchedFromUid, String _launchedFromPackage, Intent _intent, String _resolvedType,
  326. ActivityInfo aInfo, Configuration _configuration,
  327. ActivityRecord _resultTo, String _resultWho, int _reqCode,
  328. boolean _componentSpecified, ActivityStackSupervisor supervisor) {
  329. service = _service;
  330. appToken = new Token(this);
  331. info = aInfo;
  332. launchedFromUid = _launchedFromUid;
  333. launchedFromPackage = _launchedFromPackage;
  334. userId = UserHandle.getUserId(aInfo.applicationInfo.uid);
  335. intent = _intent;
  336. shortComponentName = _intent.getComponent().flattenToShortString();
  337. resolvedType = _resolvedType;
  338. componentSpecified = _componentSpecified;
  339. configuration = _configuration;
  340. resultTo = _resultTo;
  341. resultWho = _resultWho;
  342. requestCode = _reqCode;
  343. state = ActivityState.INITIALIZING;
  344. frontOfTask = false;
  345. launchFailed = false;
  346. stopped = false;
  347. delayedResume = false;
  348. finishing = false;
  349. configDestroy = false;
  350. keysPaused = false;
  351. inHistory = false;
  352. visible = true;
  353. waitingVisible = false;
  354. nowVisible = false;
  355. thumbnailNeeded = false;
  356. idle = false;
  357. hasBeenLaunched = false;
  358. mStackSupervisor = supervisor;
  359. // This starts out true, since the initial state of an activity
  360. // is that we have everything, and we shouldn't never consider it
  361. // lacking in state to be removed if it dies.
  362. haveState = true;
  363. if (aInfo != null) {
  364. if (aInfo.targetActivity == null
  365. || aInfo.launchMode == ActivityInfo.LAUNCH_MULTIPLE
  366. || aInfo.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
  367. realActivity = _intent.getComponent();
  368. } else {
  369. realActivity = new ComponentName(aInfo.packageName,
  370. aInfo.targetActivity);
  371. }
  372. taskAffinity = aInfo.taskAffinity;
  373. stateNotNeeded = (aInfo.flags&
  374. ActivityInfo.FLAG_STATE_NOT_NEEDED) != 0;
  375. baseDir = aInfo.applicationInfo.sourceDir;
  376. resDir = aInfo.applicationInfo.publicSourceDir;
  377. dataDir = aInfo.applicationInfo.dataDir;
  378. nonLocalizedLabel = aInfo.nonLocalizedLabel;
  379. labelRes = aInfo.labelRes;
  380. if (nonLocalizedLabel == null && labelRes == 0) {
  381. ApplicationInfo app = aInfo.applicationInfo;
  382. nonLocalizedLabel = app.nonLocalizedLabel;
  383. labelRes = app.labelRes;
  384. }
  385. icon = aInfo.getIconResource();
  386. logo = aInfo.getLogoResource();
  387. theme = aInfo.getThemeResource();
  388. realTheme = theme;
  389. if (realTheme == 0) {
  390. realTheme = aInfo.applicationInfo.targetSdkVersion
  391. < Build.VERSION_CODES.HONEYCOMB
  392. ? android.R.style.Theme
  393. : android.R.style.Theme_Holo;
  394. }
  395. if ((aInfo.flags&ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
  396. windowFlags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
  397. }
  398. if ((aInfo.flags&ActivityInfo.FLAG_MULTIPROCESS) != 0
  399. && _caller != null
  400. && (aInfo.applicationInfo.uid == Process.SYSTEM_UID
  401. || aInfo.applicationInfo.uid == _caller.info.uid)) {
  402. processName = _caller.processName;
  403. } else {
  404. processName = aInfo.processName;
  405. }
  406. if (intent != null && (aInfo.flags & ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS) != 0) {
  407. intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  408. }
  409. packageName = aInfo.applicationInfo.packageName;
  410. launchMode = aInfo.launchMode;
  411. AttributeCache.Entry ent = AttributeCache.instance().get(packageName,
  412. realTheme, com.android.internal.R.styleable.Window, userId);
  413. fullscreen = ent != null && !ent.array.getBoolean(
  414. com.android.internal.R.styleable.Window_windowIsFloating, false)
  415. && !ent.array.getBoolean(
  416. com.android.internal.R.styleable.Window_windowIsTranslucent, false);
  417. noDisplay = ent != null && ent.array.getBoolean(
  418. com.android.internal.R.styleable.Window_windowNoDisplay, false);
  419. if ((!_componentSpecified || _launchedFromUid == Process.myUid()
  420. || _launchedFromUid == 0) &&
  421. Intent.ACTION_MAIN.equals(_intent.getAction()) &&
  422. _intent.hasCategory(Intent.CATEGORY_HOME) &&
  423. _intent.getCategories().size() == 1 &&
  424. _intent.getData() == null &&
  425. _intent.getType() == null &&
  426. (intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
  427. isNotResolverActivity()) {
  428. // This sure looks like a home activity!
  429. mActivityType = HOME_ACTIVITY_TYPE;
  430. } else if (realActivity.getClassName().contains(RECENTS_PACKAGE_NAME)) {
  431. mActivityType = RECENTS_ACTIVITY_TYPE;
  432. } else {
  433. mActivityType = APPLICATION_ACTIVITY_TYPE;
  434. }
  435. immersive = (aInfo.flags & ActivityInfo.FLAG_IMMERSIVE) != 0;
  436. } else {
  437. realActivity = null;
  438. taskAffinity = null;
  439. stateNotNeeded = false;
  440. baseDir = null;
  441. resDir = null;
  442. dataDir = null;
  443. processName = null;
  444. packageName = null;
  445. fullscreen = true;
  446. noDisplay = false;
  447. mActivityType = APPLICATION_ACTIVITY_TYPE;
  448. immersive = false;
  449. }
  450. }
  451. void setTask(TaskRecord newTask, ThumbnailHolder newThumbHolder, boolean isRoot) {
  452. if (task != null && task.removeActivity(this)) {
  453. if (task != newTask) {
  454. mStackSupervisor.removeTask(task);
  455. } else {
  456. Slog.d(TAG, "!!! REMOVE THIS LOG !!! setTask: nearly removed stack=" +
  457. (newTask == null ? null : newTask.stack));
  458. }
  459. }
  460. if (inHistory && !finishing) {
  461. if (task != null) {
  462. task.numActivities--;
  463. }
  464. if (newTask != null) {
  465. newTask.numActivities++;
  466. }
  467. }
  468. if (newThumbHolder == null) {
  469. newThumbHolder = newTask;
  470. }
  471. task = newTask;
  472. if (!isRoot && (intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
  473. // This is the start of a new sub-task.
  474. if (thumbHolder == null) {
  475. thumbHolder = new ThumbnailHolder();
  476. }
  477. } else {
  478. thumbHolder = newThumbHolder;
  479. }
  480. }
  481. boolean changeWindowTranslucency(boolean toOpaque) {
  482. if (fullscreen == toOpaque) {
  483. return false;
  484. }
  485. AttributeCache.Entry ent =
  486. AttributeCache.instance().get(packageName, realTheme, styleable.Window, userId);
  487. if (ent == null
  488. || !ent.array.getBoolean(styleable.Window_windowIsTranslucent, false)
  489. || ent.array.getBoolean(styleable.Window_windowIsFloating, false)) {
  490. return false;
  491. }
  492. // Keep track of the number of fullscreen activities in this task.
  493. task.numFullscreen += toOpaque ? +1 : -1;
  494. fullscreen = toOpaque;
  495. return true;
  496. }
  497. void putInHistory() {
  498. if (!inHistory) {
  499. inHistory = true;
  500. if (task != null && !finishing) {
  501. task.numActivities++;
  502. }
  503. }
  504. }
  505. void takeFromHistory() {
  506. if (inHistory) {
  507. inHistory = false;
  508. if (task != null && !finishing) {
  509. task.numActivities--;
  510. task = null;
  511. }
  512. clearOptionsLocked();
  513. }
  514. }
  515. boolean isInHistory() {
  516. return inHistory;
  517. }
  518. boolean isHomeActivity() {
  519. return mActivityType == HOME_ACTIVITY_TYPE;
  520. }
  521. boolean isRecentsActivity() {
  522. return mActivityType == RECENTS_ACTIVITY_TYPE;
  523. }
  524. boolean isApplicationActivity() {
  525. return mActivityType == APPLICATION_ACTIVITY_TYPE;
  526. }
  527. void makeFinishing() {
  528. if (!finishing) {
  529. finishing = true;
  530. if (task != null && inHistory) {
  531. task.numActivities--;
  532. }
  533. if (stopped) {
  534. clearOptionsLocked();
  535. }
  536. }
  537. }
  538. boolean isRootActivity() {
  539. final ArrayList<ActivityRecord> activities = task.mActivities;
  540. return activities.size() == 0 || this == activities.get(0);
  541. }
  542. UriPermissionOwner getUriPermissionsLocked() {
  543. if (uriPermissions == null) {
  544. uriPermissions = new UriPermissionOwner(service, this);
  545. }
  546. return uriPermissions;
  547. }
  548. void addResultLocked(ActivityRecord from, String resultWho,
  549. int requestCode, int resultCode,
  550. Intent resultData) {
  551. ActivityResult r = new ActivityResult(from, resultWho,
  552. requestCode, resultCode, resultData);
  553. if (results == null) {
  554. results = new ArrayList<ResultInfo>();
  555. }
  556. results.add(r);
  557. }
  558. void removeResultsLocked(ActivityRecord from, String resultWho,
  559. int requestCode) {
  560. if (results != null) {
  561. for (int i=results.size()-1; i>=0; i--) {
  562. ActivityResult r = (ActivityResult)results.get(i);
  563. if (r.mFrom != from) continue;
  564. if (r.mResultWho == null) {
  565. if (resultWho != null) continue;
  566. } else {
  567. if (!r.mResultWho.equals(resultWho)) continue;
  568. }
  569. if (r.mRequestCode != requestCode) continue;
  570. results.remove(i);
  571. }
  572. }
  573. }
  574. void addNewIntentLocked(Intent intent) {
  575. if (newIntents == null) {
  576. newIntents = new ArrayList<Intent>();
  577. }
  578. newIntents.add(intent);
  579. }
  580. /**
  581. * Deliver a new Intent to an existing activity, so that its onNewIntent()
  582. * method will be called at the proper time.
  583. */
  584. final void deliverNewIntentLocked(int callingUid, Intent intent) {
  585. // The activity now gets access to the data associated with this Intent.
  586. service.grantUriPermissionFromIntentLocked(callingUid, packageName,
  587. intent, getUriPermissionsLocked());
  588. // We want to immediately deliver the intent to the activity if
  589. // it is currently the top resumed activity... however, if the
  590. // device is sleeping, then all activities are stopped, so in that
  591. // case we will deliver it if this is the current top activity on its
  592. // stack.
  593. boolean unsent = true;
  594. if ((state == ActivityState.RESUMED || (service.mSleeping
  595. && task.stack.topRunningActivityLocked(null) == this))
  596. && app != null && app.thread != null) {
  597. try {
  598. ArrayList<Intent> ar = new ArrayList<Intent>();
  599. intent = new Intent(intent);
  600. ar.add(intent);
  601. app.thread.scheduleNewIntent(ar, appToken);
  602. unsent = false;
  603. } catch (RemoteException e) {
  604. Slog.w(ActivityManagerService.TAG,
  605. "Exception thrown sending new intent to " + this, e);
  606. } catch (NullPointerException e) {
  607. Slog.w(ActivityManagerService.TAG,
  608. "Exception thrown sending new intent to " + this, e);
  609. }
  610. }
  611. if (unsent) {
  612. addNewIntentLocked(new Intent(intent));
  613. }
  614. }
  615. void updateOptionsLocked(Bundle options) {
  616. if (options != null) {
  617. if (pendingOptions != null) {
  618. pendingOptions.abort();
  619. }
  620. pendingOptions = new ActivityOptions(options);
  621. }
  622. }
  623. void updateOptionsLocked(ActivityOptions options) {
  624. if (options != null) {
  625. if (pendingOptions != null) {
  626. pendingOptions.abort();
  627. }
  628. pendingOptions = options;
  629. }
  630. }
  631. void applyOptionsLocked() {
  632. if (pendingOptions != null) {
  633. final int animationType = pendingOptions.getAnimationType();
  634. switch (animationType) {
  635. case ActivityOptions.ANIM_CUSTOM:
  636. service.mWindowManager.overridePendingAppTransition(
  637. pendingOptions.getPackageName(),
  638. pendingOptions.getCustomEnterResId(),
  639. pendingOptions.getCustomExitResId(),
  640. pendingOptions.getOnAnimationStartListener());
  641. break;
  642. case ActivityOptions.ANIM_SCALE_UP:
  643. service.mWindowManager.overridePendingAppTransitionScaleUp(
  644. pendingOptions.getStartX(), pendingOptions.getStartY(),
  645. pendingOptions.getStartWidth(), pendingOptions.getStartHeight());
  646. if (intent.getSourceBounds() == null) {
  647. intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
  648. pendingOptions.getStartY(),
  649. pendingOptions.getStartX()+pendingOptions.getStartWidth(),
  650. pendingOptions.getStartY()+pendingOptions.getStartHeight()));
  651. }
  652. break;
  653. case ActivityOptions.ANIM_THUMBNAIL_SCALE_UP:
  654. case ActivityOptions.ANIM_THUMBNAIL_SCALE_DOWN:
  655. boolean scaleUp = (animationType == ActivityOptions.ANIM_THUMBNAIL_SCALE_UP);
  656. service.mWindowManager.overridePendingAppTransitionThumb(
  657. pendingOptions.getThumbnail(),
  658. pendingOptions.getStartX(), pendingOptions.getStartY(),
  659. pendingOptions.getOnAnimationStartListener(),
  660. scaleUp);
  661. if (intent.getSourceBounds() == null) {
  662. intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
  663. pendingOptions.getStartY(),
  664. pendingOptions.getStartX()
  665. + pendingOptions.getThumbnail().getWidth(),
  666. pendingOptions.getStartY()
  667. + pendingOptions.getThumbnail().getHeight()));
  668. }
  669. break;
  670. }
  671. pendingOptions = null;
  672. }
  673. }
  674. void clearOptionsLocked() {
  675. if (pendingOptions != null) {
  676. pendingOptions.abort();
  677. pendingOptions = null;
  678. }
  679. }
  680. ActivityOptions takeOptionsLocked() {
  681. ActivityOptions opts = pendingOptions;
  682. pendingOptions = null;
  683. return opts;
  684. }
  685. void removeUriPermissionsLocked() {
  686. if (uriPermissions != null) {
  687. uriPermissions.removeUriPermissionsLocked();
  688. uriPermissions = null;
  689. }
  690. }
  691. void pauseKeyDispatchingLocked() {
  692. if (!keysPaused) {
  693. keysPaused = true;
  694. service.mWindowManager.pauseKeyDispatching(appToken);
  695. }
  696. }
  697. void resumeKeyDispatchingLocked() {
  698. if (keysPaused) {
  699. keysPaused = false;
  700. service.mWindowManager.resumeKeyDispatching(appToken);
  701. }
  702. }
  703. void updateThumbnail(Bitmap newThumbnail, CharSequence description) {
  704. if (thumbHolder != null) {
  705. if (newThumbnail != null) {
  706. if (ActivityManagerService.DEBUG_THUMBNAILS) Slog.i(ActivityManagerService.TAG,
  707. "Setting thumbnail of " + this + " holder " + thumbHolder
  708. + " to " + newThumbnail);
  709. thumbHolder.lastThumbnail = newThumbnail;
  710. }
  711. thumbHolder.lastDescription = description;
  712. }
  713. }
  714. void startLaunchTickingLocked() {
  715. if (ActivityManagerService.IS_USER_BUILD) {
  716. return;
  717. }
  718. if (launchTickTime == 0) {
  719. launchTickTime = SystemClock.uptimeMillis();
  720. continueLaunchTickingLocked();
  721. }
  722. }
  723. boolean continueLaunchTickingLocked() {
  724. if (launchTickTime != 0) {
  725. final ActivityStack stack = task.stack;
  726. Message msg = stack.mHandler.obtainMessage(ActivityStack.LAUNCH_TICK_MSG, this);
  727. stack.mHandler.removeMessages(ActivityStack.LAUNCH_TICK_MSG);
  728. stack.mHandler.sendMessageDelayed(msg, ActivityStack.LAUNCH_TICK);
  729. return true;
  730. }
  731. return false;
  732. }
  733. void finishLaunchTickingLocked() {
  734. launchTickTime = 0;
  735. task.stack.mHandler.removeMessages(ActivityStack.LAUNCH_TICK_MSG);
  736. }
  737. // IApplicationToken
  738. public boolean mayFreezeScreenLocked(ProcessRecord app) {
  739. // Only freeze the screen if this activity is currently attached to
  740. // an application, and that application is not blocked or unresponding.
  741. // In any other case, we can't count on getting the screen unfrozen,
  742. // so it is best to leave as-is.
  743. return app != null && !app.crashing && !app.notResponding;
  744. }
  745. public void startFreezingScreenLocked(ProcessRecord app, int configChanges) {
  746. if (mayFreezeScreenLocked(app)) {
  747. service.mWindowManager.startAppFreezingScreen(appToken, configChanges);
  748. }
  749. }
  750. public void stopFreezingScreenLocked(boolean force) {
  751. if (force || frozenBeforeDestroy) {
  752. frozenBeforeDestroy = false;
  753. service.mWindowManager.stopAppFreezingScreen(appToken, force);
  754. }
  755. }
  756. public void reportFullyDrawnLocked() {
  757. final long curTime = SystemClock.uptimeMillis();
  758. if (displayStartTime != 0) {
  759. reportLaunchTimeLocked(curTime);
  760. }
  761. if (fullyDrawnStartTime != 0) {
  762. final ActivityStack stack = task.stack;
  763. final long thisTime = curTime - fullyDrawnStartTime;
  764. final long totalTime = stack.mFullyDrawnStartTime != 0
  765. ? (curTime - stack.mFullyDrawnStartTime) : thisTime;
  766. if (ActivityManagerService.SHOW_ACTIVITY_START_TIME) {
  767. Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
  768. EventLog.writeEvent(EventLogTags.AM_ACTIVITY_FULLY_DRAWN_TIME,
  769. userId, System.identityHashCode(this), shortComponentName,
  770. thisTime, totalTime);
  771. StringBuilder sb = service.mStringBuilder;
  772. sb.setLength(0);
  773. sb.append("Fully drawn ");
  774. sb.append(shortComponentName);
  775. sb.append(": ");
  776. TimeUtils.formatDuration(thisTime, sb);
  777. if (thisTime != totalTime) {
  778. sb.append(" (total ");
  779. TimeUtils.formatDuration(totalTime, sb);
  780. sb.append(")");
  781. }
  782. Log.i(ActivityManagerService.TAG, sb.toString());
  783. }
  784. if (totalTime > 0) {
  785. service.mUsageStatsService.noteFullyDrawnTime(realActivity, (int) totalTime);
  786. }
  787. fullyDrawnStartTime = 0;
  788. stack.mFullyDrawnStartTime = 0;
  789. }
  790. }
  791. private void reportLaunchTimeLocked(final long curTime) {
  792. final ActivityStack stack = task.stack;
  793. final long thisTime = curTime - displayStartTime;
  794. final long totalTime = stack.mLaunchStartTime != 0
  795. ? (curTime - stack.mLaunchStartTime) : thisTime;
  796. if (ActivityManagerService.SHOW_ACTIVITY_START_TIME) {
  797. Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "launching", 0);
  798. EventLog.writeEvent(EventLogTags.AM_ACTIVITY_LAUNCH_TIME,
  799. userId, System.identityHashCode(this), shortComponentName,
  800. thisTime, totalTime);
  801. StringBuilder sb = service.mStringBuilder;
  802. sb.setLength(0);
  803. sb.append("Displayed ");
  804. sb.append(shortComponentName);
  805. sb.append(": ");
  806. TimeUtils.formatDuration(thisTime, sb);
  807. if (thisTime != totalTime) {
  808. sb.append(" (total ");
  809. TimeUtils.formatDuration(totalTime, sb);
  810. sb.append(")");
  811. }
  812. Log.i(ActivityManagerService.TAG, sb.toString());
  813. }
  814. mStackSupervisor.reportActivityLaunchedLocked(false, this, thisTime, totalTime);
  815. if (totalTime > 0) {
  816. service.mUsageStatsService.noteLaunchTime(realActivity, (int)totalTime);
  817. }
  818. displayStartTime = 0;
  819. stack.mLaunchStartTime = 0;
  820. }
  821. public void windowsDrawn() {
  822. synchronized(service) {
  823. if (displayStartTime != 0) {
  824. reportLaunchTimeLocked(SystemClock.uptimeMillis());
  825. }
  826. startTime = 0;
  827. finishLaunchTickingLocked();
  828. }
  829. }
  830. public void windowsVisible() {
  831. synchronized(service) {
  832. mStackSupervisor.reportActivityVisibleLocked(this);
  833. if (ActivityManagerService.DEBUG_SWITCH) Log.v(
  834. ActivityManagerService.TAG, "windowsVisible(): " + this);
  835. if (!nowVisible) {
  836. nowVisible = true;
  837. lastVisibleTime = SystemClock.uptimeMillis();
  838. if (!idle) {
  839. // Instead of doing the full stop routine here, let's just
  840. // hide any activities we now can, and let them stop when
  841. // the normal idle happens.
  842. mStackSupervisor.processStoppingActivitiesLocked(false);
  843. } else {
  844. // If this activity was already idle, then we now need to
  845. // make sure we perform the full stop of any activities
  846. // that are waiting to do so. This is because we won't
  847. // do that while they are still waiting for this one to
  848. // become visible.
  849. final int N = mStackSupervisor.mWaitingVisibleActivities.size();
  850. if (N > 0) {
  851. for (int i=0; i<N; i++) {
  852. ActivityRecord r = mStackSupervisor.mWaitingVisibleActivities.get(i);
  853. r.waitingVisible = false;
  854. if (ActivityManagerService.DEBUG_SWITCH) Log.v(
  855. ActivityManagerService.TAG,
  856. "Was waiting for visible: " + r);
  857. }
  858. mStackSupervisor.mWaitingVisibleActivities.clear();
  859. mStackSupervisor.scheduleIdleLocked();
  860. }
  861. }
  862. service.scheduleAppGcsLocked();
  863. }
  864. }
  865. }
  866. public void windowsGone() {
  867. if (ActivityManagerService.DEBUG_SWITCH) Log.v(
  868. ActivityManagerService.TAG, "windowsGone(): " + this);
  869. nowVisible = false;
  870. }
  871. private ActivityRecord getWaitingHistoryRecordLocked() {
  872. // First find the real culprit... if we are waiting
  873. // for another app to start, then we have paused dispatching
  874. // for this activity.
  875. ActivityRecord r = this;
  876. if (r.waitingVisible) {
  877. final ActivityStack stack = mStackSupervisor.getFocusedStack();
  878. // Hmmm, who might we be waiting for?
  879. r = stack.mResumedActivity;
  880. if (r == null) {
  881. r = stack.mPausingActivity;
  882. }
  883. // Both of those null? Fall back to 'this' again
  884. if (r == null) {
  885. r = this;
  886. }
  887. }
  888. return r;
  889. }
  890. public boolean keyDispatchingTimedOut(String reason) {
  891. ActivityRecord r;
  892. ProcessRecord anrApp;
  893. synchronized(service) {
  894. r = getWaitingHistoryRecordLocked();
  895. anrApp = r != null ? r.app : null;
  896. }
  897. return service.inputDispatchingTimedOut(anrApp, r, this, false, reason);
  898. }
  899. /** Returns the key dispatching timeout for this application token. */
  900. public long getKeyDispatchingTimeout() {
  901. synchronized(service) {
  902. ActivityRecord r = getWaitingHistoryRecordLocked();
  903. return ActivityManagerService.getInputDispatchingTimeoutLocked(r);
  904. }
  905. }
  906. /**
  907. * This method will return true if the activity is either visible, is becoming visible, is
  908. * currently pausing, or is resumed.
  909. */
  910. public boolean isInterestingToUserLocked() {
  911. return visible || nowVisible || state == ActivityState.PAUSING ||
  912. state == ActivityState.RESUMED;
  913. }
  914. public void setSleeping(boolean _sleeping) {
  915. if (sleeping == _sleeping) {
  916. return;
  917. }
  918. if (app != null && app.thread != null) {
  919. try {
  920. app.thread.scheduleSleeping(appToken, _sleeping);
  921. if (_sleeping && !mStackSupervisor.mGoingToSleepActivities.contains(this)) {
  922. mStackSupervisor.mGoingToSleepActivities.add(this);
  923. }
  924. sleeping = _sleeping;
  925. } catch (RemoteException e) {
  926. Slog.w(TAG, "Exception thrown when sleeping: " + intent.getComponent(), e);
  927. }
  928. }
  929. }
  930. static void activityResumedLocked(IBinder token) {
  931. final ActivityRecord r = ActivityRecord.forToken(token);
  932. if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; dropping state of: " + r);
  933. r.icicle = null;
  934. r.haveState = false;
  935. }
  936. static int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
  937. final ActivityRecord r = ActivityRecord.forToken(token);
  938. if (r == null) {
  939. return -1;
  940. }
  941. final TaskRecord task = r.task;
  942. switch (task.mActivities.indexOf(r)) {
  943. case -1: return -1;
  944. case 0: return task.taskId;
  945. default: return onlyRoot ? -1 : task.taskId;
  946. }
  947. }
  948. static ActivityRecord isInStackLocked(IBinder token) {
  949. final ActivityRecord r = ActivityRecord.forToken(token);
  950. if (r != null) {
  951. return r.task.stack.isInStackLocked(token);
  952. }
  953. return null;
  954. }
  955. static ActivityStack getStackLocked(IBinder token) {
  956. final ActivityRecord r = ActivityRecord.isInStackLocked(token);
  957. if (r != null) {
  958. return r.task.stack;
  959. }
  960. return null;
  961. }
  962. private String activityTypeToString(int type) {
  963. switch (type) {
  964. case APPLICATION_ACTIVITY_TYPE: return "APPLICATION_ACTIVITY_TYPE";
  965. case HOME_ACTIVITY_TYPE: return "HOME_ACTIVITY_TYPE";
  966. case RECENTS_ACTIVITY_TYPE: return "RECENTS_ACTIVITY_TYPE";
  967. default: return Integer.toString(type);
  968. }
  969. }
  970. @Override
  971. public String toString() {
  972. if (stringName != null) {
  973. return stringName + " t" + (task == null ? -1 : task.taskId) +
  974. (finishing ? " f}" : "}");
  975. }
  976. StringBuilder sb = new StringBuilder(128);
  977. sb.append("ActivityRecord{");
  978. sb.append(Integer.toHexString(System.identityHashCode(this)));
  979. sb.append(" u");
  980. sb.append(userId);
  981. sb.append(' ');
  982. sb.append(intent.getComponent().flattenToShortString());
  983. stringName = sb.toString();
  984. return toString();
  985. }
  986. }