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