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