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