Am.java revision 06e8ee0c8ad2527add3db3dd1a1d4eee9d8631f8
1/* 2** 3** Copyright 2007, The Android Open Source Project 4** 5** Licensed under the Apache License, Version 2.0 (the "License"); 6** you may not use this file except in compliance with the License. 7** You may obtain a copy of the License at 8** 9** http://www.apache.org/licenses/LICENSE-2.0 10** 11** Unless required by applicable law or agreed to in writing, software 12** distributed under the License is distributed on an "AS IS" BASIS, 13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14** See the License for the specific language governing permissions and 15** limitations under the License. 16*/ 17 18 19package com.android.commands.am; 20 21import static android.app.ActivityManager.StackId.DOCKED_STACK_ID; 22import static android.app.ActivityManager.RESIZE_MODE_SYSTEM; 23import static android.app.ActivityManager.RESIZE_MODE_USER; 24import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID; 25 26import android.app.ActivityManager; 27import android.app.ActivityManager.StackInfo; 28import android.app.ActivityManagerNative; 29import android.app.ActivityOptions; 30import android.app.IActivityContainer; 31import android.app.IActivityController; 32import android.app.IActivityManager; 33import android.app.IInstrumentationWatcher; 34import android.app.Instrumentation; 35import android.app.IStopUserCallback; 36import android.app.ProfilerInfo; 37import android.app.UiAutomationConnection; 38import android.app.usage.ConfigurationStats; 39import android.app.usage.IUsageStatsManager; 40import android.app.usage.UsageStatsManager; 41import android.content.ComponentCallbacks2; 42import android.content.ComponentName; 43import android.content.Context; 44import android.content.IIntentReceiver; 45import android.content.Intent; 46import android.content.pm.IPackageManager; 47import android.content.pm.ParceledListSlice; 48import android.content.pm.ResolveInfo; 49import android.content.pm.UserInfo; 50import android.content.res.Configuration; 51import android.graphics.Rect; 52import android.os.Binder; 53import android.os.Build; 54import android.os.Bundle; 55import android.os.ParcelFileDescriptor; 56import android.os.RemoteException; 57import android.os.SELinux; 58import android.os.ServiceManager; 59import android.os.ShellCommand; 60import android.os.SystemClock; 61import android.os.SystemProperties; 62import android.os.UserHandle; 63import android.text.TextUtils; 64import android.util.AndroidException; 65import android.util.ArrayMap; 66import android.view.IWindowManager; 67 68import com.android.internal.os.BaseCommand; 69import com.android.internal.util.HexDump; 70import com.android.internal.util.Preconditions; 71 72import java.io.BufferedReader; 73import java.io.File; 74import java.io.FileNotFoundException; 75import java.io.IOException; 76import java.io.InputStreamReader; 77import java.io.PrintStream; 78import java.io.PrintWriter; 79import java.net.URISyntaxException; 80import java.util.ArrayList; 81import java.util.Collections; 82import java.util.Comparator; 83import java.util.List; 84 85public class Am extends BaseCommand { 86 87 private static final String SHELL_PACKAGE_NAME = "com.android.shell"; 88 89 // Is the object moving in a positive direction? 90 private static final boolean MOVING_FORWARD = true; 91 // Is the object moving in the horizontal plan? 92 private static final boolean MOVING_HORIZONTALLY = true; 93 // Is the object current point great then its target point? 94 private static final boolean GREATER_THAN_TARGET = true; 95 // Amount we reduce the stack size by when testing a task re-size. 96 private static final int STACK_BOUNDS_INSET = 10; 97 98 private IActivityManager mAm; 99 100 private int mStartFlags = 0; 101 private boolean mWaitOption = false; 102 private boolean mStopOption = false; 103 104 private int mRepeat = 0; 105 private int mUserId; 106 private String mReceiverPermission; 107 108 private String mProfileFile; 109 private int mSamplingInterval; 110 private boolean mAutoStop; 111 private int mStackId; 112 113 /** 114 * Command-line entry point. 115 * 116 * @param args The command-line arguments 117 */ 118 public static void main(String[] args) { 119 (new Am()).run(args); 120 } 121 122 @Override 123 public void onShowUsage(PrintStream out) { 124 PrintWriter pw = new PrintWriter(out); 125 pw.println( 126 "usage: am [subcommand] [options]\n" + 127 "usage: am start [-D] [-N] [-W] [-P <FILE>] [--start-profiler <FILE>]\n" + 128 " [--sampling INTERVAL] [-R COUNT] [-S]\n" + 129 " [--track-allocation] [--user <USER_ID> | current] <INTENT>\n" + 130 " am startservice [--user <USER_ID> | current] <INTENT>\n" + 131 " am stopservice [--user <USER_ID> | current] <INTENT>\n" + 132 " am force-stop [--user <USER_ID> | all | current] <PACKAGE>\n" + 133 " am kill [--user <USER_ID> | all | current] <PACKAGE>\n" + 134 " am kill-all\n" + 135 " am broadcast [--user <USER_ID> | all | current] <INTENT>\n" + 136 " am instrument [-r] [-e <NAME> <VALUE>] [-p <FILE>] [-w]\n" + 137 " [--user <USER_ID> | current]\n" + 138 " [--no-window-animation] [--abi <ABI>] <COMPONENT>\n" + 139 " am profile start [--user <USER_ID> current] [--sampling INTERVAL] <PROCESS> <FILE>\n" + 140 " am profile stop [--user <USER_ID> current] [<PROCESS>]\n" + 141 " am dumpheap [--user <USER_ID> current] [-n] <PROCESS> <FILE>\n" + 142 " am set-debug-app [-w] [--persistent] <PACKAGE>\n" + 143 " am clear-debug-app\n" + 144 " am set-watch-heap <PROCESS> <MEM-LIMIT>\n" + 145 " am clear-watch-heap\n" + 146 " am bug-report [--progress]\n" + 147 " am monitor [--gdb <port>]\n" + 148 " am hang [--allow-restart]\n" + 149 " am restart\n" + 150 " am idle-maintenance\n" + 151 " am screen-compat [on|off] <PACKAGE>\n" + 152 " am package-importance <PACKAGE>\n" + 153 " am to-uri [INTENT]\n" + 154 " am to-intent-uri [INTENT]\n" + 155 " am to-app-uri [INTENT]\n" + 156 " am switch-user <USER_ID>\n" + 157 " am start-user <USER_ID>\n" + 158 " am unlock-user <USER_ID> [TOKEN_HEX]\n" + 159 " am stop-user [-w] [-f] <USER_ID>\n" + 160 " am stack start <DISPLAY_ID> <INTENT>\n" + 161 " am stack movetask <TASK_ID> <STACK_ID> [true|false]\n" + 162 " am stack resize <STACK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" + 163 " am stack resize-animated <STACK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" + 164 " am stack resize-docked-stack <LEFT,TOP,RIGHT,BOTTOM> [<TASK_LEFT,TASK_TOP,TASK_RIGHT,TASK_BOTTOM>]\n" + 165 " am stack size-docked-stack-test: <STEP_SIZE> <l|t|r|b> [DELAY_MS]\n" + 166 " am stack move-top-activity-to-pinned-stack: <STACK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" + 167 " am stack positiontask <TASK_ID> <STACK_ID> <POSITION>\n" + 168 " am stack list\n" + 169 " am stack info <STACK_ID>\n" + 170 " am stack remove <STACK_ID>\n" + 171 " am task lock <TASK_ID>\n" + 172 " am task lock stop\n" + 173 " am task resizeable <TASK_ID> [0 (unresizeable) | 1 (crop_windows) | 2 (resizeable) | 3 (resizeable_and_pipable)]\n" + 174 " am task resize <TASK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" + 175 " am task drag-task-test <TASK_ID> <STEP_SIZE> [DELAY_MS] \n" + 176 " am task size-task-test <TASK_ID> <STEP_SIZE> [DELAY_MS] \n" + 177 " am get-config\n" + 178 " am suppress-resize-config-changes <true|false>\n" + 179 " am set-inactive [--user <USER_ID>] <PACKAGE> true|false\n" + 180 " am get-inactive [--user <USER_ID>] <PACKAGE>\n" + 181 " am send-trim-memory [--user <USER_ID>] <PROCESS>\n" + 182 " [HIDDEN|RUNNING_MODERATE|BACKGROUND|RUNNING_LOW|MODERATE|RUNNING_CRITICAL|COMPLETE]\n" + 183 " am get-current-user\n" + 184 "\n" + 185 "am start: start an Activity. Options are:\n" + 186 " -D: enable debugging\n" + 187 " -N: enable native debugging\n" + 188 " -W: wait for launch to complete\n" + 189 " --start-profiler <FILE>: start profiler and send results to <FILE>\n" + 190 " --sampling INTERVAL: use sample profiling with INTERVAL microseconds\n" + 191 " between samples (use with --start-profiler)\n" + 192 " -P <FILE>: like above, but profiling stops when app goes idle\n" + 193 " -R: repeat the activity launch <COUNT> times. Prior to each repeat,\n" + 194 " the top activity will be finished.\n" + 195 " -S: force stop the target app before starting the activity\n" + 196 " --track-allocation: enable tracking of object allocations\n" + 197 " --user <USER_ID> | current: Specify which user to run as; if not\n" + 198 " specified then run as the current user.\n" + 199 " --stack <STACK_ID>: Specify into which stack should the activity be put." + 200 "\n" + 201 "am startservice: start a Service. Options are:\n" + 202 " --user <USER_ID> | current: Specify which user to run as; if not\n" + 203 " specified then run as the current user.\n" + 204 "\n" + 205 "am stopservice: stop a Service. Options are:\n" + 206 " --user <USER_ID> | current: Specify which user to run as; if not\n" + 207 " specified then run as the current user.\n" + 208 "\n" + 209 "am force-stop: force stop everything associated with <PACKAGE>.\n" + 210 " --user <USER_ID> | all | current: Specify user to force stop;\n" + 211 " all users if not specified.\n" + 212 "\n" + 213 "am kill: Kill all processes associated with <PACKAGE>. Only kills.\n" + 214 " processes that are safe to kill -- that is, will not impact the user\n" + 215 " experience.\n" + 216 " --user <USER_ID> | all | current: Specify user whose processes to kill;\n" + 217 " all users if not specified.\n" + 218 "\n" + 219 "am kill-all: Kill all background processes.\n" + 220 "\n" + 221 "am broadcast: send a broadcast Intent. Options are:\n" + 222 " --user <USER_ID> | all | current: Specify which user to send to; if not\n" + 223 " specified then send to all users.\n" + 224 " --receiver-permission <PERMISSION>: Require receiver to hold permission.\n" + 225 "\n" + 226 "am instrument: start an Instrumentation. Typically this target <COMPONENT>\n" + 227 " is the form <TEST_PACKAGE>/<RUNNER_CLASS>. Options are:\n" + 228 " -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT). Use with\n" + 229 " [-e perf true] to generate raw output for performance measurements.\n" + 230 " -e <NAME> <VALUE>: set argument <NAME> to <VALUE>. For test runners a\n" + 231 " common form is [-e <testrunner_flag> <value>[,<value>...]].\n" + 232 " -p <FILE>: write profiling data to <FILE>\n" + 233 " -w: wait for instrumentation to finish before returning. Required for\n" + 234 " test runners.\n" + 235 " --user <USER_ID> | current: Specify user instrumentation runs in;\n" + 236 " current user if not specified.\n" + 237 " --no-window-animation: turn off window animations while running.\n" + 238 " --abi <ABI>: Launch the instrumented process with the selected ABI.\n" + 239 " This assumes that the process supports the selected ABI.\n" + 240 "\n" + 241 "am trace-ipc: Trace IPC transactions.\n" + 242 " start: start tracing IPC transactions.\n" + 243 " stop: stop tracing IPC transactions and dump the results to file.\n" + 244 " --dump-file <FILE>: Specify the file the trace should be dumped to.\n" + 245 "\n" + 246 "am profile: start and stop profiler on a process. The given <PROCESS> argument\n" + 247 " may be either a process name or pid. Options are:\n" + 248 " --user <USER_ID> | current: When supplying a process name,\n" + 249 " specify user of process to profile; uses current user if not specified.\n" + 250 "\n" + 251 "am dumpheap: dump the heap of a process. The given <PROCESS> argument may\n" + 252 " be either a process name or pid. Options are:\n" + 253 " -n: dump native heap instead of managed heap\n" + 254 " --user <USER_ID> | current: When supplying a process name,\n" + 255 " specify user of process to dump; uses current user if not specified.\n" + 256 "\n" + 257 "am set-debug-app: set application <PACKAGE> to debug. Options are:\n" + 258 " -w: wait for debugger when application starts\n" + 259 " --persistent: retain this value\n" + 260 "\n" + 261 "am clear-debug-app: clear the previously set-debug-app.\n" + 262 "\n" + 263 "am set-watch-heap: start monitoring pss size of <PROCESS>, if it is at or\n" + 264 " above <HEAP-LIMIT> then a heap dump is collected for the user to report\n" + 265 "\n" + 266 "am clear-watch-heap: clear the previously set-watch-heap.\n" + 267 "\n" + 268 "am bug-report: request bug report generation; will launch a notification\n" + 269 " when done to select where it should be delivered. Options are: \n" + 270 " --progress: will launch a notification right away to show its progress.\n" + 271 "\n" + 272 "am monitor: start monitoring for crashes or ANRs.\n" + 273 " --gdb: start gdbserv on the given port at crash/ANR\n" + 274 "\n" + 275 "am hang: hang the system.\n" + 276 " --allow-restart: allow watchdog to perform normal system restart\n" + 277 "\n" + 278 "am restart: restart the user-space system.\n" + 279 "\n" + 280 "am idle-maintenance: perform idle maintenance now.\n" + 281 "\n" + 282 "am screen-compat: control screen compatibility mode of <PACKAGE>.\n" + 283 "\n" + 284 "am package-importance: print current importance of <PACKAGE>.\n" + 285 "\n" + 286 "am to-uri: print the given Intent specification as a URI.\n" + 287 "\n" + 288 "am to-intent-uri: print the given Intent specification as an intent: URI.\n" + 289 "\n" + 290 "am to-app-uri: print the given Intent specification as an android-app: URI.\n" + 291 "\n" + 292 "am switch-user: switch to put USER_ID in the foreground, starting\n" + 293 " execution of that user if it is currently stopped.\n" + 294 "\n" + 295 "am start-user: start USER_ID in background if it is currently stopped,\n" + 296 " use switch-user if you want to start the user in foreground.\n" + 297 "\n" + 298 "am stop-user: stop execution of USER_ID, not allowing it to run any\n" + 299 " code until a later explicit start or switch to it.\n" + 300 " -w: wait for stop-user to complete.\n" + 301 " -f: force stop even if there are related users that cannot be stopped.\n" + 302 "\n" + 303 "am stack start: start a new activity on <DISPLAY_ID> using <INTENT>.\n" + 304 "\n" + 305 "am stack movetask: move <TASK_ID> from its current stack to the top (true) or" + 306 " bottom (false) of <STACK_ID>.\n" + 307 "\n" + 308 "am stack resize: change <STACK_ID> size and position to <LEFT,TOP,RIGHT,BOTTOM>.\n" + 309 "\n" + 310 "am stack resize-docked-stack: change docked stack to <LEFT,TOP,RIGHT,BOTTOM>\n" + 311 " and supplying temporary different task bounds indicated by\n" + 312 " <TASK_LEFT,TOP,RIGHT,BOTTOM>\n" + 313 "\n" + 314 "am stack size-docked-stack-test: test command for sizing docked stack by\n" + 315 " <STEP_SIZE> increments from the side <l>eft, <t>op, <r>ight, or <b>ottom\n" + 316 " applying the optional [DELAY_MS] between each step.\n" + 317 "\n" + 318 "am stack move-top-activity-to-pinned-stack: moves the top activity from\n" + 319 " <STACK_ID> to the pinned stack using <LEFT,TOP,RIGHT,BOTTOM> for the\n" + 320 " bounds of the pinned stack.\n" + 321 "\n" + 322 "am stack positiontask: place <TASK_ID> in <STACK_ID> at <POSITION>" + 323 "\n" + 324 "am stack list: list all of the activity stacks and their sizes.\n" + 325 "\n" + 326 "am stack info: display the information about activity stack <STACK_ID>.\n" + 327 "\n" + 328 "am stack remove: remove stack <STACK_ID>.\n" + 329 "\n" + 330 "am task lock: bring <TASK_ID> to the front and don't allow other tasks to run.\n" + 331 "\n" + 332 "am task lock stop: end the current task lock.\n" + 333 "\n" + 334 "am task resizeable: change resizeable mode of <TASK_ID>.\n" + 335 " 0 (unresizeable) | 1 (crop_windows) | 2 (resizeable) | 3 (resizeable_and_pipable)\n" + 336 "\n" + 337 "am task resize: makes sure <TASK_ID> is in a stack with the specified bounds.\n" + 338 " Forces the task to be resizeable and creates a stack if no existing stack\n" + 339 " has the specified bounds.\n" + 340 "\n" + 341 "am task drag-task-test: test command for dragging/moving <TASK_ID> by\n" + 342 " <STEP_SIZE> increments around the screen applying the optional [DELAY_MS]\n" + 343 " between each step.\n" + 344 "\n" + 345 "am task size-task-test: test command for sizing <TASK_ID> by <STEP_SIZE>" + 346 " increments within the screen applying the optional [DELAY_MS] between\n" + 347 " each step.\n" + 348 "\n" + 349 "am get-config: retrieve the configuration and any recent configurations\n" + 350 " of the device.\n" + 351 "am suppress-resize-config-changes: suppresses configuration changes due to\n" + 352 " user resizing an activity/task.\n" + 353 "\n" + 354 "am set-inactive: sets the inactive state of an app.\n" + 355 "\n" + 356 "am get-inactive: returns the inactive state of an app.\n" + 357 "\n" + 358 "am send-trim-memory: send a memory trim event to a <PROCESS>.\n" + 359 "\n" + 360 "am get-current-user: returns id of the current foreground user.\n" + 361 "\n" 362 ); 363 Intent.printIntentArgsHelp(pw, ""); 364 pw.flush(); 365 } 366 367 @Override 368 public void onRun() throws Exception { 369 370 mAm = ActivityManagerNative.getDefault(); 371 if (mAm == null) { 372 System.err.println(NO_SYSTEM_ERROR_CODE); 373 throw new AndroidException("Can't connect to activity manager; is the system running?"); 374 } 375 376 String op = nextArgRequired(); 377 378 if (op.equals("start")) { 379 runStart(); 380 } else if (op.equals("startservice")) { 381 runStartService(); 382 } else if (op.equals("stopservice")) { 383 runStopService(); 384 } else if (op.equals("force-stop")) { 385 runForceStop(); 386 } else if (op.equals("kill")) { 387 runKill(); 388 } else if (op.equals("kill-all")) { 389 runKillAll(); 390 } else if (op.equals("instrument")) { 391 runInstrument(); 392 } else if (op.equals("trace-ipc")) { 393 runTraceIpc(); 394 } else if (op.equals("broadcast")) { 395 sendBroadcast(); 396 } else if (op.equals("profile")) { 397 runProfile(); 398 } else if (op.equals("dumpheap")) { 399 runDumpHeap(); 400 } else if (op.equals("set-debug-app")) { 401 runSetDebugApp(); 402 } else if (op.equals("clear-debug-app")) { 403 runClearDebugApp(); 404 } else if (op.equals("set-watch-heap")) { 405 runSetWatchHeap(); 406 } else if (op.equals("clear-watch-heap")) { 407 runClearWatchHeap(); 408 } else if (op.equals("bug-report")) { 409 runBugReport(); 410 } else if (op.equals("monitor")) { 411 runMonitor(); 412 } else if (op.equals("hang")) { 413 runHang(); 414 } else if (op.equals("restart")) { 415 runRestart(); 416 } else if (op.equals("idle-maintenance")) { 417 runIdleMaintenance(); 418 } else if (op.equals("screen-compat")) { 419 runScreenCompat(); 420 } else if (op.equals("package-importance")) { 421 runPackageImportance(); 422 } else if (op.equals("to-uri")) { 423 runToUri(0); 424 } else if (op.equals("to-intent-uri")) { 425 runToUri(Intent.URI_INTENT_SCHEME); 426 } else if (op.equals("to-app-uri")) { 427 runToUri(Intent.URI_ANDROID_APP_SCHEME); 428 } else if (op.equals("switch-user")) { 429 runSwitchUser(); 430 } else if (op.equals("start-user")) { 431 runStartUserInBackground(); 432 } else if (op.equals("unlock-user")) { 433 runUnlockUser(); 434 } else if (op.equals("stop-user")) { 435 runStopUser(); 436 } else if (op.equals("stack")) { 437 runStack(); 438 } else if (op.equals("task")) { 439 runTask(); 440 } else if (op.equals("get-config")) { 441 runGetConfig(); 442 } else if (op.equals("suppress-resize-config-changes")) { 443 runSuppressResizeConfigChanges(); 444 } else if (op.equals("set-inactive")) { 445 runSetInactive(); 446 } else if (op.equals("get-inactive")) { 447 runGetInactive(); 448 } else if (op.equals("send-trim-memory")) { 449 runSendTrimMemory(); 450 } else if (op.equals("get-current-user")) { 451 runGetCurrentUser(); 452 } else { 453 showError("Error: unknown command '" + op + "'"); 454 } 455 } 456 457 int parseUserArg(String arg) { 458 int userId; 459 if ("all".equals(arg)) { 460 userId = UserHandle.USER_ALL; 461 } else if ("current".equals(arg) || "cur".equals(arg)) { 462 userId = UserHandle.USER_CURRENT; 463 } else { 464 userId = Integer.parseInt(arg); 465 } 466 return userId; 467 } 468 469 private Intent makeIntent(int defUser) throws URISyntaxException { 470 mStartFlags = 0; 471 mWaitOption = false; 472 mStopOption = false; 473 mRepeat = 0; 474 mProfileFile = null; 475 mSamplingInterval = 0; 476 mAutoStop = false; 477 mUserId = defUser; 478 mStackId = FULLSCREEN_WORKSPACE_STACK_ID; 479 480 return Intent.parseCommandArgs(mArgs, new Intent.CommandOptionHandler() { 481 @Override 482 public boolean handleOption(String opt, ShellCommand cmd) { 483 if (opt.equals("-D")) { 484 mStartFlags |= ActivityManager.START_FLAG_DEBUG; 485 } else if (opt.equals("-N")) { 486 mStartFlags |= ActivityManager.START_FLAG_NATIVE_DEBUGGING; 487 } else if (opt.equals("-W")) { 488 mWaitOption = true; 489 } else if (opt.equals("-P")) { 490 mProfileFile = nextArgRequired(); 491 mAutoStop = true; 492 } else if (opt.equals("--start-profiler")) { 493 mProfileFile = nextArgRequired(); 494 mAutoStop = false; 495 } else if (opt.equals("--sampling")) { 496 mSamplingInterval = Integer.parseInt(nextArgRequired()); 497 } else if (opt.equals("-R")) { 498 mRepeat = Integer.parseInt(nextArgRequired()); 499 } else if (opt.equals("-S")) { 500 mStopOption = true; 501 } else if (opt.equals("--track-allocation")) { 502 mStartFlags |= ActivityManager.START_FLAG_TRACK_ALLOCATION; 503 } else if (opt.equals("--user")) { 504 mUserId = parseUserArg(nextArgRequired()); 505 } else if (opt.equals("--receiver-permission")) { 506 mReceiverPermission = nextArgRequired(); 507 } else if (opt.equals("--stack")) { 508 mStackId = Integer.parseInt(nextArgRequired()); 509 } else { 510 return false; 511 } 512 return true; 513 } 514 }); 515 } 516 517 private void runStartService() throws Exception { 518 Intent intent = makeIntent(UserHandle.USER_CURRENT); 519 if (mUserId == UserHandle.USER_ALL) { 520 System.err.println("Error: Can't start activity with user 'all'"); 521 return; 522 } 523 System.out.println("Starting service: " + intent); 524 ComponentName cn = mAm.startService(null, intent, intent.getType(), 525 SHELL_PACKAGE_NAME, mUserId); 526 if (cn == null) { 527 System.err.println("Error: Not found; no service started."); 528 } else if (cn.getPackageName().equals("!")) { 529 System.err.println("Error: Requires permission " + cn.getClassName()); 530 } else if (cn.getPackageName().equals("!!")) { 531 System.err.println("Error: " + cn.getClassName()); 532 } 533 } 534 535 private void runStopService() throws Exception { 536 Intent intent = makeIntent(UserHandle.USER_CURRENT); 537 if (mUserId == UserHandle.USER_ALL) { 538 System.err.println("Error: Can't stop activity with user 'all'"); 539 return; 540 } 541 System.out.println("Stopping service: " + intent); 542 int result = mAm.stopService(null, intent, intent.getType(), mUserId); 543 if (result == 0) { 544 System.err.println("Service not stopped: was not running."); 545 } else if (result == 1) { 546 System.err.println("Service stopped"); 547 } else if (result == -1) { 548 System.err.println("Error stopping service"); 549 } 550 } 551 552 private void runStart() throws Exception { 553 Intent intent = makeIntent(UserHandle.USER_CURRENT); 554 555 if (mUserId == UserHandle.USER_ALL) { 556 System.err.println("Error: Can't start service with user 'all'"); 557 return; 558 } 559 560 String mimeType = intent.getType(); 561 if (mimeType == null && intent.getData() != null 562 && "content".equals(intent.getData().getScheme())) { 563 mimeType = mAm.getProviderMimeType(intent.getData(), mUserId); 564 } 565 566 567 do { 568 if (mStopOption) { 569 String packageName; 570 if (intent.getComponent() != null) { 571 packageName = intent.getComponent().getPackageName(); 572 } else { 573 IPackageManager pm = IPackageManager.Stub.asInterface( 574 ServiceManager.getService("package")); 575 if (pm == null) { 576 System.err.println("Error: Package manager not running; aborting"); 577 return; 578 } 579 List<ResolveInfo> activities = pm.queryIntentActivities(intent, mimeType, 0, 580 mUserId); 581 if (activities == null || activities.size() <= 0) { 582 System.err.println("Error: Intent does not match any activities: " 583 + intent); 584 return; 585 } else if (activities.size() > 1) { 586 System.err.println("Error: Intent matches multiple activities; can't stop: " 587 + intent); 588 return; 589 } 590 packageName = activities.get(0).activityInfo.packageName; 591 } 592 System.out.println("Stopping: " + packageName); 593 mAm.forceStopPackage(packageName, mUserId); 594 Thread.sleep(250); 595 } 596 597 System.out.println("Starting: " + intent); 598 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 599 600 ParcelFileDescriptor fd = null; 601 ProfilerInfo profilerInfo = null; 602 603 if (mProfileFile != null) { 604 try { 605 fd = openForSystemServer( 606 new File(mProfileFile), 607 ParcelFileDescriptor.MODE_CREATE | 608 ParcelFileDescriptor.MODE_TRUNCATE | 609 ParcelFileDescriptor.MODE_READ_WRITE); 610 } catch (FileNotFoundException e) { 611 System.err.println("Error: Unable to open file: " + mProfileFile); 612 System.err.println("Consider using a file under /data/local/tmp/"); 613 return; 614 } 615 profilerInfo = new ProfilerInfo(mProfileFile, fd, mSamplingInterval, mAutoStop); 616 } 617 618 IActivityManager.WaitResult result = null; 619 int res; 620 final long startTime = SystemClock.uptimeMillis(); 621 ActivityOptions options = null; 622 if (mStackId != FULLSCREEN_WORKSPACE_STACK_ID) { 623 options = ActivityOptions.makeBasic(); 624 options.setLaunchStackId(mStackId); 625 } 626 if (mWaitOption) { 627 result = mAm.startActivityAndWait(null, null, intent, mimeType, 628 null, null, 0, mStartFlags, profilerInfo, 629 options != null ? options.toBundle() : null, mUserId); 630 res = result.result; 631 } else { 632 res = mAm.startActivityAsUser(null, null, intent, mimeType, 633 null, null, 0, mStartFlags, profilerInfo, 634 options != null ? options.toBundle() : null, mUserId); 635 } 636 final long endTime = SystemClock.uptimeMillis(); 637 PrintStream out = mWaitOption ? System.out : System.err; 638 boolean launched = false; 639 switch (res) { 640 case ActivityManager.START_SUCCESS: 641 launched = true; 642 break; 643 case ActivityManager.START_SWITCHES_CANCELED: 644 launched = true; 645 out.println( 646 "Warning: Activity not started because the " 647 + " current activity is being kept for the user."); 648 break; 649 case ActivityManager.START_DELIVERED_TO_TOP: 650 launched = true; 651 out.println( 652 "Warning: Activity not started, intent has " 653 + "been delivered to currently running " 654 + "top-most instance."); 655 break; 656 case ActivityManager.START_RETURN_INTENT_TO_CALLER: 657 launched = true; 658 out.println( 659 "Warning: Activity not started because intent " 660 + "should be handled by the caller"); 661 break; 662 case ActivityManager.START_TASK_TO_FRONT: 663 launched = true; 664 out.println( 665 "Warning: Activity not started, its current " 666 + "task has been brought to the front"); 667 break; 668 case ActivityManager.START_INTENT_NOT_RESOLVED: 669 out.println( 670 "Error: Activity not started, unable to " 671 + "resolve " + intent.toString()); 672 break; 673 case ActivityManager.START_CLASS_NOT_FOUND: 674 out.println(NO_CLASS_ERROR_CODE); 675 out.println("Error: Activity class " + 676 intent.getComponent().toShortString() 677 + " does not exist."); 678 break; 679 case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT: 680 out.println( 681 "Error: Activity not started, you requested to " 682 + "both forward and receive its result"); 683 break; 684 case ActivityManager.START_PERMISSION_DENIED: 685 out.println( 686 "Error: Activity not started, you do not " 687 + "have permission to access it."); 688 break; 689 case ActivityManager.START_NOT_VOICE_COMPATIBLE: 690 out.println( 691 "Error: Activity not started, voice control not allowed for: " 692 + intent); 693 break; 694 case ActivityManager.START_NOT_CURRENT_USER_ACTIVITY: 695 out.println( 696 "Error: Not allowed to start background user activity" 697 + " that shouldn't be displayed for all users."); 698 break; 699 default: 700 out.println( 701 "Error: Activity not started, unknown error code " + res); 702 break; 703 } 704 if (mWaitOption && launched) { 705 if (result == null) { 706 result = new IActivityManager.WaitResult(); 707 result.who = intent.getComponent(); 708 } 709 System.out.println("Status: " + (result.timeout ? "timeout" : "ok")); 710 if (result.who != null) { 711 System.out.println("Activity: " + result.who.flattenToShortString()); 712 } 713 if (result.thisTime >= 0) { 714 System.out.println("ThisTime: " + result.thisTime); 715 } 716 if (result.totalTime >= 0) { 717 System.out.println("TotalTime: " + result.totalTime); 718 } 719 System.out.println("WaitTime: " + (endTime-startTime)); 720 System.out.println("Complete"); 721 } 722 mRepeat--; 723 if (mRepeat > 1) { 724 mAm.unhandledBack(); 725 } 726 } while (mRepeat > 1); 727 } 728 729 private void runForceStop() throws Exception { 730 int userId = UserHandle.USER_ALL; 731 732 String opt; 733 while ((opt=nextOption()) != null) { 734 if (opt.equals("--user")) { 735 userId = parseUserArg(nextArgRequired()); 736 } else { 737 System.err.println("Error: Unknown option: " + opt); 738 return; 739 } 740 } 741 mAm.forceStopPackage(nextArgRequired(), userId); 742 } 743 744 private void runKill() throws Exception { 745 int userId = UserHandle.USER_ALL; 746 747 String opt; 748 while ((opt=nextOption()) != null) { 749 if (opt.equals("--user")) { 750 userId = parseUserArg(nextArgRequired()); 751 } else { 752 System.err.println("Error: Unknown option: " + opt); 753 return; 754 } 755 } 756 mAm.killBackgroundProcesses(nextArgRequired(), userId); 757 } 758 759 private void runKillAll() throws Exception { 760 mAm.killAllBackgroundProcesses(); 761 } 762 763 private void sendBroadcast() throws Exception { 764 Intent intent = makeIntent(UserHandle.USER_CURRENT); 765 IntentReceiver receiver = new IntentReceiver(); 766 String[] requiredPermissions = mReceiverPermission == null ? null 767 : new String[] {mReceiverPermission}; 768 System.out.println("Broadcasting: " + intent); 769 mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, requiredPermissions, 770 android.app.AppOpsManager.OP_NONE, null, true, false, mUserId); 771 receiver.waitForFinish(); 772 } 773 774 private void runInstrument() throws Exception { 775 String profileFile = null; 776 boolean wait = false; 777 boolean rawMode = false; 778 boolean no_window_animation = false; 779 int userId = UserHandle.USER_CURRENT; 780 Bundle args = new Bundle(); 781 String argKey = null, argValue = null; 782 IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window")); 783 String abi = null; 784 785 String opt; 786 while ((opt=nextOption()) != null) { 787 if (opt.equals("-p")) { 788 profileFile = nextArgRequired(); 789 } else if (opt.equals("-w")) { 790 wait = true; 791 } else if (opt.equals("-r")) { 792 rawMode = true; 793 } else if (opt.equals("-e")) { 794 argKey = nextArgRequired(); 795 argValue = nextArgRequired(); 796 args.putString(argKey, argValue); 797 } else if (opt.equals("--no_window_animation") 798 || opt.equals("--no-window-animation")) { 799 no_window_animation = true; 800 } else if (opt.equals("--user")) { 801 userId = parseUserArg(nextArgRequired()); 802 } else if (opt.equals("--abi")) { 803 abi = nextArgRequired(); 804 } else { 805 System.err.println("Error: Unknown option: " + opt); 806 return; 807 } 808 } 809 810 if (userId == UserHandle.USER_ALL) { 811 System.err.println("Error: Can't start instrumentation with user 'all'"); 812 return; 813 } 814 815 String cnArg = nextArgRequired(); 816 ComponentName cn = ComponentName.unflattenFromString(cnArg); 817 if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg); 818 819 InstrumentationWatcher watcher = null; 820 UiAutomationConnection connection = null; 821 if (wait) { 822 watcher = new InstrumentationWatcher(); 823 watcher.setRawOutput(rawMode); 824 connection = new UiAutomationConnection(); 825 } 826 827 float[] oldAnims = null; 828 if (no_window_animation) { 829 oldAnims = wm.getAnimationScales(); 830 wm.setAnimationScale(0, 0.0f); 831 wm.setAnimationScale(1, 0.0f); 832 } 833 834 if (abi != null) { 835 final String[] supportedAbis = Build.SUPPORTED_ABIS; 836 boolean matched = false; 837 for (String supportedAbi : supportedAbis) { 838 if (supportedAbi.equals(abi)) { 839 matched = true; 840 break; 841 } 842 } 843 844 if (!matched) { 845 throw new AndroidException( 846 "INSTRUMENTATION_FAILED: Unsupported instruction set " + abi); 847 } 848 } 849 850 if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher, connection, userId, abi)) { 851 throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString()); 852 } 853 854 if (watcher != null) { 855 if (!watcher.waitForFinish()) { 856 System.out.println("INSTRUMENTATION_ABORTED: System has crashed."); 857 } 858 } 859 860 if (oldAnims != null) { 861 wm.setAnimationScales(oldAnims); 862 } 863 } 864 865 private void runTraceIpc() throws Exception { 866 String op = nextArgRequired(); 867 if (op.equals("start")) { 868 runTraceIpcStart(); 869 } else if (op.equals("stop")) { 870 runTraceIpcStop(); 871 } else { 872 showError("Error: unknown command '" + op + "'"); 873 return; 874 } 875 } 876 877 private void runTraceIpcStart() throws Exception { 878 System.out.println("Starting IPC tracing."); 879 mAm.startBinderTracking(); 880 } 881 882 private void runTraceIpcStop() throws Exception { 883 String opt; 884 String filename = null; 885 while ((opt=nextOption()) != null) { 886 if (opt.equals("--dump-file")) { 887 filename = nextArgRequired(); 888 } else { 889 System.err.println("Error: Unknown option: " + opt); 890 return; 891 } 892 } 893 if (filename == null) { 894 System.err.println("Error: Specify filename to dump logs to."); 895 return; 896 } 897 898 ParcelFileDescriptor fd = null; 899 900 try { 901 File file = new File(filename); 902 file.delete(); 903 fd = openForSystemServer(file, 904 ParcelFileDescriptor.MODE_CREATE | 905 ParcelFileDescriptor.MODE_TRUNCATE | 906 ParcelFileDescriptor.MODE_READ_WRITE); 907 } catch (FileNotFoundException e) { 908 System.err.println("Error: Unable to open file: " + filename); 909 System.err.println("Consider using a file under /data/local/tmp/"); 910 return; 911 } 912 913 ; 914 if (!mAm.stopBinderTrackingAndDump(fd)) { 915 throw new AndroidException("STOP TRACE FAILED."); 916 } 917 918 System.out.println("Stopped IPC tracing. Dumping logs to: " + filename); 919 } 920 921 static void removeWallOption() { 922 String props = SystemProperties.get("dalvik.vm.extra-opts"); 923 if (props != null && props.contains("-Xprofile:wallclock")) { 924 props = props.replace("-Xprofile:wallclock", ""); 925 props = props.trim(); 926 SystemProperties.set("dalvik.vm.extra-opts", props); 927 } 928 } 929 930 private void runProfile() throws Exception { 931 String profileFile = null; 932 boolean start = false; 933 boolean wall = false; 934 int userId = UserHandle.USER_CURRENT; 935 int profileType = 0; 936 mSamplingInterval = 0; 937 938 String process = null; 939 940 String cmd = nextArgRequired(); 941 942 if ("start".equals(cmd)) { 943 start = true; 944 String opt; 945 while ((opt=nextOption()) != null) { 946 if (opt.equals("--user")) { 947 userId = parseUserArg(nextArgRequired()); 948 } else if (opt.equals("--wall")) { 949 wall = true; 950 } else if (opt.equals("--sampling")) { 951 mSamplingInterval = Integer.parseInt(nextArgRequired()); 952 } else { 953 System.err.println("Error: Unknown option: " + opt); 954 return; 955 } 956 } 957 process = nextArgRequired(); 958 } else if ("stop".equals(cmd)) { 959 String opt; 960 while ((opt=nextOption()) != null) { 961 if (opt.equals("--user")) { 962 userId = parseUserArg(nextArgRequired()); 963 } else { 964 System.err.println("Error: Unknown option: " + opt); 965 return; 966 } 967 } 968 process = nextArg(); 969 } else { 970 // Compatibility with old syntax: process is specified first. 971 process = cmd; 972 cmd = nextArgRequired(); 973 if ("start".equals(cmd)) { 974 start = true; 975 } else if (!"stop".equals(cmd)) { 976 throw new IllegalArgumentException("Profile command " + process + " not valid"); 977 } 978 } 979 980 if (userId == UserHandle.USER_ALL) { 981 System.err.println("Error: Can't profile with user 'all'"); 982 return; 983 } 984 985 ParcelFileDescriptor fd = null; 986 ProfilerInfo profilerInfo = null; 987 988 if (start) { 989 profileFile = nextArgRequired(); 990 try { 991 fd = openForSystemServer( 992 new File(profileFile), 993 ParcelFileDescriptor.MODE_CREATE | 994 ParcelFileDescriptor.MODE_TRUNCATE | 995 ParcelFileDescriptor.MODE_READ_WRITE); 996 } catch (FileNotFoundException e) { 997 System.err.println("Error: Unable to open file: " + profileFile); 998 System.err.println("Consider using a file under /data/local/tmp/"); 999 return; 1000 } 1001 profilerInfo = new ProfilerInfo(profileFile, fd, mSamplingInterval, false); 1002 } 1003 1004 try { 1005 if (wall) { 1006 // XXX doesn't work -- this needs to be set before booting. 1007 String props = SystemProperties.get("dalvik.vm.extra-opts"); 1008 if (props == null || !props.contains("-Xprofile:wallclock")) { 1009 props = props + " -Xprofile:wallclock"; 1010 //SystemProperties.set("dalvik.vm.extra-opts", props); 1011 } 1012 } else if (start) { 1013 //removeWallOption(); 1014 } 1015 if (!mAm.profileControl(process, userId, start, profilerInfo, profileType)) { 1016 wall = false; 1017 throw new AndroidException("PROFILE FAILED on process " + process); 1018 } 1019 } finally { 1020 if (!wall) { 1021 //removeWallOption(); 1022 } 1023 } 1024 } 1025 1026 private void runDumpHeap() throws Exception { 1027 boolean managed = true; 1028 int userId = UserHandle.USER_CURRENT; 1029 1030 String opt; 1031 while ((opt=nextOption()) != null) { 1032 if (opt.equals("--user")) { 1033 userId = parseUserArg(nextArgRequired()); 1034 if (userId == UserHandle.USER_ALL) { 1035 System.err.println("Error: Can't dump heap with user 'all'"); 1036 return; 1037 } 1038 } else if (opt.equals("-n")) { 1039 managed = false; 1040 } else { 1041 System.err.println("Error: Unknown option: " + opt); 1042 return; 1043 } 1044 } 1045 String process = nextArgRequired(); 1046 String heapFile = nextArgRequired(); 1047 ParcelFileDescriptor fd = null; 1048 1049 try { 1050 File file = new File(heapFile); 1051 file.delete(); 1052 fd = openForSystemServer(file, 1053 ParcelFileDescriptor.MODE_CREATE | 1054 ParcelFileDescriptor.MODE_TRUNCATE | 1055 ParcelFileDescriptor.MODE_READ_WRITE); 1056 } catch (FileNotFoundException e) { 1057 System.err.println("Error: Unable to open file: " + heapFile); 1058 System.err.println("Consider using a file under /data/local/tmp/"); 1059 return; 1060 } 1061 1062 if (!mAm.dumpHeap(process, userId, managed, heapFile, fd)) { 1063 throw new AndroidException("HEAP DUMP FAILED on process " + process); 1064 } 1065 } 1066 1067 private void runSetDebugApp() throws Exception { 1068 boolean wait = false; 1069 boolean persistent = false; 1070 1071 String opt; 1072 while ((opt=nextOption()) != null) { 1073 if (opt.equals("-w")) { 1074 wait = true; 1075 } else if (opt.equals("--persistent")) { 1076 persistent = true; 1077 } else { 1078 System.err.println("Error: Unknown option: " + opt); 1079 return; 1080 } 1081 } 1082 1083 String pkg = nextArgRequired(); 1084 mAm.setDebugApp(pkg, wait, persistent); 1085 } 1086 1087 private void runClearDebugApp() throws Exception { 1088 mAm.setDebugApp(null, false, true); 1089 } 1090 1091 private void runSetWatchHeap() throws Exception { 1092 String proc = nextArgRequired(); 1093 String limit = nextArgRequired(); 1094 mAm.setDumpHeapDebugLimit(proc, 0, Long.parseLong(limit), null); 1095 } 1096 1097 private void runClearWatchHeap() throws Exception { 1098 String proc = nextArgRequired(); 1099 mAm.setDumpHeapDebugLimit(proc, 0, -1, null); 1100 } 1101 1102 private void runBugReport() throws Exception { 1103 String opt; 1104 int bugreportType = ActivityManager.BUGREPORT_OPTION_FULL; 1105 while ((opt=nextOption()) != null) { 1106 if (opt.equals("--progress")) { 1107 bugreportType = ActivityManager.BUGREPORT_OPTION_INTERACTIVE; 1108 } else { 1109 System.err.println("Error: Unknown option: " + opt); 1110 return; 1111 } 1112 } 1113 mAm.requestBugReport(bugreportType); 1114 System.out.println("Your lovely bug report is being created; please be patient."); 1115 } 1116 1117 private void runSwitchUser() throws Exception { 1118 String user = nextArgRequired(); 1119 mAm.switchUser(Integer.parseInt(user)); 1120 } 1121 1122 private void runStartUserInBackground() throws Exception { 1123 String user = nextArgRequired(); 1124 boolean success = mAm.startUserInBackground(Integer.parseInt(user)); 1125 if (success) { 1126 System.out.println("Success: user started"); 1127 } else { 1128 System.err.println("Error: could not start user"); 1129 } 1130 } 1131 1132 private byte[] argToBytes(String arg) { 1133 if (arg.equals("!")) { 1134 return null; 1135 } else { 1136 return HexDump.hexStringToByteArray(arg); 1137 } 1138 } 1139 1140 private void runUnlockUser() throws Exception { 1141 int userId = Integer.parseInt(nextArgRequired()); 1142 byte[] token = argToBytes(nextArgRequired()); 1143 byte[] secret = argToBytes(nextArgRequired()); 1144 boolean success = mAm.unlockUser(userId, token, secret); 1145 if (success) { 1146 System.out.println("Success: user unlocked"); 1147 } else { 1148 System.err.println("Error: could not unlock user"); 1149 } 1150 } 1151 1152 private static class StopUserCallback extends IStopUserCallback.Stub { 1153 private boolean mFinished = false; 1154 1155 public synchronized void waitForFinish() { 1156 try { 1157 while (!mFinished) wait(); 1158 } catch (InterruptedException e) { 1159 throw new IllegalStateException(e); 1160 } 1161 } 1162 1163 @Override 1164 public synchronized void userStopped(int userId) { 1165 mFinished = true; 1166 notifyAll(); 1167 } 1168 1169 @Override 1170 public synchronized void userStopAborted(int userId) { 1171 mFinished = true; 1172 notifyAll(); 1173 } 1174 } 1175 1176 private void runStopUser() throws Exception { 1177 boolean wait = false; 1178 boolean force = false; 1179 String opt; 1180 while ((opt = nextOption()) != null) { 1181 if ("-w".equals(opt)) { 1182 wait = true; 1183 } else if ("-f".equals(opt)) { 1184 force = true; 1185 } else { 1186 System.err.println("Error: unknown option: " + opt); 1187 return; 1188 } 1189 } 1190 int user = Integer.parseInt(nextArgRequired()); 1191 StopUserCallback callback = wait ? new StopUserCallback() : null; 1192 1193 int res = mAm.stopUser(user, force, callback); 1194 if (res != ActivityManager.USER_OP_SUCCESS) { 1195 String txt = ""; 1196 switch (res) { 1197 case ActivityManager.USER_OP_IS_CURRENT: 1198 txt = " (Can't stop current user)"; 1199 break; 1200 case ActivityManager.USER_OP_UNKNOWN_USER: 1201 txt = " (Unknown user " + user + ")"; 1202 break; 1203 case ActivityManager.USER_OP_ERROR_IS_SYSTEM: 1204 txt = " (System user cannot be stopped)"; 1205 break; 1206 case ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP: 1207 txt = " (Can't stop user " + user 1208 + " - one of its related users can't be stopped)"; 1209 break; 1210 } 1211 System.err.println("Switch failed: " + res + txt); 1212 } else if (callback != null) { 1213 callback.waitForFinish(); 1214 } 1215 } 1216 1217 class MyActivityController extends IActivityController.Stub { 1218 final String mGdbPort; 1219 1220 static final int STATE_NORMAL = 0; 1221 static final int STATE_CRASHED = 1; 1222 static final int STATE_EARLY_ANR = 2; 1223 static final int STATE_ANR = 3; 1224 1225 int mState; 1226 1227 static final int RESULT_DEFAULT = 0; 1228 1229 static final int RESULT_CRASH_DIALOG = 0; 1230 static final int RESULT_CRASH_KILL = 1; 1231 1232 static final int RESULT_EARLY_ANR_CONTINUE = 0; 1233 static final int RESULT_EARLY_ANR_KILL = 1; 1234 1235 static final int RESULT_ANR_DIALOG = 0; 1236 static final int RESULT_ANR_KILL = 1; 1237 static final int RESULT_ANR_WAIT = 1; 1238 1239 int mResult; 1240 1241 Process mGdbProcess; 1242 Thread mGdbThread; 1243 boolean mGotGdbPrint; 1244 1245 MyActivityController(String gdbPort) { 1246 mGdbPort = gdbPort; 1247 } 1248 1249 @Override 1250 public boolean activityResuming(String pkg) { 1251 synchronized (this) { 1252 System.out.println("** Activity resuming: " + pkg); 1253 } 1254 return true; 1255 } 1256 1257 @Override 1258 public boolean activityStarting(Intent intent, String pkg) { 1259 synchronized (this) { 1260 System.out.println("** Activity starting: " + pkg); 1261 } 1262 return true; 1263 } 1264 1265 @Override 1266 public boolean appCrashed(String processName, int pid, String shortMsg, String longMsg, 1267 long timeMillis, String stackTrace) { 1268 synchronized (this) { 1269 System.out.println("** ERROR: PROCESS CRASHED"); 1270 System.out.println("processName: " + processName); 1271 System.out.println("processPid: " + pid); 1272 System.out.println("shortMsg: " + shortMsg); 1273 System.out.println("longMsg: " + longMsg); 1274 System.out.println("timeMillis: " + timeMillis); 1275 System.out.println("stack:"); 1276 System.out.print(stackTrace); 1277 System.out.println("#"); 1278 int result = waitControllerLocked(pid, STATE_CRASHED); 1279 return result == RESULT_CRASH_KILL ? false : true; 1280 } 1281 } 1282 1283 @Override 1284 public int appEarlyNotResponding(String processName, int pid, String annotation) { 1285 synchronized (this) { 1286 System.out.println("** ERROR: EARLY PROCESS NOT RESPONDING"); 1287 System.out.println("processName: " + processName); 1288 System.out.println("processPid: " + pid); 1289 System.out.println("annotation: " + annotation); 1290 int result = waitControllerLocked(pid, STATE_EARLY_ANR); 1291 if (result == RESULT_EARLY_ANR_KILL) return -1; 1292 return 0; 1293 } 1294 } 1295 1296 @Override 1297 public int appNotResponding(String processName, int pid, String processStats) { 1298 synchronized (this) { 1299 System.out.println("** ERROR: PROCESS NOT RESPONDING"); 1300 System.out.println("processName: " + processName); 1301 System.out.println("processPid: " + pid); 1302 System.out.println("processStats:"); 1303 System.out.print(processStats); 1304 System.out.println("#"); 1305 int result = waitControllerLocked(pid, STATE_ANR); 1306 if (result == RESULT_ANR_KILL) return -1; 1307 if (result == RESULT_ANR_WAIT) return 1; 1308 return 0; 1309 } 1310 } 1311 1312 @Override 1313 public int systemNotResponding(String message) { 1314 synchronized (this) { 1315 System.out.println("** ERROR: PROCESS NOT RESPONDING"); 1316 System.out.println("message: " + message); 1317 System.out.println("#"); 1318 System.out.println("Allowing system to die."); 1319 return -1; 1320 } 1321 } 1322 1323 void killGdbLocked() { 1324 mGotGdbPrint = false; 1325 if (mGdbProcess != null) { 1326 System.out.println("Stopping gdbserver"); 1327 mGdbProcess.destroy(); 1328 mGdbProcess = null; 1329 } 1330 if (mGdbThread != null) { 1331 mGdbThread.interrupt(); 1332 mGdbThread = null; 1333 } 1334 } 1335 1336 int waitControllerLocked(int pid, int state) { 1337 if (mGdbPort != null) { 1338 killGdbLocked(); 1339 1340 try { 1341 System.out.println("Starting gdbserver on port " + mGdbPort); 1342 System.out.println("Do the following:"); 1343 System.out.println(" adb forward tcp:" + mGdbPort + " tcp:" + mGdbPort); 1344 System.out.println(" gdbclient app_process :" + mGdbPort); 1345 1346 mGdbProcess = Runtime.getRuntime().exec(new String[] { 1347 "gdbserver", ":" + mGdbPort, "--attach", Integer.toString(pid) 1348 }); 1349 final InputStreamReader converter = new InputStreamReader( 1350 mGdbProcess.getInputStream()); 1351 mGdbThread = new Thread() { 1352 @Override 1353 public void run() { 1354 BufferedReader in = new BufferedReader(converter); 1355 String line; 1356 int count = 0; 1357 while (true) { 1358 synchronized (MyActivityController.this) { 1359 if (mGdbThread == null) { 1360 return; 1361 } 1362 if (count == 2) { 1363 mGotGdbPrint = true; 1364 MyActivityController.this.notifyAll(); 1365 } 1366 } 1367 try { 1368 line = in.readLine(); 1369 if (line == null) { 1370 return; 1371 } 1372 System.out.println("GDB: " + line); 1373 count++; 1374 } catch (IOException e) { 1375 return; 1376 } 1377 } 1378 } 1379 }; 1380 mGdbThread.start(); 1381 1382 // Stupid waiting for .5s. Doesn't matter if we end early. 1383 try { 1384 this.wait(500); 1385 } catch (InterruptedException e) { 1386 } 1387 1388 } catch (IOException e) { 1389 System.err.println("Failure starting gdbserver: " + e); 1390 killGdbLocked(); 1391 } 1392 } 1393 mState = state; 1394 System.out.println(""); 1395 printMessageForState(); 1396 1397 while (mState != STATE_NORMAL) { 1398 try { 1399 wait(); 1400 } catch (InterruptedException e) { 1401 } 1402 } 1403 1404 killGdbLocked(); 1405 1406 return mResult; 1407 } 1408 1409 void resumeController(int result) { 1410 synchronized (this) { 1411 mState = STATE_NORMAL; 1412 mResult = result; 1413 notifyAll(); 1414 } 1415 } 1416 1417 void printMessageForState() { 1418 switch (mState) { 1419 case STATE_NORMAL: 1420 System.out.println("Monitoring activity manager... available commands:"); 1421 break; 1422 case STATE_CRASHED: 1423 System.out.println("Waiting after crash... available commands:"); 1424 System.out.println("(c)ontinue: show crash dialog"); 1425 System.out.println("(k)ill: immediately kill app"); 1426 break; 1427 case STATE_EARLY_ANR: 1428 System.out.println("Waiting after early ANR... available commands:"); 1429 System.out.println("(c)ontinue: standard ANR processing"); 1430 System.out.println("(k)ill: immediately kill app"); 1431 break; 1432 case STATE_ANR: 1433 System.out.println("Waiting after ANR... available commands:"); 1434 System.out.println("(c)ontinue: show ANR dialog"); 1435 System.out.println("(k)ill: immediately kill app"); 1436 System.out.println("(w)ait: wait some more"); 1437 break; 1438 } 1439 System.out.println("(q)uit: finish monitoring"); 1440 } 1441 1442 void run() throws RemoteException { 1443 try { 1444 printMessageForState(); 1445 1446 mAm.setActivityController(this); 1447 mState = STATE_NORMAL; 1448 1449 InputStreamReader converter = new InputStreamReader(System.in); 1450 BufferedReader in = new BufferedReader(converter); 1451 String line; 1452 1453 while ((line = in.readLine()) != null) { 1454 boolean addNewline = true; 1455 if (line.length() <= 0) { 1456 addNewline = false; 1457 } else if ("q".equals(line) || "quit".equals(line)) { 1458 resumeController(RESULT_DEFAULT); 1459 break; 1460 } else if (mState == STATE_CRASHED) { 1461 if ("c".equals(line) || "continue".equals(line)) { 1462 resumeController(RESULT_CRASH_DIALOG); 1463 } else if ("k".equals(line) || "kill".equals(line)) { 1464 resumeController(RESULT_CRASH_KILL); 1465 } else { 1466 System.out.println("Invalid command: " + line); 1467 } 1468 } else if (mState == STATE_ANR) { 1469 if ("c".equals(line) || "continue".equals(line)) { 1470 resumeController(RESULT_ANR_DIALOG); 1471 } else if ("k".equals(line) || "kill".equals(line)) { 1472 resumeController(RESULT_ANR_KILL); 1473 } else if ("w".equals(line) || "wait".equals(line)) { 1474 resumeController(RESULT_ANR_WAIT); 1475 } else { 1476 System.out.println("Invalid command: " + line); 1477 } 1478 } else if (mState == STATE_EARLY_ANR) { 1479 if ("c".equals(line) || "continue".equals(line)) { 1480 resumeController(RESULT_EARLY_ANR_CONTINUE); 1481 } else if ("k".equals(line) || "kill".equals(line)) { 1482 resumeController(RESULT_EARLY_ANR_KILL); 1483 } else { 1484 System.out.println("Invalid command: " + line); 1485 } 1486 } else { 1487 System.out.println("Invalid command: " + line); 1488 } 1489 1490 synchronized (this) { 1491 if (addNewline) { 1492 System.out.println(""); 1493 } 1494 printMessageForState(); 1495 } 1496 } 1497 1498 } catch (IOException e) { 1499 e.printStackTrace(); 1500 } finally { 1501 mAm.setActivityController(null); 1502 } 1503 } 1504 } 1505 1506 private void runMonitor() throws Exception { 1507 String opt; 1508 String gdbPort = null; 1509 while ((opt=nextOption()) != null) { 1510 if (opt.equals("--gdb")) { 1511 gdbPort = nextArgRequired(); 1512 } else { 1513 System.err.println("Error: Unknown option: " + opt); 1514 return; 1515 } 1516 } 1517 1518 MyActivityController controller = new MyActivityController(gdbPort); 1519 controller.run(); 1520 } 1521 1522 private void runHang() throws Exception { 1523 String opt; 1524 boolean allowRestart = false; 1525 while ((opt=nextOption()) != null) { 1526 if (opt.equals("--allow-restart")) { 1527 allowRestart = true; 1528 } else { 1529 System.err.println("Error: Unknown option: " + opt); 1530 return; 1531 } 1532 } 1533 1534 System.out.println("Hanging the system..."); 1535 mAm.hang(new Binder(), allowRestart); 1536 } 1537 1538 private void runRestart() throws Exception { 1539 String opt; 1540 while ((opt=nextOption()) != null) { 1541 System.err.println("Error: Unknown option: " + opt); 1542 return; 1543 } 1544 1545 System.out.println("Restart the system..."); 1546 mAm.restart(); 1547 } 1548 1549 private void runIdleMaintenance() throws Exception { 1550 String opt; 1551 while ((opt=nextOption()) != null) { 1552 System.err.println("Error: Unknown option: " + opt); 1553 return; 1554 } 1555 1556 System.out.println("Performing idle maintenance..."); 1557 Intent intent = new Intent( 1558 "com.android.server.task.controllers.IdleController.ACTION_TRIGGER_IDLE"); 1559 mAm.broadcastIntent(null, intent, null, null, 0, null, null, null, 1560 android.app.AppOpsManager.OP_NONE, null, true, false, UserHandle.USER_ALL); 1561 } 1562 1563 private void runScreenCompat() throws Exception { 1564 String mode = nextArgRequired(); 1565 boolean enabled; 1566 if ("on".equals(mode)) { 1567 enabled = true; 1568 } else if ("off".equals(mode)) { 1569 enabled = false; 1570 } else { 1571 System.err.println("Error: enabled mode must be 'on' or 'off' at " + mode); 1572 return; 1573 } 1574 1575 String packageName = nextArgRequired(); 1576 do { 1577 try { 1578 mAm.setPackageScreenCompatMode(packageName, enabled 1579 ? ActivityManager.COMPAT_MODE_ENABLED 1580 : ActivityManager.COMPAT_MODE_DISABLED); 1581 } catch (RemoteException e) { 1582 } 1583 packageName = nextArg(); 1584 } while (packageName != null); 1585 } 1586 1587 private void runPackageImportance() throws Exception { 1588 String packageName = nextArgRequired(); 1589 try { 1590 int procState = mAm.getPackageProcessState(packageName, "com.android.shell"); 1591 System.out.println( 1592 ActivityManager.RunningAppProcessInfo.procStateToImportance(procState)); 1593 } catch (RemoteException e) { 1594 } 1595 } 1596 1597 private void runToUri(int flags) throws Exception { 1598 Intent intent = makeIntent(UserHandle.USER_CURRENT); 1599 System.out.println(intent.toUri(flags)); 1600 } 1601 1602 private class IntentReceiver extends IIntentReceiver.Stub { 1603 private boolean mFinished = false; 1604 1605 @Override 1606 public void performReceive(Intent intent, int resultCode, String data, Bundle extras, 1607 boolean ordered, boolean sticky, int sendingUser) { 1608 String line = "Broadcast completed: result=" + resultCode; 1609 if (data != null) line = line + ", data=\"" + data + "\""; 1610 if (extras != null) line = line + ", extras: " + extras; 1611 System.out.println(line); 1612 synchronized (this) { 1613 mFinished = true; 1614 notifyAll(); 1615 } 1616 } 1617 1618 public synchronized void waitForFinish() { 1619 try { 1620 while (!mFinished) wait(); 1621 } catch (InterruptedException e) { 1622 throw new IllegalStateException(e); 1623 } 1624 } 1625 } 1626 1627 private class InstrumentationWatcher extends IInstrumentationWatcher.Stub { 1628 private boolean mFinished = false; 1629 private boolean mRawMode = false; 1630 1631 /** 1632 * Set or reset "raw mode". In "raw mode", all bundles are dumped. In "pretty mode", 1633 * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that. 1634 * @param rawMode true for raw mode, false for pretty mode. 1635 */ 1636 public void setRawOutput(boolean rawMode) { 1637 mRawMode = rawMode; 1638 } 1639 1640 @Override 1641 public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) { 1642 synchronized (this) { 1643 // pretty printer mode? 1644 String pretty = null; 1645 if (!mRawMode && results != null) { 1646 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); 1647 } 1648 if (pretty != null) { 1649 System.out.print(pretty); 1650 } else { 1651 if (results != null) { 1652 for (String key : results.keySet()) { 1653 System.out.println( 1654 "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key)); 1655 } 1656 } 1657 System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode); 1658 } 1659 notifyAll(); 1660 } 1661 } 1662 1663 @Override 1664 public void instrumentationFinished(ComponentName name, int resultCode, 1665 Bundle results) { 1666 synchronized (this) { 1667 // pretty printer mode? 1668 String pretty = null; 1669 if (!mRawMode && results != null) { 1670 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); 1671 } 1672 if (pretty != null) { 1673 System.out.println(pretty); 1674 } else { 1675 if (results != null) { 1676 for (String key : results.keySet()) { 1677 System.out.println( 1678 "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key)); 1679 } 1680 } 1681 System.out.println("INSTRUMENTATION_CODE: " + resultCode); 1682 } 1683 mFinished = true; 1684 notifyAll(); 1685 } 1686 } 1687 1688 public boolean waitForFinish() { 1689 synchronized (this) { 1690 while (!mFinished) { 1691 try { 1692 if (!mAm.asBinder().pingBinder()) { 1693 return false; 1694 } 1695 wait(1000); 1696 } catch (InterruptedException e) { 1697 throw new IllegalStateException(e); 1698 } 1699 } 1700 } 1701 return true; 1702 } 1703 } 1704 1705 private void runStack() throws Exception { 1706 String op = nextArgRequired(); 1707 switch (op) { 1708 case "start": 1709 runStackStart(); 1710 break; 1711 case "movetask": 1712 runStackMoveTask(); 1713 break; 1714 case "resize": 1715 runStackResize(); 1716 break; 1717 case "resize-animated": 1718 runStackResizeAnimated(); 1719 break; 1720 case "resize-docked-stack": 1721 runStackResizeDocked(); 1722 break; 1723 case "positiontask": 1724 runStackPositionTask(); 1725 break; 1726 case "list": 1727 runStackList(); 1728 break; 1729 case "info": 1730 runStackInfo(); 1731 break; 1732 case "move-top-activity-to-pinned-stack": 1733 runMoveTopActivityToPinnedStack(); 1734 break; 1735 case "size-docked-stack-test": 1736 runStackSizeDockedStackTest(); 1737 break; 1738 case "remove": 1739 runStackRemove(); 1740 break; 1741 default: 1742 showError("Error: unknown command '" + op + "'"); 1743 break; 1744 } 1745 } 1746 1747 private void runStackStart() throws Exception { 1748 String displayIdStr = nextArgRequired(); 1749 int displayId = Integer.valueOf(displayIdStr); 1750 Intent intent = makeIntent(UserHandle.USER_CURRENT); 1751 1752 try { 1753 IActivityContainer container = mAm.createStackOnDisplay(displayId); 1754 if (container != null) { 1755 container.startActivity(intent); 1756 } 1757 } catch (RemoteException e) { 1758 } 1759 } 1760 1761 private void runStackMoveTask() throws Exception { 1762 String taskIdStr = nextArgRequired(); 1763 int taskId = Integer.valueOf(taskIdStr); 1764 String stackIdStr = nextArgRequired(); 1765 int stackId = Integer.valueOf(stackIdStr); 1766 String toTopStr = nextArgRequired(); 1767 final boolean toTop; 1768 if ("true".equals(toTopStr)) { 1769 toTop = true; 1770 } else if ("false".equals(toTopStr)) { 1771 toTop = false; 1772 } else { 1773 System.err.println("Error: bad toTop arg: " + toTopStr); 1774 return; 1775 } 1776 1777 try { 1778 mAm.moveTaskToStack(taskId, stackId, toTop); 1779 } catch (RemoteException e) { 1780 } 1781 } 1782 1783 private void runStackResize() throws Exception { 1784 String stackIdStr = nextArgRequired(); 1785 int stackId = Integer.valueOf(stackIdStr); 1786 final Rect bounds = getBounds(); 1787 if (bounds == null) { 1788 System.err.println("Error: invalid input bounds"); 1789 return; 1790 } 1791 resizeStack(stackId, bounds, 0); 1792 } 1793 1794 private void runStackResizeAnimated() throws Exception { 1795 String stackIdStr = nextArgRequired(); 1796 int stackId = Integer.valueOf(stackIdStr); 1797 final Rect bounds; 1798 if ("null".equals(mArgs.peekNextArg())) { 1799 bounds = null; 1800 } else { 1801 bounds = getBounds(); 1802 if (bounds == null) { 1803 System.err.println("Error: invalid input bounds"); 1804 return; 1805 } 1806 } 1807 resizeStackUnchecked(stackId, bounds, 0, true); 1808 } 1809 1810 private void resizeStackUnchecked(int stackId, Rect bounds, int delayMs, boolean animate) { 1811 try { 1812 mAm.resizeStack(stackId, bounds, false, false, animate); 1813 Thread.sleep(delayMs); 1814 } catch (RemoteException e) { 1815 showError("Error: resizing stack " + e); 1816 } catch (InterruptedException e) { 1817 } 1818 } 1819 1820 private void runStackResizeDocked() throws Exception { 1821 final Rect bounds = getBounds(); 1822 final Rect taskBounds = getBounds(); 1823 if (bounds == null || taskBounds == null) { 1824 System.err.println("Error: invalid input bounds"); 1825 return; 1826 } 1827 try { 1828 mAm.resizeDockedStack(bounds, taskBounds, null, null, null); 1829 } catch (RemoteException e) { 1830 showError("Error: resizing docked stack " + e); 1831 } 1832 } 1833 1834 private void resizeStack(int stackId, Rect bounds, int delayMs) 1835 throws Exception { 1836 if (bounds == null) { 1837 showError("Error: invalid input bounds"); 1838 return; 1839 } 1840 resizeStackUnchecked(stackId, bounds, delayMs, false); 1841 } 1842 1843 private void runStackPositionTask() throws Exception { 1844 String taskIdStr = nextArgRequired(); 1845 int taskId = Integer.valueOf(taskIdStr); 1846 String stackIdStr = nextArgRequired(); 1847 int stackId = Integer.valueOf(stackIdStr); 1848 String positionStr = nextArgRequired(); 1849 int position = Integer.valueOf(positionStr); 1850 1851 try { 1852 mAm.positionTaskInStack(taskId, stackId, position); 1853 } catch (RemoteException e) { 1854 } 1855 } 1856 1857 private void runStackList() throws Exception { 1858 try { 1859 List<StackInfo> stacks = mAm.getAllStackInfos(); 1860 for (StackInfo info : stacks) { 1861 System.out.println(info); 1862 } 1863 } catch (RemoteException e) { 1864 } 1865 } 1866 1867 private void runStackInfo() throws Exception { 1868 try { 1869 String stackIdStr = nextArgRequired(); 1870 int stackId = Integer.valueOf(stackIdStr); 1871 StackInfo info = mAm.getStackInfo(stackId); 1872 System.out.println(info); 1873 } catch (RemoteException e) { 1874 } 1875 } 1876 1877 private void runStackRemove() throws Exception { 1878 String stackIdStr = nextArgRequired(); 1879 int stackId = Integer.valueOf(stackIdStr); 1880 mAm.removeStack(stackId); 1881 } 1882 1883 private void runMoveTopActivityToPinnedStack() throws Exception { 1884 int stackId = Integer.valueOf(nextArgRequired()); 1885 final Rect bounds = getBounds(); 1886 if (bounds == null) { 1887 System.err.println("Error: invalid input bounds"); 1888 return; 1889 } 1890 1891 try { 1892 if (!mAm.moveTopActivityToPinnedStack(stackId, bounds)) { 1893 showError("Didn't move top activity to pinned stack."); 1894 } 1895 } catch (RemoteException e) { 1896 showError("Unable to move top activity: " + e); 1897 return; 1898 } 1899 } 1900 1901 private void runStackSizeDockedStackTest() throws Exception { 1902 final int stepSize = Integer.valueOf(nextArgRequired()); 1903 final String side = nextArgRequired(); 1904 final String delayStr = nextArg(); 1905 final int delayMs = (delayStr != null) ? Integer.valueOf(delayStr) : 0; 1906 1907 Rect bounds; 1908 try { 1909 StackInfo info = mAm.getStackInfo(DOCKED_STACK_ID); 1910 if (info == null) { 1911 showError("Docked stack doesn't exist"); 1912 return; 1913 } 1914 if (info.bounds == null) { 1915 showError("Docked stack doesn't have a bounds"); 1916 return; 1917 } 1918 bounds = info.bounds; 1919 } catch (RemoteException e) { 1920 showError("Unable to get docked stack info:" + e); 1921 return; 1922 } 1923 1924 final boolean horizontalGrowth = "l".equals(side) || "r".equals(side); 1925 final int changeSize = (horizontalGrowth ? bounds.width() : bounds.height()) / 2; 1926 int currentPoint; 1927 switch (side) { 1928 case "l": 1929 currentPoint = bounds.left; 1930 break; 1931 case "r": 1932 currentPoint = bounds.right; 1933 break; 1934 case "t": 1935 currentPoint = bounds.top; 1936 break; 1937 case "b": 1938 currentPoint = bounds.bottom; 1939 break; 1940 default: 1941 showError("Unknown growth side: " + side); 1942 return; 1943 } 1944 1945 final int startPoint = currentPoint; 1946 final int minPoint = currentPoint - changeSize; 1947 final int maxPoint = currentPoint + changeSize; 1948 1949 int maxChange; 1950 System.out.println("Shrinking docked stack side=" + side); 1951 while (currentPoint > minPoint) { 1952 maxChange = Math.min(stepSize, currentPoint - minPoint); 1953 currentPoint -= maxChange; 1954 setBoundsSide(bounds, side, currentPoint); 1955 resizeStack(DOCKED_STACK_ID, bounds, delayMs); 1956 } 1957 1958 System.out.println("Growing docked stack side=" + side); 1959 while (currentPoint < maxPoint) { 1960 maxChange = Math.min(stepSize, maxPoint - currentPoint); 1961 currentPoint += maxChange; 1962 setBoundsSide(bounds, side, currentPoint); 1963 resizeStack(DOCKED_STACK_ID, bounds, delayMs); 1964 } 1965 1966 System.out.println("Back to Original size side=" + side); 1967 while (currentPoint > startPoint) { 1968 maxChange = Math.min(stepSize, currentPoint - startPoint); 1969 currentPoint -= maxChange; 1970 setBoundsSide(bounds, side, currentPoint); 1971 resizeStack(DOCKED_STACK_ID, bounds, delayMs); 1972 } 1973 } 1974 1975 private void setBoundsSide(Rect bounds, String side, int value) { 1976 switch (side) { 1977 case "l": 1978 bounds.left = value; 1979 break; 1980 case "r": 1981 bounds.right = value; 1982 break; 1983 case "t": 1984 bounds.top = value; 1985 break; 1986 case "b": 1987 bounds.bottom = value; 1988 break; 1989 default: 1990 showError("Unknown set side: " + side); 1991 break; 1992 } 1993 } 1994 1995 private void runTask() throws Exception { 1996 String op = nextArgRequired(); 1997 if (op.equals("lock")) { 1998 runTaskLock(); 1999 } else if (op.equals("resizeable")) { 2000 runTaskResizeable(); 2001 } else if (op.equals("resize")) { 2002 runTaskResize(); 2003 } else if (op.equals("drag-task-test")) { 2004 runTaskDragTaskTest(); 2005 } else if (op.equals("size-task-test")) { 2006 runTaskSizeTaskTest(); 2007 } else { 2008 showError("Error: unknown command '" + op + "'"); 2009 return; 2010 } 2011 } 2012 2013 private void runTaskLock() throws Exception { 2014 String taskIdStr = nextArgRequired(); 2015 try { 2016 if (taskIdStr.equals("stop")) { 2017 mAm.stopLockTaskMode(); 2018 } else { 2019 int taskId = Integer.valueOf(taskIdStr); 2020 mAm.startLockTaskMode(taskId); 2021 } 2022 System.err.println("Activity manager is " + (mAm.isInLockTaskMode() ? "" : "not ") + 2023 "in lockTaskMode"); 2024 } catch (RemoteException e) { 2025 } 2026 } 2027 2028 private void runTaskResizeable() throws Exception { 2029 final String taskIdStr = nextArgRequired(); 2030 final int taskId = Integer.valueOf(taskIdStr); 2031 final String resizeableStr = nextArgRequired(); 2032 final int resizeableMode = Integer.valueOf(resizeableStr); 2033 2034 try { 2035 mAm.setTaskResizeable(taskId, resizeableMode); 2036 } catch (RemoteException e) { 2037 } 2038 } 2039 2040 private void runTaskResize() throws Exception { 2041 final String taskIdStr = nextArgRequired(); 2042 final int taskId = Integer.valueOf(taskIdStr); 2043 final Rect bounds = getBounds(); 2044 if (bounds == null) { 2045 System.err.println("Error: invalid input bounds"); 2046 return; 2047 } 2048 taskResize(taskId, bounds, 0, false); 2049 } 2050 2051 private void taskResize(int taskId, Rect bounds, int delay_ms, boolean pretendUserResize) { 2052 try { 2053 final int resizeMode = pretendUserResize ? RESIZE_MODE_USER : RESIZE_MODE_SYSTEM; 2054 mAm.resizeTask(taskId, bounds, resizeMode); 2055 Thread.sleep(delay_ms); 2056 } catch (RemoteException e) { 2057 System.err.println("Error changing task bounds: " + e); 2058 } catch (InterruptedException e) { 2059 } 2060 } 2061 2062 private void runTaskDragTaskTest() { 2063 final int taskId = Integer.valueOf(nextArgRequired()); 2064 final int stepSize = Integer.valueOf(nextArgRequired()); 2065 final String delayStr = nextArg(); 2066 final int delay_ms = (delayStr != null) ? Integer.valueOf(delayStr) : 0; 2067 final StackInfo stackInfo; 2068 Rect taskBounds; 2069 try { 2070 stackInfo = mAm.getStackInfo(mAm.getFocusedStackId()); 2071 taskBounds = mAm.getTaskBounds(taskId); 2072 } catch (RemoteException e) { 2073 System.err.println("Error getting focus stack info or task bounds: " + e); 2074 return; 2075 } 2076 final Rect stackBounds = stackInfo.bounds; 2077 int travelRight = stackBounds.width() - taskBounds.width(); 2078 int travelLeft = -travelRight; 2079 int travelDown = stackBounds.height() - taskBounds.height(); 2080 int travelUp = -travelDown; 2081 int passes = 0; 2082 2083 // We do 2 passes to get back to the original location of the task. 2084 while (passes < 2) { 2085 // Move right 2086 System.out.println("Moving right..."); 2087 travelRight = moveTask(taskId, taskBounds, stackBounds, stepSize, 2088 travelRight, MOVING_FORWARD, MOVING_HORIZONTALLY, delay_ms); 2089 System.out.println("Still need to travel right by " + travelRight); 2090 2091 // Move down 2092 System.out.println("Moving down..."); 2093 travelDown = moveTask(taskId, taskBounds, stackBounds, stepSize, 2094 travelDown, MOVING_FORWARD, !MOVING_HORIZONTALLY, delay_ms); 2095 System.out.println("Still need to travel down by " + travelDown); 2096 2097 // Move left 2098 System.out.println("Moving left..."); 2099 travelLeft = moveTask(taskId, taskBounds, stackBounds, stepSize, 2100 travelLeft, !MOVING_FORWARD, MOVING_HORIZONTALLY, delay_ms); 2101 System.out.println("Still need to travel left by " + travelLeft); 2102 2103 // Move up 2104 System.out.println("Moving up..."); 2105 travelUp = moveTask(taskId, taskBounds, stackBounds, stepSize, 2106 travelUp, !MOVING_FORWARD, !MOVING_HORIZONTALLY, delay_ms); 2107 System.out.println("Still need to travel up by " + travelUp); 2108 2109 try { 2110 taskBounds = mAm.getTaskBounds(taskId); 2111 } catch (RemoteException e) { 2112 System.err.println("Error getting task bounds: " + e); 2113 return; 2114 } 2115 passes++; 2116 } 2117 } 2118 2119 private int moveTask(int taskId, Rect taskRect, Rect stackRect, int stepSize, 2120 int maxToTravel, boolean movingForward, boolean horizontal, int delay_ms) { 2121 int maxMove; 2122 if (movingForward) { 2123 while (maxToTravel > 0 2124 && ((horizontal && taskRect.right < stackRect.right) 2125 ||(!horizontal && taskRect.bottom < stackRect.bottom))) { 2126 if (horizontal) { 2127 maxMove = Math.min(stepSize, stackRect.right - taskRect.right); 2128 maxToTravel -= maxMove; 2129 taskRect.right += maxMove; 2130 taskRect.left += maxMove; 2131 } else { 2132 maxMove = Math.min(stepSize, stackRect.bottom - taskRect.bottom); 2133 maxToTravel -= maxMove; 2134 taskRect.top += maxMove; 2135 taskRect.bottom += maxMove; 2136 } 2137 taskResize(taskId, taskRect, delay_ms, false); 2138 } 2139 } else { 2140 while (maxToTravel < 0 2141 && ((horizontal && taskRect.left > stackRect.left) 2142 ||(!horizontal && taskRect.top > stackRect.top))) { 2143 if (horizontal) { 2144 maxMove = Math.min(stepSize, taskRect.left - stackRect.left); 2145 maxToTravel -= maxMove; 2146 taskRect.right -= maxMove; 2147 taskRect.left -= maxMove; 2148 } else { 2149 maxMove = Math.min(stepSize, taskRect.top - stackRect.top); 2150 maxToTravel -= maxMove; 2151 taskRect.top -= maxMove; 2152 taskRect.bottom -= maxMove; 2153 } 2154 taskResize(taskId, taskRect, delay_ms, false); 2155 } 2156 } 2157 // Return the remaining distance we didn't travel because we reached the target location. 2158 return maxToTravel; 2159 } 2160 2161 private void runTaskSizeTaskTest() { 2162 final int taskId = Integer.valueOf(nextArgRequired()); 2163 final int stepSize = Integer.valueOf(nextArgRequired()); 2164 final String delayStr = nextArg(); 2165 final int delay_ms = (delayStr != null) ? Integer.valueOf(delayStr) : 0; 2166 final StackInfo stackInfo; 2167 final Rect initialTaskBounds; 2168 try { 2169 stackInfo = mAm.getStackInfo(mAm.getFocusedStackId()); 2170 initialTaskBounds = mAm.getTaskBounds(taskId); 2171 } catch (RemoteException e) { 2172 System.err.println("Error getting focus stack info or task bounds: " + e); 2173 return; 2174 } 2175 final Rect stackBounds = stackInfo.bounds; 2176 stackBounds.inset(STACK_BOUNDS_INSET, STACK_BOUNDS_INSET); 2177 final Rect currentTaskBounds = new Rect(initialTaskBounds); 2178 2179 // Size by top-left 2180 System.out.println("Growing top-left"); 2181 do { 2182 currentTaskBounds.top -= getStepSize( 2183 currentTaskBounds.top, stackBounds.top, stepSize, GREATER_THAN_TARGET); 2184 2185 currentTaskBounds.left -= getStepSize( 2186 currentTaskBounds.left, stackBounds.left, stepSize, GREATER_THAN_TARGET); 2187 2188 taskResize(taskId, currentTaskBounds, delay_ms, true); 2189 } while (stackBounds.top < currentTaskBounds.top 2190 || stackBounds.left < currentTaskBounds.left); 2191 2192 // Back to original size 2193 System.out.println("Shrinking top-left"); 2194 do { 2195 currentTaskBounds.top += getStepSize( 2196 currentTaskBounds.top, initialTaskBounds.top, stepSize, !GREATER_THAN_TARGET); 2197 2198 currentTaskBounds.left += getStepSize( 2199 currentTaskBounds.left, initialTaskBounds.left, stepSize, !GREATER_THAN_TARGET); 2200 2201 taskResize(taskId, currentTaskBounds, delay_ms, true); 2202 } while (initialTaskBounds.top > currentTaskBounds.top 2203 || initialTaskBounds.left > currentTaskBounds.left); 2204 2205 // Size by top-right 2206 System.out.println("Growing top-right"); 2207 do { 2208 currentTaskBounds.top -= getStepSize( 2209 currentTaskBounds.top, stackBounds.top, stepSize, GREATER_THAN_TARGET); 2210 2211 currentTaskBounds.right += getStepSize( 2212 currentTaskBounds.right, stackBounds.right, stepSize, !GREATER_THAN_TARGET); 2213 2214 taskResize(taskId, currentTaskBounds, delay_ms, true); 2215 } while (stackBounds.top < currentTaskBounds.top 2216 || stackBounds.right > currentTaskBounds.right); 2217 2218 // Back to original size 2219 System.out.println("Shrinking top-right"); 2220 do { 2221 currentTaskBounds.top += getStepSize( 2222 currentTaskBounds.top, initialTaskBounds.top, stepSize, !GREATER_THAN_TARGET); 2223 2224 currentTaskBounds.right -= getStepSize(currentTaskBounds.right, initialTaskBounds.right, 2225 stepSize, GREATER_THAN_TARGET); 2226 2227 taskResize(taskId, currentTaskBounds, delay_ms, true); 2228 } while (initialTaskBounds.top > currentTaskBounds.top 2229 || initialTaskBounds.right < currentTaskBounds.right); 2230 2231 // Size by bottom-left 2232 System.out.println("Growing bottom-left"); 2233 do { 2234 currentTaskBounds.bottom += getStepSize( 2235 currentTaskBounds.bottom, stackBounds.bottom, stepSize, !GREATER_THAN_TARGET); 2236 2237 currentTaskBounds.left -= getStepSize( 2238 currentTaskBounds.left, stackBounds.left, stepSize, GREATER_THAN_TARGET); 2239 2240 taskResize(taskId, currentTaskBounds, delay_ms, true); 2241 } while (stackBounds.bottom > currentTaskBounds.bottom 2242 || stackBounds.left < currentTaskBounds.left); 2243 2244 // Back to original size 2245 System.out.println("Shrinking bottom-left"); 2246 do { 2247 currentTaskBounds.bottom -= getStepSize(currentTaskBounds.bottom, 2248 initialTaskBounds.bottom, stepSize, GREATER_THAN_TARGET); 2249 2250 currentTaskBounds.left += getStepSize( 2251 currentTaskBounds.left, initialTaskBounds.left, stepSize, !GREATER_THAN_TARGET); 2252 2253 taskResize(taskId, currentTaskBounds, delay_ms, true); 2254 } while (initialTaskBounds.bottom < currentTaskBounds.bottom 2255 || initialTaskBounds.left > currentTaskBounds.left); 2256 2257 // Size by bottom-right 2258 System.out.println("Growing bottom-right"); 2259 do { 2260 currentTaskBounds.bottom += getStepSize( 2261 currentTaskBounds.bottom, stackBounds.bottom, stepSize, !GREATER_THAN_TARGET); 2262 2263 currentTaskBounds.right += getStepSize( 2264 currentTaskBounds.right, stackBounds.right, stepSize, !GREATER_THAN_TARGET); 2265 2266 taskResize(taskId, currentTaskBounds, delay_ms, true); 2267 } while (stackBounds.bottom > currentTaskBounds.bottom 2268 || stackBounds.right > currentTaskBounds.right); 2269 2270 // Back to original size 2271 System.out.println("Shrinking bottom-right"); 2272 do { 2273 currentTaskBounds.bottom -= getStepSize(currentTaskBounds.bottom, 2274 initialTaskBounds.bottom, stepSize, GREATER_THAN_TARGET); 2275 2276 currentTaskBounds.right -= getStepSize(currentTaskBounds.right, initialTaskBounds.right, 2277 stepSize, GREATER_THAN_TARGET); 2278 2279 taskResize(taskId, currentTaskBounds, delay_ms, true); 2280 } while (initialTaskBounds.bottom < currentTaskBounds.bottom 2281 || initialTaskBounds.right < currentTaskBounds.right); 2282 } 2283 2284 private int getStepSize(int current, int target, int inStepSize, boolean greaterThanTarget) { 2285 int stepSize = 0; 2286 if (greaterThanTarget && target < current) { 2287 current -= inStepSize; 2288 stepSize = inStepSize; 2289 if (target > current) { 2290 stepSize -= (target - current); 2291 } 2292 } 2293 if (!greaterThanTarget && target > current) { 2294 current += inStepSize; 2295 stepSize = inStepSize; 2296 if (target < current) { 2297 stepSize += (current - target); 2298 } 2299 } 2300 return stepSize; 2301 } 2302 2303 private List<Configuration> getRecentConfigurations(int days) { 2304 IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService( 2305 Context.USAGE_STATS_SERVICE)); 2306 final long now = System.currentTimeMillis(); 2307 final long nDaysAgo = now - (days * 24 * 60 * 60 * 1000); 2308 try { 2309 @SuppressWarnings("unchecked") 2310 ParceledListSlice<ConfigurationStats> configStatsSlice = usm.queryConfigurationStats( 2311 UsageStatsManager.INTERVAL_BEST, nDaysAgo, now, "com.android.shell"); 2312 if (configStatsSlice == null) { 2313 return Collections.emptyList(); 2314 } 2315 2316 final ArrayMap<Configuration, Integer> recentConfigs = new ArrayMap<>(); 2317 final List<ConfigurationStats> configStatsList = configStatsSlice.getList(); 2318 final int configStatsListSize = configStatsList.size(); 2319 for (int i = 0; i < configStatsListSize; i++) { 2320 final ConfigurationStats stats = configStatsList.get(i); 2321 final int indexOfKey = recentConfigs.indexOfKey(stats.getConfiguration()); 2322 if (indexOfKey < 0) { 2323 recentConfigs.put(stats.getConfiguration(), stats.getActivationCount()); 2324 } else { 2325 recentConfigs.setValueAt(indexOfKey, 2326 recentConfigs.valueAt(indexOfKey) + stats.getActivationCount()); 2327 } 2328 } 2329 2330 final Comparator<Configuration> comparator = new Comparator<Configuration>() { 2331 @Override 2332 public int compare(Configuration a, Configuration b) { 2333 return recentConfigs.get(b).compareTo(recentConfigs.get(a)); 2334 } 2335 }; 2336 2337 ArrayList<Configuration> configs = new ArrayList<>(recentConfigs.size()); 2338 configs.addAll(recentConfigs.keySet()); 2339 Collections.sort(configs, comparator); 2340 return configs; 2341 2342 } catch (RemoteException e) { 2343 return Collections.emptyList(); 2344 } 2345 } 2346 2347 private void runGetConfig() throws Exception { 2348 int days = 14; 2349 String option = nextOption(); 2350 if (option != null) { 2351 if (!option.equals("--days")) { 2352 throw new IllegalArgumentException("unrecognized option " + option); 2353 } 2354 2355 days = Integer.parseInt(nextArgRequired()); 2356 if (days <= 0) { 2357 throw new IllegalArgumentException("--days must be a positive integer"); 2358 } 2359 } 2360 2361 try { 2362 Configuration config = mAm.getConfiguration(); 2363 if (config == null) { 2364 System.err.println("Activity manager has no configuration"); 2365 return; 2366 } 2367 2368 System.out.println("config: " + Configuration.resourceQualifierString(config)); 2369 System.out.println("abi: " + TextUtils.join(",", Build.SUPPORTED_ABIS)); 2370 2371 final List<Configuration> recentConfigs = getRecentConfigurations(days); 2372 final int recentConfigSize = recentConfigs.size(); 2373 if (recentConfigSize > 0) { 2374 System.out.println("recentConfigs:"); 2375 } 2376 2377 for (int i = 0; i < recentConfigSize; i++) { 2378 System.out.println(" config: " + Configuration.resourceQualifierString( 2379 recentConfigs.get(i))); 2380 } 2381 2382 } catch (RemoteException e) { 2383 } 2384 } 2385 2386 private void runSuppressResizeConfigChanges() throws Exception { 2387 boolean suppress = Boolean.valueOf(nextArgRequired()); 2388 2389 try { 2390 mAm.suppressResizeConfigChanges(suppress); 2391 } catch (RemoteException e) { 2392 System.err.println("Error suppressing resize config changes: " + e); 2393 } 2394 } 2395 2396 private void runSetInactive() throws Exception { 2397 int userId = UserHandle.USER_CURRENT; 2398 2399 String opt; 2400 while ((opt=nextOption()) != null) { 2401 if (opt.equals("--user")) { 2402 userId = parseUserArg(nextArgRequired()); 2403 } else { 2404 System.err.println("Error: Unknown option: " + opt); 2405 return; 2406 } 2407 } 2408 String packageName = nextArgRequired(); 2409 String value = nextArgRequired(); 2410 2411 IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService( 2412 Context.USAGE_STATS_SERVICE)); 2413 usm.setAppInactive(packageName, Boolean.parseBoolean(value), userId); 2414 } 2415 2416 private void runGetInactive() throws Exception { 2417 int userId = UserHandle.USER_CURRENT; 2418 2419 String opt; 2420 while ((opt=nextOption()) != null) { 2421 if (opt.equals("--user")) { 2422 userId = parseUserArg(nextArgRequired()); 2423 } else { 2424 System.err.println("Error: Unknown option: " + opt); 2425 return; 2426 } 2427 } 2428 String packageName = nextArgRequired(); 2429 2430 IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService( 2431 Context.USAGE_STATS_SERVICE)); 2432 boolean isIdle = usm.isAppInactive(packageName, userId); 2433 System.out.println("Idle=" + isIdle); 2434 } 2435 2436 private void runSendTrimMemory() throws Exception { 2437 int userId = UserHandle.USER_CURRENT; 2438 String opt; 2439 while ((opt = nextOption()) != null) { 2440 if (opt.equals("--user")) { 2441 userId = parseUserArg(nextArgRequired()); 2442 if (userId == UserHandle.USER_ALL) { 2443 System.err.println("Error: Can't use user 'all'"); 2444 return; 2445 } 2446 } else { 2447 System.err.println("Error: Unknown option: " + opt); 2448 return; 2449 } 2450 } 2451 2452 String proc = nextArgRequired(); 2453 String levelArg = nextArgRequired(); 2454 int level; 2455 switch (levelArg) { 2456 case "HIDDEN": 2457 level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN; 2458 break; 2459 case "RUNNING_MODERATE": 2460 level = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE; 2461 break; 2462 case "BACKGROUND": 2463 level = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND; 2464 break; 2465 case "RUNNING_LOW": 2466 level = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW; 2467 break; 2468 case "MODERATE": 2469 level = ComponentCallbacks2.TRIM_MEMORY_MODERATE; 2470 break; 2471 case "RUNNING_CRITICAL": 2472 level = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL; 2473 break; 2474 case "COMPLETE": 2475 level = ComponentCallbacks2.TRIM_MEMORY_COMPLETE; 2476 break; 2477 default: 2478 System.err.println("Error: Unknown level option: " + levelArg); 2479 return; 2480 } 2481 if (!mAm.setProcessMemoryTrimLevel(proc, userId, level)) { 2482 System.err.println("Error: Failure to set the level - probably Unknown Process: " + 2483 proc); 2484 } 2485 } 2486 2487 private void runGetCurrentUser() throws Exception { 2488 UserInfo currentUser = Preconditions.checkNotNull(mAm.getCurrentUser(), 2489 "Current user not set"); 2490 System.out.println(currentUser.id); 2491 } 2492 2493 /** 2494 * Open the given file for sending into the system process. This verifies 2495 * with SELinux that the system will have access to the file. 2496 */ 2497 private static ParcelFileDescriptor openForSystemServer(File file, int mode) 2498 throws FileNotFoundException { 2499 final ParcelFileDescriptor fd = ParcelFileDescriptor.open(file, mode); 2500 final String tcon = SELinux.getFileContext(file.getAbsolutePath()); 2501 if (!SELinux.checkSELinuxAccess("u:r:system_server:s0", tcon, "file", "read")) { 2502 throw new FileNotFoundException("System server has no access to file context " + tcon); 2503 } 2504 return fd; 2505 } 2506 2507 private Rect getBounds() { 2508 String leftStr = nextArgRequired(); 2509 int left = Integer.valueOf(leftStr); 2510 String topStr = nextArgRequired(); 2511 int top = Integer.valueOf(topStr); 2512 String rightStr = nextArgRequired(); 2513 int right = Integer.valueOf(rightStr); 2514 String bottomStr = nextArgRequired(); 2515 int bottom = Integer.valueOf(bottomStr); 2516 if (left < 0) { 2517 System.err.println("Error: bad left arg: " + leftStr); 2518 return null; 2519 } 2520 if (top < 0) { 2521 System.err.println("Error: bad top arg: " + topStr); 2522 return null; 2523 } 2524 if (right <= 0) { 2525 System.err.println("Error: bad right arg: " + rightStr); 2526 return null; 2527 } 2528 if (bottom <= 0) { 2529 System.err.println("Error: bad bottom arg: " + bottomStr); 2530 return null; 2531 } 2532 return new Rect(left, top, right, bottom); 2533 } 2534} 2535