Am.java revision 405e012681aa563b1d7b66c671c90ed2deb26e41
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.ActivityManagerNative; 22import android.app.IActivityController; 23import android.app.IActivityManager; 24import android.app.IInstrumentationWatcher; 25import android.app.Instrumentation; 26import android.content.ComponentName; 27import android.content.IIntentReceiver; 28import android.content.Intent; 29import android.net.Uri; 30import android.os.Bundle; 31import android.os.ParcelFileDescriptor; 32import android.os.RemoteException; 33import android.os.ServiceManager; 34import android.util.AndroidException; 35import android.view.IWindowManager; 36 37import java.io.BufferedReader; 38import java.io.File; 39import java.io.FileNotFoundException; 40import java.io.IOException; 41import java.io.InputStreamReader; 42import java.io.PrintStream; 43import java.net.URISyntaxException; 44import java.util.Iterator; 45import java.util.Set; 46 47public class Am { 48 49 private IActivityManager mAm; 50 private String[] mArgs; 51 private int mNextArg; 52 private String mCurArgData; 53 54 private boolean mDebugOption = false; 55 private boolean mWaitOption = false; 56 57 // These are magic strings understood by the Eclipse plugin. 58 private static final String FATAL_ERROR_CODE = "Error type 1"; 59 private static final String NO_SYSTEM_ERROR_CODE = "Error type 2"; 60 private static final String NO_CLASS_ERROR_CODE = "Error type 3"; 61 62 /** 63 * Command-line entry point. 64 * 65 * @param args The command-line arguments 66 */ 67 public static void main(String[] args) { 68 try { 69 (new Am()).run(args); 70 } catch (IllegalArgumentException e) { 71 showUsage(); 72 System.err.println("Error: " + e.getMessage()); 73 } catch (Exception e) { 74 System.err.println(e.toString()); 75 System.exit(1); 76 } 77 } 78 79 private void run(String[] args) throws Exception { 80 if (args.length < 1) { 81 showUsage(); 82 return; 83 } 84 85 mAm = ActivityManagerNative.getDefault(); 86 if (mAm == null) { 87 System.err.println(NO_SYSTEM_ERROR_CODE); 88 throw new AndroidException("Can't connect to activity manager; is the system running?"); 89 } 90 91 mArgs = args; 92 String op = args[0]; 93 mNextArg = 1; 94 95 if (op.equals("start")) { 96 runStart(); 97 } else if (op.equals("startservice")) { 98 runStartService(); 99 } else if (op.equals("instrument")) { 100 runInstrument(); 101 } else if (op.equals("broadcast")) { 102 sendBroadcast(); 103 } else if (op.equals("profile")) { 104 runProfile(); 105 } else if (op.equals("dumpheap")) { 106 runDumpHeap(); 107 } else if (op.equals("monitor")) { 108 runMonitor(); 109 } else { 110 throw new IllegalArgumentException("Unknown command: " + op); 111 } 112 } 113 114 private Intent makeIntent() throws URISyntaxException { 115 Intent intent = new Intent(); 116 boolean hasIntentInfo = false; 117 118 mDebugOption = false; 119 mWaitOption = false; 120 Uri data = null; 121 String type = null; 122 123 String opt; 124 while ((opt=nextOption()) != null) { 125 if (opt.equals("-a")) { 126 intent.setAction(nextArgRequired()); 127 hasIntentInfo = true; 128 } else if (opt.equals("-d")) { 129 data = Uri.parse(nextArgRequired()); 130 hasIntentInfo = true; 131 } else if (opt.equals("-t")) { 132 type = nextArgRequired(); 133 hasIntentInfo = true; 134 } else if (opt.equals("-c")) { 135 intent.addCategory(nextArgRequired()); 136 hasIntentInfo = true; 137 } else if (opt.equals("-e") || opt.equals("--es")) { 138 String key = nextArgRequired(); 139 String value = nextArgRequired(); 140 intent.putExtra(key, value); 141 hasIntentInfo = true; 142 } else if (opt.equals("--esn")) { 143 String key = nextArgRequired(); 144 intent.putExtra(key, (String) null); 145 hasIntentInfo = true; 146 } else if (opt.equals("--ei")) { 147 String key = nextArgRequired(); 148 String value = nextArgRequired(); 149 intent.putExtra(key, Integer.valueOf(value)); 150 hasIntentInfo = true; 151 } else if (opt.equals("--eia")) { 152 String key = nextArgRequired(); 153 String value = nextArgRequired(); 154 String[] strings = value.split(","); 155 int[] list = new int[strings.length]; 156 for (int i = 0; i < strings.length; i++) { 157 list[i] = Integer.valueOf(strings[i]); 158 } 159 intent.putExtra(key, list); 160 hasIntentInfo = true; 161 } else if (opt.equals("--el")) { 162 String key = nextArgRequired(); 163 String value = nextArgRequired(); 164 intent.putExtra(key, Long.valueOf(value)); 165 hasIntentInfo = true; 166 } else if (opt.equals("--ela")) { 167 String key = nextArgRequired(); 168 String value = nextArgRequired(); 169 String[] strings = value.split(","); 170 long[] list = new long[strings.length]; 171 for (int i = 0; i < strings.length; i++) { 172 list[i] = Long.valueOf(strings[i]); 173 } 174 intent.putExtra(key, list); 175 hasIntentInfo = true; 176 } else if (opt.equals("--ez")) { 177 String key = nextArgRequired(); 178 String value = nextArgRequired(); 179 intent.putExtra(key, Boolean.valueOf(value)); 180 hasIntentInfo = true; 181 } else if (opt.equals("-n")) { 182 String str = nextArgRequired(); 183 ComponentName cn = ComponentName.unflattenFromString(str); 184 if (cn == null) throw new IllegalArgumentException("Bad component name: " + str); 185 intent.setComponent(cn); 186 hasIntentInfo = true; 187 } else if (opt.equals("-f")) { 188 String str = nextArgRequired(); 189 intent.setFlags(Integer.decode(str).intValue()); 190 } else if (opt.equals("--grant-read-uri-permission")) { 191 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 192 } else if (opt.equals("--grant-write-uri-permission")) { 193 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 194 } else if (opt.equals("--debug-log-resolution")) { 195 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 196 } else if (opt.equals("--activity-brought-to-front")) { 197 intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); 198 } else if (opt.equals("--activity-clear-top")) { 199 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 200 } else if (opt.equals("--activity-clear-when-task-reset")) { 201 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); 202 } else if (opt.equals("--activity-exclude-from-recents")) { 203 intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 204 } else if (opt.equals("--activity-launched-from-history")) { 205 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY); 206 } else if (opt.equals("--activity-multiple-task")) { 207 intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); 208 } else if (opt.equals("--activity-no-animation")) { 209 intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 210 } else if (opt.equals("--activity-no-history")) { 211 intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 212 } else if (opt.equals("--activity-no-user-action")) { 213 intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION); 214 } else if (opt.equals("--activity-previous-is-top")) { 215 intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); 216 } else if (opt.equals("--activity-reorder-to-front")) { 217 intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); 218 } else if (opt.equals("--activity-reset-task-if-needed")) { 219 intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 220 } else if (opt.equals("--activity-single-top")) { 221 intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 222 } else if (opt.equals("--receiver-registered-only")) { 223 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 224 } else if (opt.equals("--receiver-replace-pending")) { 225 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 226 } else if (opt.equals("-D")) { 227 mDebugOption = true; 228 } else if (opt.equals("-W")) { 229 mWaitOption = true; 230 } else { 231 System.err.println("Error: Unknown option: " + opt); 232 showUsage(); 233 return null; 234 } 235 } 236 intent.setDataAndType(data, type); 237 238 String uri = nextArg(); 239 if (uri != null) { 240 Intent oldIntent = intent; 241 intent = Intent.parseUri(uri, 0); 242 if (oldIntent.getAction() != null) { 243 intent.setAction(oldIntent.getAction()); 244 } 245 if (oldIntent.getData() != null || oldIntent.getType() != null) { 246 intent.setDataAndType(oldIntent.getData(), oldIntent.getType()); 247 } 248 Set cats = oldIntent.getCategories(); 249 if (cats != null) { 250 Iterator it = cats.iterator(); 251 while (it.hasNext()) { 252 intent.addCategory((String)it.next()); 253 } 254 } 255 hasIntentInfo = true; 256 } 257 258 if (!hasIntentInfo) throw new IllegalArgumentException("No intent supplied"); 259 return intent; 260 } 261 262 private void runStartService() throws Exception { 263 Intent intent = makeIntent(); 264 System.out.println("Starting service: " + intent); 265 ComponentName cn = mAm.startService(null, intent, intent.getType()); 266 if (cn == null) { 267 System.err.println("Error: Not found; no service started."); 268 } 269 } 270 271 private void runStart() throws Exception { 272 Intent intent = makeIntent(); 273 System.out.println("Starting: " + intent); 274 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 275 // XXX should do something to determine the MIME type. 276 IActivityManager.WaitResult result = null; 277 int res; 278 if (mWaitOption) { 279 result = mAm.startActivityAndWait(null, intent, intent.getType(), 280 null, 0, null, null, 0, false, mDebugOption); 281 res = result.result; 282 } else { 283 res = mAm.startActivity(null, intent, intent.getType(), 284 null, 0, null, null, 0, false, mDebugOption); 285 } 286 PrintStream out = mWaitOption ? System.out : System.err; 287 boolean launched = false; 288 switch (res) { 289 case IActivityManager.START_SUCCESS: 290 launched = true; 291 break; 292 case IActivityManager.START_SWITCHES_CANCELED: 293 launched = true; 294 out.println( 295 "Warning: Activity not started because the " 296 + " current activity is being kept for the user."); 297 break; 298 case IActivityManager.START_DELIVERED_TO_TOP: 299 launched = true; 300 out.println( 301 "Warning: Activity not started, intent has " 302 + "been delivered to currently running " 303 + "top-most instance."); 304 break; 305 case IActivityManager.START_RETURN_INTENT_TO_CALLER: 306 launched = true; 307 out.println( 308 "Warning: Activity not started because intent " 309 + "should be handled by the caller"); 310 break; 311 case IActivityManager.START_TASK_TO_FRONT: 312 launched = true; 313 out.println( 314 "Warning: Activity not started, its current " 315 + "task has been brought to the front"); 316 break; 317 case IActivityManager.START_INTENT_NOT_RESOLVED: 318 out.println( 319 "Error: Activity not started, unable to " 320 + "resolve " + intent.toString()); 321 break; 322 case IActivityManager.START_CLASS_NOT_FOUND: 323 out.println(NO_CLASS_ERROR_CODE); 324 out.println("Error: Activity class " + 325 intent.getComponent().toShortString() 326 + " does not exist."); 327 break; 328 case IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT: 329 out.println( 330 "Error: Activity not started, you requested to " 331 + "both forward and receive its result"); 332 break; 333 case IActivityManager.START_PERMISSION_DENIED: 334 out.println( 335 "Error: Activity not started, you do not " 336 + "have permission to access it."); 337 break; 338 default: 339 out.println( 340 "Error: Activity not started, unknown error code " + res); 341 break; 342 } 343 if (mWaitOption && launched) { 344 if (result == null) { 345 result = new IActivityManager.WaitResult(); 346 result.who = intent.getComponent(); 347 } 348 System.out.println("Status: " + (result.timeout ? "timeout" : "ok")); 349 if (result.who != null) { 350 System.out.println("Activity: " + result.who.flattenToShortString()); 351 } 352 if (result.thisTime >= 0) { 353 System.out.println("ThisTime: " + result.thisTime); 354 } 355 if (result.totalTime >= 0) { 356 System.out.println("TotalTime: " + result.totalTime); 357 } 358 System.out.println("Complete"); 359 } 360 } 361 362 private void sendBroadcast() throws Exception { 363 Intent intent = makeIntent(); 364 IntentReceiver receiver = new IntentReceiver(); 365 System.out.println("Broadcasting: " + intent); 366 mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, null, true, false); 367 receiver.waitForFinish(); 368 } 369 370 private void runInstrument() throws Exception { 371 String profileFile = null; 372 boolean wait = false; 373 boolean rawMode = false; 374 boolean no_window_animation = false; 375 Bundle args = new Bundle(); 376 String argKey = null, argValue = null; 377 IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window")); 378 379 String opt; 380 while ((opt=nextOption()) != null) { 381 if (opt.equals("-p")) { 382 profileFile = nextArgRequired(); 383 } else if (opt.equals("-w")) { 384 wait = true; 385 } else if (opt.equals("-r")) { 386 rawMode = true; 387 } else if (opt.equals("-e")) { 388 argKey = nextArgRequired(); 389 argValue = nextArgRequired(); 390 args.putString(argKey, argValue); 391 } else if (opt.equals("--no_window_animation")) { 392 no_window_animation = true; 393 } else { 394 System.err.println("Error: Unknown option: " + opt); 395 showUsage(); 396 return; 397 } 398 } 399 400 String cnArg = nextArgRequired(); 401 ComponentName cn = ComponentName.unflattenFromString(cnArg); 402 if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg); 403 404 InstrumentationWatcher watcher = null; 405 if (wait) { 406 watcher = new InstrumentationWatcher(); 407 watcher.setRawOutput(rawMode); 408 } 409 float[] oldAnims = null; 410 if (no_window_animation) { 411 oldAnims = wm.getAnimationScales(); 412 wm.setAnimationScale(0, 0.0f); 413 wm.setAnimationScale(1, 0.0f); 414 } 415 416 if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher)) { 417 throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString()); 418 } 419 420 if (watcher != null) { 421 if (!watcher.waitForFinish()) { 422 System.out.println("INSTRUMENTATION_ABORTED: System has crashed."); 423 } 424 } 425 426 if (oldAnims != null) { 427 wm.setAnimationScales(oldAnims); 428 } 429 } 430 431 private void runProfile() throws Exception { 432 String profileFile = null; 433 boolean start = false; 434 String process = nextArgRequired(); 435 ParcelFileDescriptor fd = null; 436 437 String cmd = nextArgRequired(); 438 if ("start".equals(cmd)) { 439 start = true; 440 profileFile = nextArgRequired(); 441 try { 442 fd = ParcelFileDescriptor.open( 443 new File(profileFile), 444 ParcelFileDescriptor.MODE_CREATE | 445 ParcelFileDescriptor.MODE_TRUNCATE | 446 ParcelFileDescriptor.MODE_READ_WRITE); 447 } catch (FileNotFoundException e) { 448 System.err.println("Error: Unable to open file: " + profileFile); 449 return; 450 } 451 } else if (!"stop".equals(cmd)) { 452 throw new IllegalArgumentException("Profile command " + cmd + " not valid"); 453 } 454 455 if (!mAm.profileControl(process, start, profileFile, fd)) { 456 throw new AndroidException("PROFILE FAILED on process " + process); 457 } 458 } 459 460 private void runDumpHeap() throws Exception { 461 boolean managed = !"-n".equals(nextOption()); 462 String process = nextArgRequired(); 463 String heapFile = nextArgRequired(); 464 ParcelFileDescriptor fd = null; 465 466 try { 467 fd = ParcelFileDescriptor.open( 468 new File(heapFile), 469 ParcelFileDescriptor.MODE_CREATE | 470 ParcelFileDescriptor.MODE_TRUNCATE | 471 ParcelFileDescriptor.MODE_READ_WRITE); 472 } catch (FileNotFoundException e) { 473 System.err.println("Error: Unable to open file: " + heapFile); 474 return; 475 } 476 477 if (!mAm.dumpHeap(process, managed, heapFile, fd)) { 478 throw new AndroidException("HEAP DUMP FAILED on process " + process); 479 } 480 } 481 482 class MyActivityController extends IActivityController.Stub { 483 final String mGdbPort; 484 485 static final int STATE_NORMAL = 0; 486 static final int STATE_CRASHED = 1; 487 static final int STATE_EARLY_ANR = 2; 488 static final int STATE_ANR = 3; 489 490 int mState; 491 492 static final int RESULT_DEFAULT = 0; 493 494 static final int RESULT_CRASH_DIALOG = 0; 495 static final int RESULT_CRASH_KILL = 1; 496 497 static final int RESULT_EARLY_ANR_CONTINUE = 0; 498 static final int RESULT_EARLY_ANR_KILL = 1; 499 500 static final int RESULT_ANR_DIALOG = 0; 501 static final int RESULT_ANR_KILL = 1; 502 static final int RESULT_ANR_WAIT = 1; 503 504 int mResult; 505 506 Process mGdbProcess; 507 Thread mGdbThread; 508 boolean mGotGdbPrint; 509 510 MyActivityController(String gdbPort) { 511 mGdbPort = gdbPort; 512 } 513 514 @Override 515 public boolean activityResuming(String pkg) throws RemoteException { 516 synchronized (this) { 517 System.out.println("** Activity resuming: " + pkg); 518 } 519 return true; 520 } 521 522 @Override 523 public boolean activityStarting(Intent intent, String pkg) throws RemoteException { 524 synchronized (this) { 525 System.out.println("** Activity starting: " + pkg); 526 } 527 return true; 528 } 529 530 @Override 531 public boolean appCrashed(String processName, int pid, String shortMsg, String longMsg, 532 long timeMillis, String stackTrace) throws RemoteException { 533 synchronized (this) { 534 System.out.println("** ERROR: PROCESS CRASHED"); 535 System.out.println("processName: " + processName); 536 System.out.println("processPid: " + pid); 537 System.out.println("shortMsg: " + shortMsg); 538 System.out.println("longMsg: " + longMsg); 539 System.out.println("timeMillis: " + timeMillis); 540 System.out.println("stack:"); 541 System.out.print(stackTrace); 542 System.out.println("#"); 543 int result = waitControllerLocked(pid, STATE_CRASHED); 544 return result == RESULT_CRASH_KILL ? false : true; 545 } 546 } 547 548 @Override 549 public int appEarlyNotResponding(String processName, int pid, String annotation) 550 throws RemoteException { 551 synchronized (this) { 552 System.out.println("** ERROR: EARLY PROCESS NOT RESPONDING"); 553 System.out.println("processName: " + processName); 554 System.out.println("processPid: " + pid); 555 System.out.println("annotation: " + annotation); 556 int result = waitControllerLocked(pid, STATE_EARLY_ANR); 557 if (result == RESULT_EARLY_ANR_KILL) return -1; 558 return 0; 559 } 560 } 561 562 @Override 563 public int appNotResponding(String processName, int pid, String processStats) 564 throws RemoteException { 565 synchronized (this) { 566 System.out.println("** ERROR: PROCESS NOT RESPONDING"); 567 System.out.println("processName: " + processName); 568 System.out.println("processPid: " + pid); 569 System.out.println("processStats:"); 570 System.out.print(processStats); 571 System.out.println("#"); 572 int result = waitControllerLocked(pid, STATE_ANR); 573 if (result == RESULT_ANR_KILL) return -1; 574 if (result == RESULT_ANR_WAIT) return 1; 575 return 0; 576 } 577 } 578 579 void killGdbLocked() { 580 mGotGdbPrint = false; 581 if (mGdbProcess != null) { 582 System.out.println("Stopping gdbserver"); 583 mGdbProcess.destroy(); 584 mGdbProcess = null; 585 } 586 if (mGdbThread != null) { 587 mGdbThread.interrupt(); 588 mGdbThread = null; 589 } 590 } 591 592 int waitControllerLocked(int pid, int state) { 593 if (mGdbPort != null) { 594 killGdbLocked(); 595 596 try { 597 System.out.println("Starting gdbserver on port " + mGdbPort); 598 System.out.println("Do the following:"); 599 System.out.println(" adb forward tcp:" + mGdbPort + " tcp:" + mGdbPort); 600 System.out.println(" gdbclient app_process :" + mGdbPort); 601 602 mGdbProcess = Runtime.getRuntime().exec(new String[] { 603 "gdbserver", ":" + mGdbPort, "--attach", Integer.toString(pid) 604 }); 605 final InputStreamReader converter = new InputStreamReader( 606 mGdbProcess.getInputStream()); 607 mGdbThread = new Thread() { 608 @Override 609 public void run() { 610 BufferedReader in = new BufferedReader(converter); 611 String line; 612 int count = 0; 613 while (true) { 614 synchronized (MyActivityController.this) { 615 if (mGdbThread == null) { 616 return; 617 } 618 if (count == 2) { 619 mGotGdbPrint = true; 620 MyActivityController.this.notifyAll(); 621 } 622 } 623 try { 624 line = in.readLine(); 625 if (line == null) { 626 return; 627 } 628 System.out.println("GDB: " + line); 629 count++; 630 } catch (IOException e) { 631 return; 632 } 633 } 634 } 635 }; 636 mGdbThread.start(); 637 638 // Stupid waiting for .5s. Doesn't matter if we end early. 639 try { 640 this.wait(500); 641 } catch (InterruptedException e) { 642 } 643 644 } catch (IOException e) { 645 System.err.println("Failure starting gdbserver: " + e); 646 killGdbLocked(); 647 } 648 } 649 mState = state; 650 System.out.println(""); 651 printMessageForState(); 652 653 while (mState != STATE_NORMAL) { 654 try { 655 wait(); 656 } catch (InterruptedException e) { 657 } 658 } 659 660 killGdbLocked(); 661 662 return mResult; 663 } 664 665 void resumeController(int result) { 666 synchronized (this) { 667 mState = STATE_NORMAL; 668 mResult = result; 669 notifyAll(); 670 } 671 } 672 673 void printMessageForState() { 674 switch (mState) { 675 case STATE_NORMAL: 676 System.out.println("Monitoring activity manager... available commands:"); 677 break; 678 case STATE_CRASHED: 679 System.out.println("Waiting after crash... available commands:"); 680 System.out.println("(c)ontinue: show crash dialog"); 681 System.out.println("(k)ill: immediately kill app"); 682 break; 683 case STATE_EARLY_ANR: 684 System.out.println("Waiting after early ANR... available commands:"); 685 System.out.println("(c)ontinue: standard ANR processing"); 686 System.out.println("(k)ill: immediately kill app"); 687 break; 688 case STATE_ANR: 689 System.out.println("Waiting after ANR... available commands:"); 690 System.out.println("(c)ontinue: show ANR dialog"); 691 System.out.println("(k)ill: immediately kill app"); 692 System.out.println("(w)ait: wait some more"); 693 break; 694 } 695 System.out.println("(q)uit: finish monitoring"); 696 } 697 698 void run() throws RemoteException { 699 try { 700 printMessageForState(); 701 702 mAm.setActivityController(this); 703 mState = STATE_NORMAL; 704 705 InputStreamReader converter = new InputStreamReader(System.in); 706 BufferedReader in = new BufferedReader(converter); 707 String line; 708 709 while ((line = in.readLine()) != null) { 710 boolean addNewline = true; 711 if (line.length() <= 0) { 712 addNewline = false; 713 } else if ("q".equals(line) || "quit".equals(line)) { 714 resumeController(RESULT_DEFAULT); 715 break; 716 } else if (mState == STATE_CRASHED) { 717 if ("c".equals(line) || "continue".equals(line)) { 718 resumeController(RESULT_CRASH_DIALOG); 719 } else if ("k".equals(line) || "kill".equals(line)) { 720 resumeController(RESULT_CRASH_KILL); 721 } else { 722 System.out.println("Invalid command: " + line); 723 } 724 } else if (mState == STATE_ANR) { 725 if ("c".equals(line) || "continue".equals(line)) { 726 resumeController(RESULT_ANR_DIALOG); 727 } else if ("k".equals(line) || "kill".equals(line)) { 728 resumeController(RESULT_ANR_KILL); 729 } else if ("w".equals(line) || "wait".equals(line)) { 730 resumeController(RESULT_ANR_WAIT); 731 } else { 732 System.out.println("Invalid command: " + line); 733 } 734 } else if (mState == STATE_EARLY_ANR) { 735 if ("c".equals(line) || "continue".equals(line)) { 736 resumeController(RESULT_EARLY_ANR_CONTINUE); 737 } else if ("k".equals(line) || "kill".equals(line)) { 738 resumeController(RESULT_EARLY_ANR_KILL); 739 } else { 740 System.out.println("Invalid command: " + line); 741 } 742 } else { 743 System.out.println("Invalid command: " + line); 744 } 745 746 synchronized (this) { 747 if (addNewline) { 748 System.out.println(""); 749 } 750 printMessageForState(); 751 } 752 } 753 754 } catch (IOException e) { 755 e.printStackTrace(); 756 } finally { 757 mAm.setActivityController(null); 758 } 759 } 760 } 761 762 private void runMonitor() throws Exception { 763 String opt; 764 String gdbPort = null; 765 while ((opt=nextOption()) != null) { 766 if (opt.equals("--gdb")) { 767 gdbPort = nextArgRequired(); 768 } else { 769 System.err.println("Error: Unknown option: " + opt); 770 showUsage(); 771 return; 772 } 773 } 774 775 MyActivityController controller = new MyActivityController(gdbPort); 776 controller.run(); 777 } 778 779 private class IntentReceiver extends IIntentReceiver.Stub { 780 private boolean mFinished = false; 781 782 public synchronized void performReceive( 783 Intent intent, int rc, String data, Bundle ext, boolean ord, 784 boolean sticky) { 785 String line = "Broadcast completed: result=" + rc; 786 if (data != null) line = line + ", data=\"" + data + "\""; 787 if (ext != null) line = line + ", extras: " + ext; 788 System.out.println(line); 789 mFinished = true; 790 notifyAll(); 791 } 792 793 public synchronized void waitForFinish() { 794 try { 795 while (!mFinished) wait(); 796 } catch (InterruptedException e) { 797 throw new IllegalStateException(e); 798 } 799 } 800 } 801 802 private class InstrumentationWatcher extends IInstrumentationWatcher.Stub { 803 private boolean mFinished = false; 804 private boolean mRawMode = false; 805 806 /** 807 * Set or reset "raw mode". In "raw mode", all bundles are dumped. In "pretty mode", 808 * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that. 809 * @param rawMode true for raw mode, false for pretty mode. 810 */ 811 public void setRawOutput(boolean rawMode) { 812 mRawMode = rawMode; 813 } 814 815 public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) { 816 synchronized (this) { 817 // pretty printer mode? 818 String pretty = null; 819 if (!mRawMode && results != null) { 820 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); 821 } 822 if (pretty != null) { 823 System.out.print(pretty); 824 } else { 825 if (results != null) { 826 for (String key : results.keySet()) { 827 System.out.println( 828 "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key)); 829 } 830 } 831 System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode); 832 } 833 notifyAll(); 834 } 835 } 836 837 public void instrumentationFinished(ComponentName name, int resultCode, 838 Bundle results) { 839 synchronized (this) { 840 // pretty printer mode? 841 String pretty = null; 842 if (!mRawMode && results != null) { 843 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); 844 } 845 if (pretty != null) { 846 System.out.println(pretty); 847 } else { 848 if (results != null) { 849 for (String key : results.keySet()) { 850 System.out.println( 851 "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key)); 852 } 853 } 854 System.out.println("INSTRUMENTATION_CODE: " + resultCode); 855 } 856 mFinished = true; 857 notifyAll(); 858 } 859 } 860 861 public boolean waitForFinish() { 862 synchronized (this) { 863 while (!mFinished) { 864 try { 865 if (!mAm.asBinder().pingBinder()) { 866 return false; 867 } 868 wait(1000); 869 } catch (InterruptedException e) { 870 throw new IllegalStateException(e); 871 } 872 } 873 } 874 return true; 875 } 876 } 877 878 private String nextOption() { 879 if (mCurArgData != null) { 880 String prev = mArgs[mNextArg - 1]; 881 throw new IllegalArgumentException("No argument expected after \"" + prev + "\""); 882 } 883 if (mNextArg >= mArgs.length) { 884 return null; 885 } 886 String arg = mArgs[mNextArg]; 887 if (!arg.startsWith("-")) { 888 return null; 889 } 890 mNextArg++; 891 if (arg.equals("--")) { 892 return null; 893 } 894 if (arg.length() > 1 && arg.charAt(1) != '-') { 895 if (arg.length() > 2) { 896 mCurArgData = arg.substring(2); 897 return arg.substring(0, 2); 898 } else { 899 mCurArgData = null; 900 return arg; 901 } 902 } 903 mCurArgData = null; 904 return arg; 905 } 906 907 private String nextArg() { 908 if (mCurArgData != null) { 909 String arg = mCurArgData; 910 mCurArgData = null; 911 return arg; 912 } else if (mNextArg < mArgs.length) { 913 return mArgs[mNextArg++]; 914 } else { 915 return null; 916 } 917 } 918 919 private String nextArgRequired() { 920 String arg = nextArg(); 921 if (arg == null) { 922 String prev = mArgs[mNextArg - 1]; 923 throw new IllegalArgumentException("Argument expected after \"" + prev + "\""); 924 } 925 return arg; 926 } 927 928 private static void showUsage() { 929 System.err.println( 930 "usage: am [subcommand] [options]\n" + 931 "\n" + 932 " start an Activity: am start [-D] [-W] <INTENT>\n" + 933 " -D: enable debugging\n" + 934 " -W: wait for launch to complete\n" + 935 "\n" + 936 " start a Service: am startservice <INTENT>\n" + 937 "\n" + 938 " send a broadcast Intent: am broadcast <INTENT>\n" + 939 "\n" + 940 " start an Instrumentation: am instrument [flags] <COMPONENT>\n" + 941 " -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)\n" + 942 " -e <NAME> <VALUE>: set argument <NAME> to <VALUE>\n" + 943 " -p <FILE>: write profiling data to <FILE>\n" + 944 " -w: wait for instrumentation to finish before returning\n" + 945 "\n" + 946 " run a test package against an application: am instrument [flags] <TEST_PACKAGE>/<RUNNER_CLASS>\n" + 947 " -e <testrunner_flag> <testrunner_value> [,<testrunner_value>]\n" + 948 " -w wait for the test to finish (required)\n" + 949 " -r use with -e perf true to generate raw output for performance measurements\n" + 950 "\n" + 951 " start profiling: am profile <PROCESS> start <FILE>\n" + 952 " stop profiling: am profile <PROCESS> stop\n" + 953 " dump heap: am dumpheap [flags] <PROCESS> <FILE>\n" + 954 " -n: dump native heap instead of managed heap\n" + 955 "\n" + 956 " start monitoring: am monitor [--gdb <port>]\n" + 957 " --gdb: start gdbserv on the given port at crash/ANR\n" + 958 "\n" + 959 " <INTENT> specifications include these flags:\n" + 960 " [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]\n" + 961 " [-c <CATEGORY> [-c <CATEGORY>] ...]\n" + 962 " [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]\n" + 963 " [--esn <EXTRA_KEY> ...]\n" + 964 " [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]\n" + 965 " [--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]\n" + 966 " [--el <EXTRA_KEY> <EXTRA_LONG_VALUE> ...]\n" + 967 " [--eia <EXTRA_KEY> <EXTRA_INT_VALUE>[,<EXTRA_INT_VALUE...]]\n" + 968 " [--ela <EXTRA_KEY> <EXTRA_LONG_VALUE>[,<EXTRA_LONG_VALUE...]]\n" + 969 " [-n <COMPONENT>] [-f <FLAGS>]\n" + 970 " [--grant-read-uri-permission] [--grant-write-uri-permission]\n" + 971 " [--debug-log-resolution]\n" + 972 " [--activity-brought-to-front] [--activity-clear-top]\n" + 973 " [--activity-clear-when-task-reset] [--activity-exclude-from-recents]\n" + 974 " [--activity-launched-from-history] [--activity-multiple-task]\n" + 975 " [--activity-no-animation] [--activity-no-history]\n" + 976 " [--activity-no-user-action] [--activity-previous-is-top]\n" + 977 " [--activity-reorder-to-front] [--activity-reset-task-if-needed]\n" + 978 " [--activity-single-top]\n" + 979 " [--receiver-registered-only] [--receiver-replace-pending]\n" + 980 " [<URI>]\n" 981 ); 982 } 983} 984