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