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