Am.java revision 2c749d242759ea36c0229ea933f22b6363337b19
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.UiAutomationConnection; 30import android.content.ComponentName; 31import android.content.IIntentReceiver; 32import android.content.Intent; 33import android.content.pm.IPackageManager; 34import android.content.pm.ResolveInfo; 35import android.content.res.Configuration; 36import android.graphics.Rect; 37import android.net.Uri; 38import android.os.Binder; 39import android.os.Build; 40import android.os.Bundle; 41import android.os.IBinder; 42import android.os.ParcelFileDescriptor; 43import android.os.RemoteException; 44import android.os.ServiceManager; 45import android.os.SystemProperties; 46import android.os.UserHandle; 47import android.util.AndroidException; 48import android.view.IWindowManager; 49import android.view.View; 50 51import com.android.internal.os.BaseCommand; 52 53import dalvik.system.VMRuntime; 54 55import java.io.BufferedReader; 56import java.io.File; 57import java.io.FileNotFoundException; 58import java.io.IOException; 59import java.io.InputStreamReader; 60import java.io.PrintStream; 61import java.net.URISyntaxException; 62import java.util.HashSet; 63import java.util.List; 64 65public class Am extends BaseCommand { 66 67 private IActivityManager mAm; 68 69 private int mStartFlags = 0; 70 private boolean mWaitOption = false; 71 private boolean mStopOption = false; 72 73 private int mRepeat = 0; 74 private int mUserId; 75 private String mReceiverPermission; 76 77 private String mProfileFile; 78 79 /** 80 * Command-line entry point. 81 * 82 * @param args The command-line arguments 83 */ 84 public static void main(String[] args) { 85 (new Am()).run(args); 86 } 87 88 @Override 89 public void onShowUsage(PrintStream out) { 90 out.println( 91 "usage: am [subcommand] [options]\n" + 92 "usage: am start [-D] [-W] [-P <FILE>] [--start-profiler <FILE>]\n" + 93 " [--R COUNT] [-S] [--opengl-trace]\n" + 94 " [--user <USER_ID> | current] <INTENT>\n" + 95 " am startservice [--user <USER_ID> | current] <INTENT>\n" + 96 " am stopservice [--user <USER_ID> | current] <INTENT>\n" + 97 " am force-stop [--user <USER_ID> | all | current] <PACKAGE>\n" + 98 " am kill [--user <USER_ID> | all | current] <PACKAGE>\n" + 99 " am kill-all\n" + 100 " am broadcast [--user <USER_ID> | all | current] <INTENT>\n" + 101 " am instrument [-r] [-e <NAME> <VALUE>] [-p <FILE>] [-w]\n" + 102 " [--user <USER_ID> | current]\n" + 103 " [--no-window-animation]\n" + 104 " [--abi <ABI>]\n : Launch the instrumented process with the " + 105 " selected ABI. This assumes that the process supports the" + 106 " selected ABI." + 107 " <COMPONENT>\n" + 108 " am profile start [--user <USER_ID> current] <PROCESS> <FILE>\n" + 109 " am profile stop [--user <USER_ID> current] [<PROCESS>]\n" + 110 " am dumpheap [--user <USER_ID> current] [-n] <PROCESS> <FILE>\n" + 111 " am set-debug-app [-w] [--persistent] <PACKAGE>\n" + 112 " am clear-debug-app\n" + 113 " am monitor [--gdb <port>]\n" + 114 " am hang [--allow-restart]\n" + 115 " am restart\n" + 116 " am idle-maintenance\n" + 117 " am screen-compat [on|off] <PACKAGE>\n" + 118 " am to-uri [INTENT]\n" + 119 " am to-intent-uri [INTENT]\n" + 120 " am switch-user <USER_ID>\n" + 121 " am stop-user <USER_ID>\n" + 122 " am stack start <DISPLAY_ID> <INTENT>\n" + 123 " am stack movetask <TASK_ID> <STACK_ID> [true|false]\n" + 124 " am stack resize <STACK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" + 125 " am stack list\n" + 126 " am stack info <STACK_ID>\n" + 127 " am lock-task <TASK_ID>\n" + 128 " am lock-task stop\n" + 129 " am get-config\n" + 130 "\n" + 131 "am start: start an Activity. Options are:\n" + 132 " -D: enable debugging\n" + 133 " -W: wait for launch to complete\n" + 134 " --start-profiler <FILE>: start profiler and send results to <FILE>\n" + 135 " -P <FILE>: like above, but profiling stops when app goes idle\n" + 136 " -R: repeat the activity launch <COUNT> times. Prior to each repeat,\n" + 137 " the top activity will be finished.\n" + 138 " -S: force stop the target app before starting the activity\n" + 139 " --opengl-trace: enable tracing of OpenGL functions\n" + 140 " --user <USER_ID> | current: Specify which user to run as; if not\n" + 141 " specified then run as the current user.\n" + 142 "\n" + 143 "am startservice: start a Service. Options are:\n" + 144 " --user <USER_ID> | current: Specify which user to run as; if not\n" + 145 " specified then run as the current user.\n" + 146 "\n" + 147 "am stopservice: stop a Service. Options are:\n" + 148 " --user <USER_ID> | current: Specify which user to run as; if not\n" + 149 " specified then run as the current user.\n" + 150 "\n" + 151 "am force-stop: force stop everything associated with <PACKAGE>.\n" + 152 " --user <USER_ID> | all | current: Specify user to force stop;\n" + 153 " all users if not specified.\n" + 154 "\n" + 155 "am kill: Kill all processes associated with <PACKAGE>. Only kills.\n" + 156 " processes that are safe to kill -- that is, will not impact the user\n" + 157 " experience.\n" + 158 " --user <USER_ID> | all | current: Specify user whose processes to kill;\n" + 159 " all users if not specified.\n" + 160 "\n" + 161 "am kill-all: Kill all background processes.\n" + 162 "\n" + 163 "am broadcast: send a broadcast Intent. Options are:\n" + 164 " --user <USER_ID> | all | current: Specify which user to send to; if not\n" + 165 " specified then send to all users.\n" + 166 " --receiver-permission <PERMISSION>: Require receiver to hold permission.\n" + 167 "\n" + 168 "am instrument: start an Instrumentation. Typically this target <COMPONENT>\n" + 169 " is the form <TEST_PACKAGE>/<RUNNER_CLASS>. Options are:\n" + 170 " -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT). Use with\n" + 171 " [-e perf true] to generate raw output for performance measurements.\n" + 172 " -e <NAME> <VALUE>: set argument <NAME> to <VALUE>. For test runners a\n" + 173 " common form is [-e <testrunner_flag> <value>[,<value>...]].\n" + 174 " -p <FILE>: write profiling data to <FILE>\n" + 175 " -w: wait for instrumentation to finish before returning. Required for\n" + 176 " test runners.\n" + 177 " --user <USER_ID> | current: Specify user instrumentation runs in;\n" + 178 " current user if not specified.\n" + 179 " --no-window-animation: turn off window animations while running.\n" + 180 "\n" + 181 "am profile: start and stop profiler on a process. The given <PROCESS> argument\n" + 182 " may be either a process name or pid. Options are:\n" + 183 " --user <USER_ID> | current: When supplying a process name,\n" + 184 " specify user of process to profile; uses current user if not specified.\n" + 185 "\n" + 186 "am dumpheap: dump the heap of a process. The given <PROCESS> argument may\n" + 187 " be either a process name or pid. Options are:\n" + 188 " -n: dump native heap instead of managed heap\n" + 189 " --user <USER_ID> | current: When supplying a process name,\n" + 190 " specify user of process to dump; uses current user if not specified.\n" + 191 "\n" + 192 "am set-debug-app: set application <PACKAGE> to debug. Options are:\n" + 193 " -w: wait for debugger when application starts\n" + 194 " --persistent: retain this value\n" + 195 "\n" + 196 "am clear-debug-app: clear the previously set-debug-app.\n" + 197 "\n" + 198 "am bug-report: request bug report generation; will launch UI\n" + 199 " when done to select where it should be delivered.\n" + 200 "\n" + 201 "am monitor: start monitoring for crashes or ANRs.\n" + 202 " --gdb: start gdbserv on the given port at crash/ANR\n" + 203 "\n" + 204 "am hang: hang the system.\n" + 205 " --allow-restart: allow watchdog to perform normal system restart\n" + 206 "\n" + 207 "am restart: restart the user-space system.\n" + 208 "\n" + 209 "am idle-maintenance: perform idle maintenance now.\n" + 210 "\n" + 211 "am screen-compat: control screen compatibility mode of <PACKAGE>.\n" + 212 "\n" + 213 "am to-uri: print the given Intent specification as a URI.\n" + 214 "\n" + 215 "am to-intent-uri: print the given Intent specification as an intent: URI.\n" + 216 "\n" + 217 "am switch-user: switch to put USER_ID in the foreground, starting\n" + 218 " execution of that user if it is currently stopped.\n" + 219 "\n" + 220 "am stop-user: stop execution of USER_ID, not allowing it to run any\n" + 221 " code until a later explicit switch to it.\n" + 222 "\n" + 223 "am stack start: start a new activity on <DISPLAY_ID> using <INTENT>.\n" + 224 "\n" + 225 "am stack movetask: move <TASK_ID> from its current stack to the top (true) or" + 226 " bottom (false) of <STACK_ID>.\n" + 227 "\n" + 228 "am stack resize: change <STACK_ID> size and position to <LEFT,TOP,RIGHT,BOTTOM>.\n" + 229 "\n" + 230 "am stack list: list all of the activity stacks and their sizes.\n" + 231 "\n" + 232 "am stack info: display the information about activity stack <STACK_ID>.\n" + 233 "\n" + 234 "am lock-task: bring <TASK_ID> to the front and don't allow other tasks to run\n" + 235 "\n" + 236 "am get-config: retrieve the configuration and any recent configurations\n" + 237 " of the device\n" + 238 "\n" + 239 "<INTENT> specifications include these flags and arguments:\n" + 240 " [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]\n" + 241 " [-c <CATEGORY> [-c <CATEGORY>] ...]\n" + 242 " [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]\n" + 243 " [--esn <EXTRA_KEY> ...]\n" + 244 " [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]\n" + 245 " [--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]\n" + 246 " [--el <EXTRA_KEY> <EXTRA_LONG_VALUE> ...]\n" + 247 " [--ef <EXTRA_KEY> <EXTRA_FLOAT_VALUE> ...]\n" + 248 " [--eu <EXTRA_KEY> <EXTRA_URI_VALUE> ...]\n" + 249 " [--ecn <EXTRA_KEY> <EXTRA_COMPONENT_NAME_VALUE>]\n" + 250 " [--eia <EXTRA_KEY> <EXTRA_INT_VALUE>[,<EXTRA_INT_VALUE...]]\n" + 251 " [--ela <EXTRA_KEY> <EXTRA_LONG_VALUE>[,<EXTRA_LONG_VALUE...]]\n" + 252 " [--efa <EXTRA_KEY> <EXTRA_FLOAT_VALUE>[,<EXTRA_FLOAT_VALUE...]]\n" + 253 " [--esa <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]\n" + 254 " (to embed a comma into a string escape it using \"\\,\")\n" + 255 " [-n <COMPONENT>] [-f <FLAGS>]\n" + 256 " [--grant-read-uri-permission] [--grant-write-uri-permission]\n" + 257 " [--grant-persistable-uri-permission] [--grant-prefix-uri-permission]\n" + 258 " [--debug-log-resolution] [--exclude-stopped-packages]\n" + 259 " [--include-stopped-packages]\n" + 260 " [--activity-brought-to-front] [--activity-clear-top]\n" + 261 " [--activity-clear-when-task-reset] [--activity-exclude-from-recents]\n" + 262 " [--activity-launched-from-history] [--activity-multiple-task]\n" + 263 " [--activity-no-animation] [--activity-no-history]\n" + 264 " [--activity-no-user-action] [--activity-previous-is-top]\n" + 265 " [--activity-reorder-to-front] [--activity-reset-task-if-needed]\n" + 266 " [--activity-single-top] [--activity-clear-task]\n" + 267 " [--activity-task-on-home]\n" + 268 " [--receiver-registered-only] [--receiver-replace-pending]\n" + 269 " [--selector]\n" + 270 " [<URI> | <PACKAGE> | <COMPONENT>]\n" 271 ); 272 } 273 274 @Override 275 public void onRun() throws Exception { 276 277 mAm = ActivityManagerNative.getDefault(); 278 if (mAm == null) { 279 System.err.println(NO_SYSTEM_ERROR_CODE); 280 throw new AndroidException("Can't connect to activity manager; is the system running?"); 281 } 282 283 String op = nextArgRequired(); 284 285 if (op.equals("start")) { 286 runStart(); 287 } else if (op.equals("startservice")) { 288 runStartService(); 289 } else if (op.equals("stopservice")) { 290 runStopService(); 291 } else if (op.equals("force-stop")) { 292 runForceStop(); 293 } else if (op.equals("kill")) { 294 runKill(); 295 } else if (op.equals("kill-all")) { 296 runKillAll(); 297 } else if (op.equals("instrument")) { 298 runInstrument(); 299 } else if (op.equals("broadcast")) { 300 sendBroadcast(); 301 } else if (op.equals("profile")) { 302 runProfile(); 303 } else if (op.equals("dumpheap")) { 304 runDumpHeap(); 305 } else if (op.equals("set-debug-app")) { 306 runSetDebugApp(); 307 } else if (op.equals("clear-debug-app")) { 308 runClearDebugApp(); 309 } else if (op.equals("bug-report")) { 310 runBugReport(); 311 } else if (op.equals("monitor")) { 312 runMonitor(); 313 } else if (op.equals("hang")) { 314 runHang(); 315 } else if (op.equals("restart")) { 316 runRestart(); 317 } else if (op.equals("idle-maintenance")) { 318 runIdleMaintenance(); 319 } else if (op.equals("screen-compat")) { 320 runScreenCompat(); 321 } else if (op.equals("to-uri")) { 322 runToUri(false); 323 } else if (op.equals("to-intent-uri")) { 324 runToUri(true); 325 } else if (op.equals("switch-user")) { 326 runSwitchUser(); 327 } else if (op.equals("stop-user")) { 328 runStopUser(); 329 } else if (op.equals("stack")) { 330 runStack(); 331 } else if (op.equals("lock-task")) { 332 runLockTask(); 333 } else if (op.equals("get-config")) { 334 runGetConfig(); 335 } else { 336 showError("Error: unknown command '" + op + "'"); 337 } 338 } 339 340 int parseUserArg(String arg) { 341 int userId; 342 if ("all".equals(arg)) { 343 userId = UserHandle.USER_ALL; 344 } else if ("current".equals(arg) || "cur".equals(arg)) { 345 userId = UserHandle.USER_CURRENT; 346 } else { 347 userId = Integer.parseInt(arg); 348 } 349 return userId; 350 } 351 352 private Intent makeIntent(int defUser) throws URISyntaxException { 353 Intent intent = new Intent(); 354 Intent baseIntent = intent; 355 boolean hasIntentInfo = false; 356 357 mStartFlags = 0; 358 mWaitOption = false; 359 mStopOption = false; 360 mRepeat = 0; 361 mProfileFile = null; 362 mUserId = defUser; 363 Uri data = null; 364 String type = null; 365 366 String opt; 367 while ((opt=nextOption()) != null) { 368 if (opt.equals("-a")) { 369 intent.setAction(nextArgRequired()); 370 if (intent == baseIntent) { 371 hasIntentInfo = true; 372 } 373 } else if (opt.equals("-d")) { 374 data = Uri.parse(nextArgRequired()); 375 if (intent == baseIntent) { 376 hasIntentInfo = true; 377 } 378 } else if (opt.equals("-t")) { 379 type = nextArgRequired(); 380 if (intent == baseIntent) { 381 hasIntentInfo = true; 382 } 383 } else if (opt.equals("-c")) { 384 intent.addCategory(nextArgRequired()); 385 if (intent == baseIntent) { 386 hasIntentInfo = true; 387 } 388 } else if (opt.equals("-e") || opt.equals("--es")) { 389 String key = nextArgRequired(); 390 String value = nextArgRequired(); 391 intent.putExtra(key, value); 392 } else if (opt.equals("--esn")) { 393 String key = nextArgRequired(); 394 intent.putExtra(key, (String) null); 395 } else if (opt.equals("--ei")) { 396 String key = nextArgRequired(); 397 String value = nextArgRequired(); 398 intent.putExtra(key, Integer.valueOf(value)); 399 } else if (opt.equals("--eu")) { 400 String key = nextArgRequired(); 401 String value = nextArgRequired(); 402 intent.putExtra(key, Uri.parse(value)); 403 } else if (opt.equals("--ecn")) { 404 String key = nextArgRequired(); 405 String value = nextArgRequired(); 406 ComponentName cn = ComponentName.unflattenFromString(value); 407 if (cn == null) throw new IllegalArgumentException("Bad component name: " + value); 408 intent.putExtra(key, cn); 409 } else if (opt.equals("--eia")) { 410 String key = nextArgRequired(); 411 String value = nextArgRequired(); 412 String[] strings = value.split(","); 413 int[] list = new int[strings.length]; 414 for (int i = 0; i < strings.length; i++) { 415 list[i] = Integer.valueOf(strings[i]); 416 } 417 intent.putExtra(key, list); 418 } else if (opt.equals("--el")) { 419 String key = nextArgRequired(); 420 String value = nextArgRequired(); 421 intent.putExtra(key, Long.valueOf(value)); 422 } else if (opt.equals("--ela")) { 423 String key = nextArgRequired(); 424 String value = nextArgRequired(); 425 String[] strings = value.split(","); 426 long[] list = new long[strings.length]; 427 for (int i = 0; i < strings.length; i++) { 428 list[i] = Long.valueOf(strings[i]); 429 } 430 intent.putExtra(key, list); 431 hasIntentInfo = true; 432 } else if (opt.equals("--ef")) { 433 String key = nextArgRequired(); 434 String value = nextArgRequired(); 435 intent.putExtra(key, Float.valueOf(value)); 436 hasIntentInfo = true; 437 } else if (opt.equals("--efa")) { 438 String key = nextArgRequired(); 439 String value = nextArgRequired(); 440 String[] strings = value.split(","); 441 float[] list = new float[strings.length]; 442 for (int i = 0; i < strings.length; i++) { 443 list[i] = Float.valueOf(strings[i]); 444 } 445 intent.putExtra(key, list); 446 hasIntentInfo = true; 447 } else if (opt.equals("--esa")) { 448 String key = nextArgRequired(); 449 String value = nextArgRequired(); 450 // Split on commas unless they are preceeded by an escape. 451 // The escape character must be escaped for the string and 452 // again for the regex, thus four escape characters become one. 453 String[] strings = value.split("(?<!\\\\),"); 454 intent.putExtra(key, strings); 455 hasIntentInfo = true; 456 } else if (opt.equals("--ez")) { 457 String key = nextArgRequired(); 458 String value = nextArgRequired(); 459 intent.putExtra(key, Boolean.valueOf(value)); 460 } else if (opt.equals("-n")) { 461 String str = nextArgRequired(); 462 ComponentName cn = ComponentName.unflattenFromString(str); 463 if (cn == null) throw new IllegalArgumentException("Bad component name: " + str); 464 intent.setComponent(cn); 465 if (intent == baseIntent) { 466 hasIntentInfo = true; 467 } 468 } else if (opt.equals("-f")) { 469 String str = nextArgRequired(); 470 intent.setFlags(Integer.decode(str).intValue()); 471 } else if (opt.equals("--grant-read-uri-permission")) { 472 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 473 } else if (opt.equals("--grant-write-uri-permission")) { 474 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 475 } else if (opt.equals("--grant-persistable-uri-permission")) { 476 intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); 477 } else if (opt.equals("--grant-prefix-uri-permission")) { 478 intent.addFlags(Intent.FLAG_GRANT_PREFIX_URI_PERMISSION); 479 } else if (opt.equals("--exclude-stopped-packages")) { 480 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); 481 } else if (opt.equals("--include-stopped-packages")) { 482 intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 483 } else if (opt.equals("--debug-log-resolution")) { 484 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 485 } else if (opt.equals("--activity-brought-to-front")) { 486 intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); 487 } else if (opt.equals("--activity-clear-top")) { 488 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 489 } else if (opt.equals("--activity-clear-when-task-reset")) { 490 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); 491 } else if (opt.equals("--activity-exclude-from-recents")) { 492 intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 493 } else if (opt.equals("--activity-launched-from-history")) { 494 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY); 495 } else if (opt.equals("--activity-multiple-task")) { 496 intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); 497 } else if (opt.equals("--activity-no-animation")) { 498 intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 499 } else if (opt.equals("--activity-no-history")) { 500 intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 501 } else if (opt.equals("--activity-no-user-action")) { 502 intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION); 503 } else if (opt.equals("--activity-previous-is-top")) { 504 intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); 505 } else if (opt.equals("--activity-reorder-to-front")) { 506 intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); 507 } else if (opt.equals("--activity-reset-task-if-needed")) { 508 intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 509 } else if (opt.equals("--activity-single-top")) { 510 intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 511 } else if (opt.equals("--activity-clear-task")) { 512 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); 513 } else if (opt.equals("--activity-task-on-home")) { 514 intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME); 515 } else if (opt.equals("--receiver-registered-only")) { 516 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 517 } else if (opt.equals("--receiver-replace-pending")) { 518 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 519 } else if (opt.equals("--selector")) { 520 intent.setDataAndType(data, type); 521 intent = new Intent(); 522 } else if (opt.equals("-D")) { 523 mStartFlags |= ActivityManager.START_FLAG_DEBUG; 524 } else if (opt.equals("-W")) { 525 mWaitOption = true; 526 } else if (opt.equals("-P")) { 527 mProfileFile = nextArgRequired(); 528 mStartFlags |= ActivityManager.START_FLAG_AUTO_STOP_PROFILER; 529 } else if (opt.equals("--start-profiler")) { 530 mProfileFile = nextArgRequired(); 531 mStartFlags &= ~ActivityManager.START_FLAG_AUTO_STOP_PROFILER; 532 } else if (opt.equals("-R")) { 533 mRepeat = Integer.parseInt(nextArgRequired()); 534 } else if (opt.equals("-S")) { 535 mStopOption = true; 536 } else if (opt.equals("--opengl-trace")) { 537 mStartFlags |= ActivityManager.START_FLAG_OPENGL_TRACES; 538 } else if (opt.equals("--user")) { 539 mUserId = parseUserArg(nextArgRequired()); 540 } else if (opt.equals("--receiver-permission")) { 541 mReceiverPermission = nextArgRequired(); 542 } else { 543 System.err.println("Error: Unknown option: " + opt); 544 return null; 545 } 546 } 547 intent.setDataAndType(data, type); 548 549 final boolean hasSelector = intent != baseIntent; 550 if (hasSelector) { 551 // A selector was specified; fix up. 552 baseIntent.setSelector(intent); 553 intent = baseIntent; 554 } 555 556 String arg = nextArg(); 557 baseIntent = null; 558 if (arg == null) { 559 if (hasSelector) { 560 // If a selector has been specified, and no arguments 561 // have been supplied for the main Intent, then we can 562 // assume it is ACTION_MAIN CATEGORY_LAUNCHER; we don't 563 // need to have a component name specified yet, the 564 // selector will take care of that. 565 baseIntent = new Intent(Intent.ACTION_MAIN); 566 baseIntent.addCategory(Intent.CATEGORY_LAUNCHER); 567 } 568 } else if (arg.indexOf(':') >= 0) { 569 // The argument is a URI. Fully parse it, and use that result 570 // to fill in any data not specified so far. 571 baseIntent = Intent.parseUri(arg, Intent.URI_INTENT_SCHEME); 572 } else if (arg.indexOf('/') >= 0) { 573 // The argument is a component name. Build an Intent to launch 574 // it. 575 baseIntent = new Intent(Intent.ACTION_MAIN); 576 baseIntent.addCategory(Intent.CATEGORY_LAUNCHER); 577 baseIntent.setComponent(ComponentName.unflattenFromString(arg)); 578 } else { 579 // Assume the argument is a package name. 580 baseIntent = new Intent(Intent.ACTION_MAIN); 581 baseIntent.addCategory(Intent.CATEGORY_LAUNCHER); 582 baseIntent.setPackage(arg); 583 } 584 if (baseIntent != null) { 585 Bundle extras = intent.getExtras(); 586 intent.replaceExtras((Bundle)null); 587 Bundle uriExtras = baseIntent.getExtras(); 588 baseIntent.replaceExtras((Bundle)null); 589 if (intent.getAction() != null && baseIntent.getCategories() != null) { 590 HashSet<String> cats = new HashSet<String>(baseIntent.getCategories()); 591 for (String c : cats) { 592 baseIntent.removeCategory(c); 593 } 594 } 595 intent.fillIn(baseIntent, Intent.FILL_IN_COMPONENT | Intent.FILL_IN_SELECTOR); 596 if (extras == null) { 597 extras = uriExtras; 598 } else if (uriExtras != null) { 599 uriExtras.putAll(extras); 600 extras = uriExtras; 601 } 602 intent.replaceExtras(extras); 603 hasIntentInfo = true; 604 } 605 606 if (!hasIntentInfo) throw new IllegalArgumentException("No intent supplied"); 607 return intent; 608 } 609 610 private void runStartService() throws Exception { 611 Intent intent = makeIntent(UserHandle.USER_CURRENT); 612 if (mUserId == UserHandle.USER_ALL) { 613 System.err.println("Error: Can't start activity with user 'all'"); 614 return; 615 } 616 System.out.println("Starting service: " + intent); 617 ComponentName cn = mAm.startService(null, intent, intent.getType(), mUserId); 618 if (cn == null) { 619 System.err.println("Error: Not found; no service started."); 620 } else if (cn.getPackageName().equals("!")) { 621 System.err.println("Error: Requires permission " + cn.getClassName()); 622 } else if (cn.getPackageName().equals("!!")) { 623 System.err.println("Error: " + cn.getClassName()); 624 } 625 } 626 627 private void runStopService() throws Exception { 628 Intent intent = makeIntent(UserHandle.USER_CURRENT); 629 if (mUserId == UserHandle.USER_ALL) { 630 System.err.println("Error: Can't stop activity with user 'all'"); 631 return; 632 } 633 System.out.println("Stopping service: " + intent); 634 int result = mAm.stopService(null, intent, intent.getType(), mUserId); 635 if (result == 0) { 636 System.err.println("Service not stopped: was not running."); 637 } else if (result == 1) { 638 System.err.println("Service stopped"); 639 } else if (result == -1) { 640 System.err.println("Error stopping service"); 641 } 642 } 643 644 private void runStart() throws Exception { 645 Intent intent = makeIntent(UserHandle.USER_CURRENT); 646 647 if (mUserId == UserHandle.USER_ALL) { 648 System.err.println("Error: Can't start service with user 'all'"); 649 return; 650 } 651 652 String mimeType = intent.getType(); 653 if (mimeType == null && intent.getData() != null 654 && "content".equals(intent.getData().getScheme())) { 655 mimeType = mAm.getProviderMimeType(intent.getData(), mUserId); 656 } 657 658 do { 659 if (mStopOption) { 660 String packageName; 661 if (intent.getComponent() != null) { 662 packageName = intent.getComponent().getPackageName(); 663 } else { 664 IPackageManager pm = IPackageManager.Stub.asInterface( 665 ServiceManager.getService("package")); 666 if (pm == null) { 667 System.err.println("Error: Package manager not running; aborting"); 668 return; 669 } 670 List<ResolveInfo> activities = pm.queryIntentActivities(intent, mimeType, 0, 671 mUserId); 672 if (activities == null || activities.size() <= 0) { 673 System.err.println("Error: Intent does not match any activities: " 674 + intent); 675 return; 676 } else if (activities.size() > 1) { 677 System.err.println("Error: Intent matches multiple activities; can't stop: " 678 + intent); 679 return; 680 } 681 packageName = activities.get(0).activityInfo.packageName; 682 } 683 System.out.println("Stopping: " + packageName); 684 mAm.forceStopPackage(packageName, mUserId); 685 Thread.sleep(250); 686 } 687 688 System.out.println("Starting: " + intent); 689 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 690 691 ParcelFileDescriptor fd = null; 692 693 if (mProfileFile != null) { 694 try { 695 fd = ParcelFileDescriptor.open( 696 new File(mProfileFile), 697 ParcelFileDescriptor.MODE_CREATE | 698 ParcelFileDescriptor.MODE_TRUNCATE | 699 ParcelFileDescriptor.MODE_READ_WRITE); 700 } catch (FileNotFoundException e) { 701 System.err.println("Error: Unable to open file: " + mProfileFile); 702 return; 703 } 704 } 705 706 IActivityManager.WaitResult result = null; 707 int res; 708 if (mWaitOption) { 709 result = mAm.startActivityAndWait(null, null, intent, mimeType, 710 null, null, 0, mStartFlags, mProfileFile, fd, null, mUserId); 711 res = result.result; 712 } else { 713 res = mAm.startActivityAsUser(null, null, intent, mimeType, 714 null, null, 0, mStartFlags, mProfileFile, fd, null, mUserId); 715 } 716 PrintStream out = mWaitOption ? System.out : System.err; 717 boolean launched = false; 718 switch (res) { 719 case ActivityManager.START_SUCCESS: 720 launched = true; 721 break; 722 case ActivityManager.START_SWITCHES_CANCELED: 723 launched = true; 724 out.println( 725 "Warning: Activity not started because the " 726 + " current activity is being kept for the user."); 727 break; 728 case ActivityManager.START_DELIVERED_TO_TOP: 729 launched = true; 730 out.println( 731 "Warning: Activity not started, intent has " 732 + "been delivered to currently running " 733 + "top-most instance."); 734 break; 735 case ActivityManager.START_RETURN_INTENT_TO_CALLER: 736 launched = true; 737 out.println( 738 "Warning: Activity not started because intent " 739 + "should be handled by the caller"); 740 break; 741 case ActivityManager.START_TASK_TO_FRONT: 742 launched = true; 743 out.println( 744 "Warning: Activity not started, its current " 745 + "task has been brought to the front"); 746 break; 747 case ActivityManager.START_INTENT_NOT_RESOLVED: 748 out.println( 749 "Error: Activity not started, unable to " 750 + "resolve " + intent.toString()); 751 break; 752 case ActivityManager.START_CLASS_NOT_FOUND: 753 out.println(NO_CLASS_ERROR_CODE); 754 out.println("Error: Activity class " + 755 intent.getComponent().toShortString() 756 + " does not exist."); 757 break; 758 case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT: 759 out.println( 760 "Error: Activity not started, you requested to " 761 + "both forward and receive its result"); 762 break; 763 case ActivityManager.START_PERMISSION_DENIED: 764 out.println( 765 "Error: Activity not started, you do not " 766 + "have permission to access it."); 767 break; 768 case ActivityManager.START_NOT_VOICE_COMPATIBLE: 769 out.println( 770 "Error: Activity not started, voice control not allowed for: " 771 + intent); 772 break; 773 default: 774 out.println( 775 "Error: Activity not started, unknown error code " + res); 776 break; 777 } 778 if (mWaitOption && launched) { 779 if (result == null) { 780 result = new IActivityManager.WaitResult(); 781 result.who = intent.getComponent(); 782 } 783 System.out.println("Status: " + (result.timeout ? "timeout" : "ok")); 784 if (result.who != null) { 785 System.out.println("Activity: " + result.who.flattenToShortString()); 786 } 787 if (result.thisTime >= 0) { 788 System.out.println("ThisTime: " + result.thisTime); 789 } 790 if (result.totalTime >= 0) { 791 System.out.println("TotalTime: " + result.totalTime); 792 } 793 System.out.println("Complete"); 794 } 795 mRepeat--; 796 if (mRepeat > 1) { 797 mAm.unhandledBack(); 798 } 799 } while (mRepeat > 1); 800 } 801 802 private void runForceStop() throws Exception { 803 int userId = UserHandle.USER_ALL; 804 805 String opt; 806 while ((opt=nextOption()) != null) { 807 if (opt.equals("--user")) { 808 userId = parseUserArg(nextArgRequired()); 809 } else { 810 System.err.println("Error: Unknown option: " + opt); 811 return; 812 } 813 } 814 mAm.forceStopPackage(nextArgRequired(), userId); 815 } 816 817 private void runKill() throws Exception { 818 int userId = UserHandle.USER_ALL; 819 820 String opt; 821 while ((opt=nextOption()) != null) { 822 if (opt.equals("--user")) { 823 userId = parseUserArg(nextArgRequired()); 824 } else { 825 System.err.println("Error: Unknown option: " + opt); 826 return; 827 } 828 } 829 mAm.killBackgroundProcesses(nextArgRequired(), userId); 830 } 831 832 private void runKillAll() throws Exception { 833 mAm.killAllBackgroundProcesses(); 834 } 835 836 private void sendBroadcast() throws Exception { 837 Intent intent = makeIntent(UserHandle.USER_ALL); 838 IntentReceiver receiver = new IntentReceiver(); 839 System.out.println("Broadcasting: " + intent); 840 mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, mReceiverPermission, 841 android.app.AppOpsManager.OP_NONE, true, false, mUserId); 842 receiver.waitForFinish(); 843 } 844 845 private void runInstrument() throws Exception { 846 String profileFile = null; 847 boolean wait = false; 848 boolean rawMode = false; 849 boolean no_window_animation = false; 850 int userId = UserHandle.USER_CURRENT; 851 Bundle args = new Bundle(); 852 String argKey = null, argValue = null; 853 IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window")); 854 String abi = null; 855 856 String opt; 857 while ((opt=nextOption()) != null) { 858 if (opt.equals("-p")) { 859 profileFile = nextArgRequired(); 860 } else if (opt.equals("-w")) { 861 wait = true; 862 } else if (opt.equals("-r")) { 863 rawMode = true; 864 } else if (opt.equals("-e")) { 865 argKey = nextArgRequired(); 866 argValue = nextArgRequired(); 867 args.putString(argKey, argValue); 868 } else if (opt.equals("--no_window_animation") 869 || opt.equals("--no-window-animation")) { 870 no_window_animation = true; 871 } else if (opt.equals("--user")) { 872 userId = parseUserArg(nextArgRequired()); 873 } else if (opt.equals("--abi")) { 874 abi = nextArgRequired(); 875 } else { 876 System.err.println("Error: Unknown option: " + opt); 877 return; 878 } 879 } 880 881 if (userId == UserHandle.USER_ALL) { 882 System.err.println("Error: Can't start instrumentation with user 'all'"); 883 return; 884 } 885 886 String cnArg = nextArgRequired(); 887 ComponentName cn = ComponentName.unflattenFromString(cnArg); 888 if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg); 889 890 InstrumentationWatcher watcher = null; 891 UiAutomationConnection connection = null; 892 if (wait) { 893 watcher = new InstrumentationWatcher(); 894 watcher.setRawOutput(rawMode); 895 connection = new UiAutomationConnection(); 896 } 897 898 float[] oldAnims = null; 899 if (no_window_animation) { 900 oldAnims = wm.getAnimationScales(); 901 wm.setAnimationScale(0, 0.0f); 902 wm.setAnimationScale(1, 0.0f); 903 } 904 905 if (abi != null) { 906 final String[] supportedAbis = Build.SUPPORTED_ABIS; 907 boolean matched = false; 908 for (String supportedAbi : supportedAbis) { 909 if (supportedAbi.equals(abi)) { 910 matched = true; 911 break; 912 } 913 } 914 915 if (!matched) { 916 throw new AndroidException( 917 "INSTRUMENTATION_FAILED: Unsupported instruction set " + abi); 918 } 919 } 920 921 if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher, connection, userId, abi)) { 922 throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString()); 923 } 924 925 if (watcher != null) { 926 if (!watcher.waitForFinish()) { 927 System.out.println("INSTRUMENTATION_ABORTED: System has crashed."); 928 } 929 } 930 931 if (oldAnims != null) { 932 wm.setAnimationScales(oldAnims); 933 } 934 } 935 936 static void removeWallOption() { 937 String props = SystemProperties.get("dalvik.vm.extra-opts"); 938 if (props != null && props.contains("-Xprofile:wallclock")) { 939 props = props.replace("-Xprofile:wallclock", ""); 940 props = props.trim(); 941 SystemProperties.set("dalvik.vm.extra-opts", props); 942 } 943 } 944 945 private void runProfile() throws Exception { 946 String profileFile = null; 947 boolean start = false; 948 boolean wall = false; 949 int userId = UserHandle.USER_CURRENT; 950 int profileType = 0; 951 952 String process = null; 953 954 String cmd = nextArgRequired(); 955 956 if ("start".equals(cmd)) { 957 start = true; 958 String opt; 959 while ((opt=nextOption()) != null) { 960 if (opt.equals("--user")) { 961 userId = parseUserArg(nextArgRequired()); 962 } else if (opt.equals("--wall")) { 963 wall = true; 964 } else { 965 System.err.println("Error: Unknown option: " + opt); 966 return; 967 } 968 } 969 process = nextArgRequired(); 970 } else if ("stop".equals(cmd)) { 971 String opt; 972 while ((opt=nextOption()) != null) { 973 if (opt.equals("--user")) { 974 userId = parseUserArg(nextArgRequired()); 975 } else { 976 System.err.println("Error: Unknown option: " + opt); 977 return; 978 } 979 } 980 process = nextArg(); 981 } else { 982 // Compatibility with old syntax: process is specified first. 983 process = cmd; 984 cmd = nextArgRequired(); 985 if ("start".equals(cmd)) { 986 start = true; 987 } else if (!"stop".equals(cmd)) { 988 throw new IllegalArgumentException("Profile command " + process + " not valid"); 989 } 990 } 991 992 if (userId == UserHandle.USER_ALL) { 993 System.err.println("Error: Can't profile with user 'all'"); 994 return; 995 } 996 997 ParcelFileDescriptor fd = null; 998 999 if (start) { 1000 profileFile = nextArgRequired(); 1001 try { 1002 fd = ParcelFileDescriptor.open( 1003 new File(profileFile), 1004 ParcelFileDescriptor.MODE_CREATE | 1005 ParcelFileDescriptor.MODE_TRUNCATE | 1006 ParcelFileDescriptor.MODE_READ_WRITE); 1007 } catch (FileNotFoundException e) { 1008 System.err.println("Error: Unable to open file: " + profileFile); 1009 return; 1010 } 1011 } 1012 1013 try { 1014 if (wall) { 1015 // XXX doesn't work -- this needs to be set before booting. 1016 String props = SystemProperties.get("dalvik.vm.extra-opts"); 1017 if (props == null || !props.contains("-Xprofile:wallclock")) { 1018 props = props + " -Xprofile:wallclock"; 1019 //SystemProperties.set("dalvik.vm.extra-opts", props); 1020 } 1021 } else if (start) { 1022 //removeWallOption(); 1023 } 1024 if (!mAm.profileControl(process, userId, start, profileFile, fd, profileType)) { 1025 wall = false; 1026 throw new AndroidException("PROFILE FAILED on process " + process); 1027 } 1028 } finally { 1029 if (!wall) { 1030 //removeWallOption(); 1031 } 1032 } 1033 } 1034 1035 private void runDumpHeap() throws Exception { 1036 boolean managed = true; 1037 int userId = UserHandle.USER_CURRENT; 1038 1039 String opt; 1040 while ((opt=nextOption()) != null) { 1041 if (opt.equals("--user")) { 1042 userId = parseUserArg(nextArgRequired()); 1043 if (userId == UserHandle.USER_ALL) { 1044 System.err.println("Error: Can't dump heap with user 'all'"); 1045 return; 1046 } 1047 } else if (opt.equals("-n")) { 1048 managed = false; 1049 } else { 1050 System.err.println("Error: Unknown option: " + opt); 1051 return; 1052 } 1053 } 1054 String process = nextArgRequired(); 1055 String heapFile = nextArgRequired(); 1056 ParcelFileDescriptor fd = null; 1057 1058 try { 1059 File file = new File(heapFile); 1060 file.delete(); 1061 fd = ParcelFileDescriptor.open(file, 1062 ParcelFileDescriptor.MODE_CREATE | 1063 ParcelFileDescriptor.MODE_TRUNCATE | 1064 ParcelFileDescriptor.MODE_READ_WRITE); 1065 } catch (FileNotFoundException e) { 1066 System.err.println("Error: Unable to open file: " + heapFile); 1067 return; 1068 } 1069 1070 if (!mAm.dumpHeap(process, userId, managed, heapFile, fd)) { 1071 throw new AndroidException("HEAP DUMP FAILED on process " + process); 1072 } 1073 } 1074 1075 private void runSetDebugApp() throws Exception { 1076 boolean wait = false; 1077 boolean persistent = false; 1078 1079 String opt; 1080 while ((opt=nextOption()) != null) { 1081 if (opt.equals("-w")) { 1082 wait = true; 1083 } else if (opt.equals("--persistent")) { 1084 persistent = true; 1085 } else { 1086 System.err.println("Error: Unknown option: " + opt); 1087 return; 1088 } 1089 } 1090 1091 String pkg = nextArgRequired(); 1092 mAm.setDebugApp(pkg, wait, persistent); 1093 } 1094 1095 private void runClearDebugApp() throws Exception { 1096 mAm.setDebugApp(null, false, true); 1097 } 1098 1099 private void runBugReport() throws Exception { 1100 mAm.requestBugReport(); 1101 System.out.println("Your lovely bug report is being created; please be patient."); 1102 } 1103 1104 private void runSwitchUser() throws Exception { 1105 String user = nextArgRequired(); 1106 mAm.switchUser(Integer.parseInt(user)); 1107 } 1108 1109 private void runStopUser() throws Exception { 1110 String user = nextArgRequired(); 1111 int res = mAm.stopUser(Integer.parseInt(user), null); 1112 if (res != ActivityManager.USER_OP_SUCCESS) { 1113 String txt = ""; 1114 switch (res) { 1115 case ActivityManager.USER_OP_IS_CURRENT: 1116 txt = " (Can't stop current user)"; 1117 break; 1118 case ActivityManager.USER_OP_UNKNOWN_USER: 1119 txt = " (Unknown user " + user + ")"; 1120 break; 1121 } 1122 System.err.println("Switch failed: " + res + txt); 1123 } 1124 } 1125 1126 class MyActivityController extends IActivityController.Stub { 1127 final String mGdbPort; 1128 1129 static final int STATE_NORMAL = 0; 1130 static final int STATE_CRASHED = 1; 1131 static final int STATE_EARLY_ANR = 2; 1132 static final int STATE_ANR = 3; 1133 1134 int mState; 1135 1136 static final int RESULT_DEFAULT = 0; 1137 1138 static final int RESULT_CRASH_DIALOG = 0; 1139 static final int RESULT_CRASH_KILL = 1; 1140 1141 static final int RESULT_EARLY_ANR_CONTINUE = 0; 1142 static final int RESULT_EARLY_ANR_KILL = 1; 1143 1144 static final int RESULT_ANR_DIALOG = 0; 1145 static final int RESULT_ANR_KILL = 1; 1146 static final int RESULT_ANR_WAIT = 1; 1147 1148 int mResult; 1149 1150 Process mGdbProcess; 1151 Thread mGdbThread; 1152 boolean mGotGdbPrint; 1153 1154 MyActivityController(String gdbPort) { 1155 mGdbPort = gdbPort; 1156 } 1157 1158 @Override 1159 public boolean activityResuming(String pkg) { 1160 synchronized (this) { 1161 System.out.println("** Activity resuming: " + pkg); 1162 } 1163 return true; 1164 } 1165 1166 @Override 1167 public boolean activityStarting(Intent intent, String pkg) { 1168 synchronized (this) { 1169 System.out.println("** Activity starting: " + pkg); 1170 } 1171 return true; 1172 } 1173 1174 @Override 1175 public boolean appCrashed(String processName, int pid, String shortMsg, String longMsg, 1176 long timeMillis, String stackTrace) { 1177 synchronized (this) { 1178 System.out.println("** ERROR: PROCESS CRASHED"); 1179 System.out.println("processName: " + processName); 1180 System.out.println("processPid: " + pid); 1181 System.out.println("shortMsg: " + shortMsg); 1182 System.out.println("longMsg: " + longMsg); 1183 System.out.println("timeMillis: " + timeMillis); 1184 System.out.println("stack:"); 1185 System.out.print(stackTrace); 1186 System.out.println("#"); 1187 int result = waitControllerLocked(pid, STATE_CRASHED); 1188 return result == RESULT_CRASH_KILL ? false : true; 1189 } 1190 } 1191 1192 @Override 1193 public int appEarlyNotResponding(String processName, int pid, String annotation) { 1194 synchronized (this) { 1195 System.out.println("** ERROR: EARLY PROCESS NOT RESPONDING"); 1196 System.out.println("processName: " + processName); 1197 System.out.println("processPid: " + pid); 1198 System.out.println("annotation: " + annotation); 1199 int result = waitControllerLocked(pid, STATE_EARLY_ANR); 1200 if (result == RESULT_EARLY_ANR_KILL) return -1; 1201 return 0; 1202 } 1203 } 1204 1205 @Override 1206 public int appNotResponding(String processName, int pid, String processStats) { 1207 synchronized (this) { 1208 System.out.println("** ERROR: PROCESS NOT RESPONDING"); 1209 System.out.println("processName: " + processName); 1210 System.out.println("processPid: " + pid); 1211 System.out.println("processStats:"); 1212 System.out.print(processStats); 1213 System.out.println("#"); 1214 int result = waitControllerLocked(pid, STATE_ANR); 1215 if (result == RESULT_ANR_KILL) return -1; 1216 if (result == RESULT_ANR_WAIT) return 1; 1217 return 0; 1218 } 1219 } 1220 1221 @Override 1222 public int systemNotResponding(String message) { 1223 synchronized (this) { 1224 System.out.println("** ERROR: PROCESS NOT RESPONDING"); 1225 System.out.println("message: " + message); 1226 System.out.println("#"); 1227 System.out.println("Allowing system to die."); 1228 return -1; 1229 } 1230 } 1231 1232 void killGdbLocked() { 1233 mGotGdbPrint = false; 1234 if (mGdbProcess != null) { 1235 System.out.println("Stopping gdbserver"); 1236 mGdbProcess.destroy(); 1237 mGdbProcess = null; 1238 } 1239 if (mGdbThread != null) { 1240 mGdbThread.interrupt(); 1241 mGdbThread = null; 1242 } 1243 } 1244 1245 int waitControllerLocked(int pid, int state) { 1246 if (mGdbPort != null) { 1247 killGdbLocked(); 1248 1249 try { 1250 System.out.println("Starting gdbserver on port " + mGdbPort); 1251 System.out.println("Do the following:"); 1252 System.out.println(" adb forward tcp:" + mGdbPort + " tcp:" + mGdbPort); 1253 System.out.println(" gdbclient app_process :" + mGdbPort); 1254 1255 mGdbProcess = Runtime.getRuntime().exec(new String[] { 1256 "gdbserver", ":" + mGdbPort, "--attach", Integer.toString(pid) 1257 }); 1258 final InputStreamReader converter = new InputStreamReader( 1259 mGdbProcess.getInputStream()); 1260 mGdbThread = new Thread() { 1261 @Override 1262 public void run() { 1263 BufferedReader in = new BufferedReader(converter); 1264 String line; 1265 int count = 0; 1266 while (true) { 1267 synchronized (MyActivityController.this) { 1268 if (mGdbThread == null) { 1269 return; 1270 } 1271 if (count == 2) { 1272 mGotGdbPrint = true; 1273 MyActivityController.this.notifyAll(); 1274 } 1275 } 1276 try { 1277 line = in.readLine(); 1278 if (line == null) { 1279 return; 1280 } 1281 System.out.println("GDB: " + line); 1282 count++; 1283 } catch (IOException e) { 1284 return; 1285 } 1286 } 1287 } 1288 }; 1289 mGdbThread.start(); 1290 1291 // Stupid waiting for .5s. Doesn't matter if we end early. 1292 try { 1293 this.wait(500); 1294 } catch (InterruptedException e) { 1295 } 1296 1297 } catch (IOException e) { 1298 System.err.println("Failure starting gdbserver: " + e); 1299 killGdbLocked(); 1300 } 1301 } 1302 mState = state; 1303 System.out.println(""); 1304 printMessageForState(); 1305 1306 while (mState != STATE_NORMAL) { 1307 try { 1308 wait(); 1309 } catch (InterruptedException e) { 1310 } 1311 } 1312 1313 killGdbLocked(); 1314 1315 return mResult; 1316 } 1317 1318 void resumeController(int result) { 1319 synchronized (this) { 1320 mState = STATE_NORMAL; 1321 mResult = result; 1322 notifyAll(); 1323 } 1324 } 1325 1326 void printMessageForState() { 1327 switch (mState) { 1328 case STATE_NORMAL: 1329 System.out.println("Monitoring activity manager... available commands:"); 1330 break; 1331 case STATE_CRASHED: 1332 System.out.println("Waiting after crash... available commands:"); 1333 System.out.println("(c)ontinue: show crash dialog"); 1334 System.out.println("(k)ill: immediately kill app"); 1335 break; 1336 case STATE_EARLY_ANR: 1337 System.out.println("Waiting after early ANR... available commands:"); 1338 System.out.println("(c)ontinue: standard ANR processing"); 1339 System.out.println("(k)ill: immediately kill app"); 1340 break; 1341 case STATE_ANR: 1342 System.out.println("Waiting after ANR... available commands:"); 1343 System.out.println("(c)ontinue: show ANR dialog"); 1344 System.out.println("(k)ill: immediately kill app"); 1345 System.out.println("(w)ait: wait some more"); 1346 break; 1347 } 1348 System.out.println("(q)uit: finish monitoring"); 1349 } 1350 1351 void run() throws RemoteException { 1352 try { 1353 printMessageForState(); 1354 1355 mAm.setActivityController(this); 1356 mState = STATE_NORMAL; 1357 1358 InputStreamReader converter = new InputStreamReader(System.in); 1359 BufferedReader in = new BufferedReader(converter); 1360 String line; 1361 1362 while ((line = in.readLine()) != null) { 1363 boolean addNewline = true; 1364 if (line.length() <= 0) { 1365 addNewline = false; 1366 } else if ("q".equals(line) || "quit".equals(line)) { 1367 resumeController(RESULT_DEFAULT); 1368 break; 1369 } else if (mState == STATE_CRASHED) { 1370 if ("c".equals(line) || "continue".equals(line)) { 1371 resumeController(RESULT_CRASH_DIALOG); 1372 } else if ("k".equals(line) || "kill".equals(line)) { 1373 resumeController(RESULT_CRASH_KILL); 1374 } else { 1375 System.out.println("Invalid command: " + line); 1376 } 1377 } else if (mState == STATE_ANR) { 1378 if ("c".equals(line) || "continue".equals(line)) { 1379 resumeController(RESULT_ANR_DIALOG); 1380 } else if ("k".equals(line) || "kill".equals(line)) { 1381 resumeController(RESULT_ANR_KILL); 1382 } else if ("w".equals(line) || "wait".equals(line)) { 1383 resumeController(RESULT_ANR_WAIT); 1384 } else { 1385 System.out.println("Invalid command: " + line); 1386 } 1387 } else if (mState == STATE_EARLY_ANR) { 1388 if ("c".equals(line) || "continue".equals(line)) { 1389 resumeController(RESULT_EARLY_ANR_CONTINUE); 1390 } else if ("k".equals(line) || "kill".equals(line)) { 1391 resumeController(RESULT_EARLY_ANR_KILL); 1392 } else { 1393 System.out.println("Invalid command: " + line); 1394 } 1395 } else { 1396 System.out.println("Invalid command: " + line); 1397 } 1398 1399 synchronized (this) { 1400 if (addNewline) { 1401 System.out.println(""); 1402 } 1403 printMessageForState(); 1404 } 1405 } 1406 1407 } catch (IOException e) { 1408 e.printStackTrace(); 1409 } finally { 1410 mAm.setActivityController(null); 1411 } 1412 } 1413 } 1414 1415 private void runMonitor() throws Exception { 1416 String opt; 1417 String gdbPort = null; 1418 while ((opt=nextOption()) != null) { 1419 if (opt.equals("--gdb")) { 1420 gdbPort = nextArgRequired(); 1421 } else { 1422 System.err.println("Error: Unknown option: " + opt); 1423 return; 1424 } 1425 } 1426 1427 MyActivityController controller = new MyActivityController(gdbPort); 1428 controller.run(); 1429 } 1430 1431 private void runHang() throws Exception { 1432 String opt; 1433 boolean allowRestart = false; 1434 while ((opt=nextOption()) != null) { 1435 if (opt.equals("--allow-restart")) { 1436 allowRestart = true; 1437 } else { 1438 System.err.println("Error: Unknown option: " + opt); 1439 return; 1440 } 1441 } 1442 1443 System.out.println("Hanging the system..."); 1444 mAm.hang(new Binder(), allowRestart); 1445 } 1446 1447 private void runRestart() throws Exception { 1448 String opt; 1449 while ((opt=nextOption()) != null) { 1450 System.err.println("Error: Unknown option: " + opt); 1451 return; 1452 } 1453 1454 System.out.println("Restart the system..."); 1455 mAm.restart(); 1456 } 1457 1458 private void runIdleMaintenance() throws Exception { 1459 String opt; 1460 while ((opt=nextOption()) != null) { 1461 System.err.println("Error: Unknown option: " + opt); 1462 return; 1463 } 1464 1465 System.out.println("Performing idle maintenance..."); 1466 Intent intent = new Intent( 1467 "com.android.server.IdleMaintenanceService.action.FORCE_IDLE_MAINTENANCE"); 1468 mAm.broadcastIntent(null, intent, null, null, 0, null, null, null, 1469 android.app.AppOpsManager.OP_NONE, true, false, UserHandle.USER_ALL); 1470 } 1471 1472 private void runScreenCompat() throws Exception { 1473 String mode = nextArgRequired(); 1474 boolean enabled; 1475 if ("on".equals(mode)) { 1476 enabled = true; 1477 } else if ("off".equals(mode)) { 1478 enabled = false; 1479 } else { 1480 System.err.println("Error: enabled mode must be 'on' or 'off' at " + mode); 1481 return; 1482 } 1483 1484 String packageName = nextArgRequired(); 1485 do { 1486 try { 1487 mAm.setPackageScreenCompatMode(packageName, enabled 1488 ? ActivityManager.COMPAT_MODE_ENABLED 1489 : ActivityManager.COMPAT_MODE_DISABLED); 1490 } catch (RemoteException e) { 1491 } 1492 packageName = nextArg(); 1493 } while (packageName != null); 1494 } 1495 1496 private void runToUri(boolean intentScheme) throws Exception { 1497 Intent intent = makeIntent(UserHandle.USER_CURRENT); 1498 System.out.println(intent.toUri(intentScheme ? Intent.URI_INTENT_SCHEME : 0)); 1499 } 1500 1501 private class IntentReceiver extends IIntentReceiver.Stub { 1502 private boolean mFinished = false; 1503 1504 @Override 1505 public void performReceive(Intent intent, int resultCode, String data, Bundle extras, 1506 boolean ordered, boolean sticky, int sendingUser) { 1507 String line = "Broadcast completed: result=" + resultCode; 1508 if (data != null) line = line + ", data=\"" + data + "\""; 1509 if (extras != null) line = line + ", extras: " + extras; 1510 System.out.println(line); 1511 synchronized (this) { 1512 mFinished = true; 1513 notifyAll(); 1514 } 1515 } 1516 1517 public synchronized void waitForFinish() { 1518 try { 1519 while (!mFinished) wait(); 1520 } catch (InterruptedException e) { 1521 throw new IllegalStateException(e); 1522 } 1523 } 1524 } 1525 1526 private class InstrumentationWatcher extends IInstrumentationWatcher.Stub { 1527 private boolean mFinished = false; 1528 private boolean mRawMode = false; 1529 1530 /** 1531 * Set or reset "raw mode". In "raw mode", all bundles are dumped. In "pretty mode", 1532 * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that. 1533 * @param rawMode true for raw mode, false for pretty mode. 1534 */ 1535 public void setRawOutput(boolean rawMode) { 1536 mRawMode = rawMode; 1537 } 1538 1539 @Override 1540 public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) { 1541 synchronized (this) { 1542 // pretty printer mode? 1543 String pretty = null; 1544 if (!mRawMode && results != null) { 1545 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); 1546 } 1547 if (pretty != null) { 1548 System.out.print(pretty); 1549 } else { 1550 if (results != null) { 1551 for (String key : results.keySet()) { 1552 System.out.println( 1553 "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key)); 1554 } 1555 } 1556 System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode); 1557 } 1558 notifyAll(); 1559 } 1560 } 1561 1562 @Override 1563 public void instrumentationFinished(ComponentName name, int resultCode, 1564 Bundle results) { 1565 synchronized (this) { 1566 // pretty printer mode? 1567 String pretty = null; 1568 if (!mRawMode && results != null) { 1569 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); 1570 } 1571 if (pretty != null) { 1572 System.out.println(pretty); 1573 } else { 1574 if (results != null) { 1575 for (String key : results.keySet()) { 1576 System.out.println( 1577 "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key)); 1578 } 1579 } 1580 System.out.println("INSTRUMENTATION_CODE: " + resultCode); 1581 } 1582 mFinished = true; 1583 notifyAll(); 1584 } 1585 } 1586 1587 public boolean waitForFinish() { 1588 synchronized (this) { 1589 while (!mFinished) { 1590 try { 1591 if (!mAm.asBinder().pingBinder()) { 1592 return false; 1593 } 1594 wait(1000); 1595 } catch (InterruptedException e) { 1596 throw new IllegalStateException(e); 1597 } 1598 } 1599 } 1600 return true; 1601 } 1602 } 1603 1604 private void runStack() throws Exception { 1605 String op = nextArgRequired(); 1606 if (op.equals("start")) { 1607 runStackStart(); 1608 } else if (op.equals("movetask")) { 1609 runStackMoveTask(); 1610 } else if (op.equals("resize")) { 1611 runStackResize(); 1612 } else if (op.equals("list")) { 1613 runStackList(); 1614 } else if (op.equals("info")) { 1615 runStackInfo(); 1616 } else { 1617 showError("Error: unknown command '" + op + "'"); 1618 return; 1619 } 1620 } 1621 1622 private void runStackStart() throws Exception { 1623 String displayIdStr = nextArgRequired(); 1624 int displayId = Integer.valueOf(displayIdStr); 1625 Intent intent = makeIntent(UserHandle.USER_CURRENT); 1626 1627 try { 1628 IBinder homeActivityToken = mAm.getHomeActivityToken(); 1629 IActivityContainer container = mAm.createActivityContainer(homeActivityToken, null); 1630 container.attachToDisplay(displayId); 1631 container.startActivity(intent); 1632 } catch (RemoteException e) { 1633 } 1634 } 1635 1636 private void runStackMoveTask() throws Exception { 1637 String taskIdStr = nextArgRequired(); 1638 int taskId = Integer.valueOf(taskIdStr); 1639 String stackIdStr = nextArgRequired(); 1640 int stackId = Integer.valueOf(stackIdStr); 1641 String toTopStr = nextArgRequired(); 1642 final boolean toTop; 1643 if ("true".equals(toTopStr)) { 1644 toTop = true; 1645 } else if ("false".equals(toTopStr)) { 1646 toTop = false; 1647 } else { 1648 System.err.println("Error: bad toTop arg: " + toTopStr); 1649 return; 1650 } 1651 1652 try { 1653 mAm.moveTaskToStack(taskId, stackId, toTop); 1654 } catch (RemoteException e) { 1655 } 1656 } 1657 1658 private void runStackResize() throws Exception { 1659 String stackIdStr = nextArgRequired(); 1660 int stackId = Integer.valueOf(stackIdStr); 1661 String leftStr = nextArgRequired(); 1662 int left = Integer.valueOf(leftStr); 1663 String topStr = nextArgRequired(); 1664 int top = Integer.valueOf(topStr); 1665 String rightStr = nextArgRequired(); 1666 int right = Integer.valueOf(rightStr); 1667 String bottomStr = nextArgRequired(); 1668 int bottom = Integer.valueOf(bottomStr); 1669 1670 try { 1671 mAm.resizeStack(stackId, new Rect(left, top, right, bottom)); 1672 } catch (RemoteException e) { 1673 } 1674 } 1675 1676 private void runStackList() throws Exception { 1677 try { 1678 List<StackInfo> stacks = mAm.getAllStackInfos(); 1679 for (StackInfo info : stacks) { 1680 System.out.println(info); 1681 } 1682 } catch (RemoteException e) { 1683 } 1684 } 1685 1686 private void runStackInfo() throws Exception { 1687 try { 1688 String stackIdStr = nextArgRequired(); 1689 int stackId = Integer.valueOf(stackIdStr); 1690 StackInfo info = mAm.getStackInfo(stackId); 1691 System.out.println(info); 1692 } catch (RemoteException e) { 1693 } 1694 } 1695 1696 private void runLockTask() throws Exception { 1697 String taskIdStr = nextArgRequired(); 1698 try { 1699 if (taskIdStr.equals("stop")) { 1700 mAm.stopLockTaskMode(); 1701 } else { 1702 int taskId = Integer.valueOf(taskIdStr); 1703 mAm.startLockTaskMode(taskId); 1704 } 1705 System.err.println("Activity manager is " + (mAm.isInLockTaskMode() ? "" : "not ") + 1706 "in lockTaskMode"); 1707 } catch (RemoteException e) { 1708 } 1709 } 1710 1711 private void runGetConfig() throws Exception { 1712 try { 1713 Configuration config = mAm.getConfiguration(); 1714 if (config == null) { 1715 System.err.println("Activity manager has no configuration"); 1716 return; 1717 } 1718 1719 System.out.println("config: " + Configuration.resourceQualifierString(config)); 1720 System.out.print("abi: " + Build.CPU_ABI); 1721 if (!Build.CPU_ABI2.isEmpty()) { 1722 System.out.print("," + Build.CPU_ABI2); 1723 } 1724 System.out.println(); 1725 1726 } catch (RemoteException e) { 1727 } 1728 } 1729} 1730