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