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