Am.java revision 68d881cf2d2b252f6f795cd64d43e316a1d736e5
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.IActivityManager; 23import android.app.IInstrumentationWatcher; 24import android.app.Instrumentation; 25import android.content.ComponentName; 26import android.content.IIntentReceiver; 27import android.content.Intent; 28import android.net.Uri; 29import android.os.Bundle; 30import android.os.ParcelFileDescriptor; 31import android.os.RemoteException; 32import android.os.ServiceManager; 33import android.util.AndroidException; 34import android.view.IWindowManager; 35 36import java.io.File; 37import java.io.FileNotFoundException; 38import java.net.URISyntaxException; 39import java.util.Iterator; 40import java.util.Set; 41 42public class Am { 43 44 private IActivityManager mAm; 45 private String[] mArgs; 46 private int mNextArg; 47 private String mCurArgData; 48 49 private boolean mDebugOption = false; 50 51 // These are magic strings understood by the Eclipse plugin. 52 private static final String FATAL_ERROR_CODE = "Error type 1"; 53 private static final String NO_SYSTEM_ERROR_CODE = "Error type 2"; 54 private static final String NO_CLASS_ERROR_CODE = "Error type 3"; 55 56 /** 57 * Command-line entry point. 58 * 59 * @param args The command-line arguments 60 */ 61 public static void main(String[] args) { 62 try { 63 (new Am()).run(args); 64 } catch (IllegalArgumentException e) { 65 showUsage(); 66 System.err.println("Error: " + e.getMessage()); 67 } catch (Exception e) { 68 System.err.println(e.toString()); 69 System.exit(1); 70 } 71 } 72 73 private void run(String[] args) throws Exception { 74 if (args.length < 1) { 75 showUsage(); 76 return; 77 } 78 79 mAm = ActivityManagerNative.getDefault(); 80 if (mAm == null) { 81 System.err.println(NO_SYSTEM_ERROR_CODE); 82 throw new AndroidException("Can't connect to activity manager; is the system running?"); 83 } 84 85 mArgs = args; 86 String op = args[0]; 87 mNextArg = 1; 88 89 if (op.equals("start")) { 90 runStart(); 91 } else if (op.equals("instrument")) { 92 runInstrument(); 93 } else if (op.equals("broadcast")) { 94 sendBroadcast(); 95 } else if (op.equals("profile")) { 96 runProfile(); 97 } else { 98 throw new IllegalArgumentException("Unknown command: " + op); 99 } 100 } 101 102 private Intent makeIntent() throws URISyntaxException { 103 Intent intent = new Intent(); 104 boolean hasIntentInfo = false; 105 106 mDebugOption = false; 107 Uri data = null; 108 String type = null; 109 110 String opt; 111 while ((opt=nextOption()) != null) { 112 if (opt.equals("-a")) { 113 intent.setAction(nextArgRequired()); 114 hasIntentInfo = true; 115 } else if (opt.equals("-d")) { 116 data = Uri.parse(nextArgRequired()); 117 hasIntentInfo = true; 118 } else if (opt.equals("-t")) { 119 type = nextArgRequired(); 120 hasIntentInfo = true; 121 } else if (opt.equals("-c")) { 122 intent.addCategory(nextArgRequired()); 123 hasIntentInfo = true; 124 } else if (opt.equals("-e") || opt.equals("--es")) { 125 String key = nextArgRequired(); 126 String value = nextArgRequired(); 127 intent.putExtra(key, value); 128 hasIntentInfo = true; 129 } else if (opt.equals("--ei")) { 130 String key = nextArgRequired(); 131 String value = nextArgRequired(); 132 intent.putExtra(key, Integer.valueOf(value)); 133 hasIntentInfo = true; 134 } else if (opt.equals("--ez")) { 135 String key = nextArgRequired(); 136 String value = nextArgRequired(); 137 intent.putExtra(key, Boolean.valueOf(value)); 138 hasIntentInfo = true; 139 } else if (opt.equals("-n")) { 140 String str = nextArgRequired(); 141 ComponentName cn = ComponentName.unflattenFromString(str); 142 if (cn == null) throw new IllegalArgumentException("Bad component name: " + str); 143 intent.setComponent(cn); 144 hasIntentInfo = true; 145 } else if (opt.equals("-f")) { 146 String str = nextArgRequired(); 147 intent.setFlags(Integer.decode(str).intValue()); 148 } else if (opt.equals("-D")) { 149 mDebugOption = true; 150 } else { 151 System.err.println("Error: Unknown option: " + opt); 152 showUsage(); 153 return null; 154 } 155 } 156 intent.setDataAndType(data, type); 157 158 String uri = nextArg(); 159 if (uri != null) { 160 Intent oldIntent = intent; 161 intent = Intent.getIntent(uri); 162 if (oldIntent.getAction() != null) { 163 intent.setAction(oldIntent.getAction()); 164 } 165 if (oldIntent.getData() != null || oldIntent.getType() != null) { 166 intent.setDataAndType(oldIntent.getData(), oldIntent.getType()); 167 } 168 Set cats = oldIntent.getCategories(); 169 if (cats != null) { 170 Iterator it = cats.iterator(); 171 while (it.hasNext()) { 172 intent.addCategory((String)it.next()); 173 } 174 } 175 hasIntentInfo = true; 176 } 177 178 if (!hasIntentInfo) throw new IllegalArgumentException("No intent supplied"); 179 return intent; 180 } 181 182 private void runStart() throws Exception { 183 Intent intent = makeIntent(); 184 System.out.println("Starting: " + intent); 185 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 186 // XXX should do something to determine the MIME type. 187 int res = mAm.startActivity(null, intent, intent.getType(), 188 null, 0, null, null, 0, false, mDebugOption); 189 switch (res) { 190 case IActivityManager.START_SUCCESS: 191 break; 192 case IActivityManager.START_SWITCHES_CANCELED: 193 System.err.println( 194 "Warning: Activity not started because the " 195 + " current activity is being kept for the user."); 196 break; 197 case IActivityManager.START_DELIVERED_TO_TOP: 198 System.err.println( 199 "Warning: Activity not started, intent has " 200 + "been delivered to currently running " 201 + "top-most instance."); 202 break; 203 case IActivityManager.START_RETURN_INTENT_TO_CALLER: 204 System.err.println( 205 "Warning: Activity not started because intent " 206 + "should be handled by the caller"); 207 break; 208 case IActivityManager.START_TASK_TO_FRONT: 209 System.err.println( 210 "Warning: Activity not started, its current " 211 + "task has been brought to the front"); 212 break; 213 case IActivityManager.START_INTENT_NOT_RESOLVED: 214 System.err.println( 215 "Error: Activity not started, unable to " 216 + "resolve " + intent.toString()); 217 break; 218 case IActivityManager.START_CLASS_NOT_FOUND: 219 System.err.println(NO_CLASS_ERROR_CODE); 220 System.err.println("Error: Activity class " + 221 intent.getComponent().toShortString() 222 + " does not exist."); 223 break; 224 case IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT: 225 System.err.println( 226 "Error: Activity not started, you requested to " 227 + "both forward and receive its result"); 228 break; 229 case IActivityManager.START_PERMISSION_DENIED: 230 System.err.println( 231 "Error: Activity not started, you do not " 232 + "have permission to access it."); 233 break; 234 default: 235 System.err.println( 236 "Error: Activity not started, unknown error code " + res); 237 break; 238 } 239 } 240 241 private void sendBroadcast() throws Exception { 242 Intent intent = makeIntent(); 243 IntentReceiver receiver = new IntentReceiver(); 244 System.out.println("Broadcasting: " + intent); 245 mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, null, true, false); 246 receiver.waitForFinish(); 247 } 248 249 private void runInstrument() throws Exception { 250 String profileFile = null; 251 boolean wait = false; 252 boolean rawMode = false; 253 boolean no_window_animation = false; 254 Bundle args = new Bundle(); 255 String argKey = null, argValue = null; 256 IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window")); 257 258 String opt; 259 while ((opt=nextOption()) != null) { 260 if (opt.equals("-p")) { 261 profileFile = nextArgRequired(); 262 } else if (opt.equals("-w")) { 263 wait = true; 264 } else if (opt.equals("-r")) { 265 rawMode = true; 266 } else if (opt.equals("-e")) { 267 argKey = nextArgRequired(); 268 argValue = nextArgRequired(); 269 args.putString(argKey, argValue); 270 } else if (opt.equals("--no_window_animation")) { 271 no_window_animation = true; 272 } else { 273 System.err.println("Error: Unknown option: " + opt); 274 showUsage(); 275 return; 276 } 277 } 278 279 String cnArg = nextArgRequired(); 280 ComponentName cn = ComponentName.unflattenFromString(cnArg); 281 if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg); 282 283 InstrumentationWatcher watcher = null; 284 if (wait) { 285 watcher = new InstrumentationWatcher(); 286 watcher.setRawOutput(rawMode); 287 } 288 float[] oldAnims = null; 289 if (no_window_animation) { 290 oldAnims = wm.getAnimationScales(); 291 wm.setAnimationScale(0, 0.0f); 292 wm.setAnimationScale(1, 0.0f); 293 } 294 295 if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher)) { 296 throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString()); 297 } 298 299 if (watcher != null) { 300 if (!watcher.waitForFinish()) { 301 System.out.println("INSTRUMENTATION_ABORTED: System has crashed."); 302 } 303 } 304 305 if (oldAnims != null) { 306 wm.setAnimationScales(oldAnims); 307 } 308 } 309 310 private void runProfile() throws Exception { 311 String profileFile = null; 312 boolean start = false; 313 String process = nextArgRequired(); 314 ParcelFileDescriptor fd = null; 315 316 String cmd = nextArgRequired(); 317 if ("start".equals(cmd)) { 318 start = true; 319 profileFile = nextArgRequired(); 320 try { 321 fd = ParcelFileDescriptor.open( 322 new File(profileFile), 323 ParcelFileDescriptor.MODE_CREATE | 324 ParcelFileDescriptor.MODE_TRUNCATE | 325 ParcelFileDescriptor.MODE_READ_WRITE); 326 } catch (FileNotFoundException e) { 327 System.err.println("Error: Unable to open file: " + profileFile); 328 return; 329 } 330 } else if (!"stop".equals(cmd)) { 331 throw new IllegalArgumentException("Profile command " + cmd + " not valid"); 332 } 333 334 if (!mAm.profileControl(process, start, profileFile, fd)) { 335 throw new AndroidException("PROFILE FAILED on process " + process); 336 } 337 } 338 339 private class IntentReceiver extends IIntentReceiver.Stub { 340 private boolean mFinished = false; 341 342 public synchronized void performReceive( 343 Intent intent, int rc, String data, Bundle ext, boolean ord, 344 boolean sticky) { 345 String line = "Broadcast completed: result=" + rc; 346 if (data != null) line = line + ", data=\"" + data + "\""; 347 if (ext != null) line = line + ", extras: " + ext; 348 System.out.println(line); 349 mFinished = true; 350 notifyAll(); 351 } 352 353 public synchronized void waitForFinish() { 354 try { 355 while (!mFinished) wait(); 356 } catch (InterruptedException e) { 357 throw new IllegalStateException(e); 358 } 359 } 360 } 361 362 private class InstrumentationWatcher extends IInstrumentationWatcher.Stub { 363 private boolean mFinished = false; 364 private boolean mRawMode = false; 365 366 /** 367 * Set or reset "raw mode". In "raw mode", all bundles are dumped. In "pretty mode", 368 * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that. 369 * @param rawMode true for raw mode, false for pretty mode. 370 */ 371 public void setRawOutput(boolean rawMode) { 372 mRawMode = rawMode; 373 } 374 375 public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) { 376 synchronized (this) { 377 // pretty printer mode? 378 String pretty = null; 379 if (!mRawMode && results != null) { 380 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); 381 } 382 if (pretty != null) { 383 System.out.print(pretty); 384 } else { 385 if (results != null) { 386 for (String key : results.keySet()) { 387 System.out.println( 388 "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key)); 389 } 390 } 391 System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode); 392 } 393 notifyAll(); 394 } 395 } 396 397 public void instrumentationFinished(ComponentName name, int resultCode, 398 Bundle results) { 399 synchronized (this) { 400 // pretty printer mode? 401 String pretty = null; 402 if (!mRawMode && results != null) { 403 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); 404 } 405 if (pretty != null) { 406 System.out.println(pretty); 407 } else { 408 if (results != null) { 409 for (String key : results.keySet()) { 410 System.out.println( 411 "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key)); 412 } 413 } 414 System.out.println("INSTRUMENTATION_CODE: " + resultCode); 415 } 416 mFinished = true; 417 notifyAll(); 418 } 419 } 420 421 public boolean waitForFinish() { 422 synchronized (this) { 423 while (!mFinished) { 424 try { 425 if (!mAm.asBinder().pingBinder()) { 426 return false; 427 } 428 wait(1000); 429 } catch (InterruptedException e) { 430 throw new IllegalStateException(e); 431 } 432 } 433 } 434 return true; 435 } 436 } 437 438 private String nextOption() { 439 if (mCurArgData != null) { 440 String prev = mArgs[mNextArg - 1]; 441 throw new IllegalArgumentException("No argument expected after \"" + prev + "\""); 442 } 443 if (mNextArg >= mArgs.length) { 444 return null; 445 } 446 String arg = mArgs[mNextArg]; 447 if (!arg.startsWith("-")) { 448 return null; 449 } 450 mNextArg++; 451 if (arg.equals("--")) { 452 return null; 453 } 454 if (arg.length() > 1 && arg.charAt(1) != '-') { 455 if (arg.length() > 2) { 456 mCurArgData = arg.substring(2); 457 return arg.substring(0, 2); 458 } else { 459 mCurArgData = null; 460 return arg; 461 } 462 } 463 mCurArgData = null; 464 return arg; 465 } 466 467 private String nextArg() { 468 if (mCurArgData != null) { 469 String arg = mCurArgData; 470 mCurArgData = null; 471 return arg; 472 } else if (mNextArg < mArgs.length) { 473 return mArgs[mNextArg++]; 474 } else { 475 return null; 476 } 477 } 478 479 private String nextArgRequired() { 480 String arg = nextArg(); 481 if (arg == null) { 482 String prev = mArgs[mNextArg - 1]; 483 throw new IllegalArgumentException("Argument expected after \"" + prev + "\""); 484 } 485 return arg; 486 } 487 488 private static void showUsage() { 489 System.err.println( 490 "usage: am [subcommand] [options]\n" + 491 "\n" + 492 " start an Activity: am start [-D] <INTENT>\n" + 493 " -D: enable debugging\n" + 494 "\n" + 495 " send a broadcast Intent: am broadcast <INTENT>\n" + 496 "\n" + 497 " start an Instrumentation: am instrument [flags] <COMPONENT>\n" + 498 " -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)\n" + 499 " -e <NAME> <VALUE>: set argument <NAME> to <VALUE>\n" + 500 " -p <FILE>: write profiling data to <FILE>\n" + 501 " -w: wait for instrumentation to finish before returning\n" + 502 "\n" + 503 " start profiling: am profile <PROCESS> start <FILE>\n" + 504 " stop profiling: am profile <PROCESS> stop\n" + 505 "\n" + 506 " <INTENT> specifications include these flags:\n" + 507 " [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]\n" + 508 " [-c <CATEGORY> [-c <CATEGORY>] ...]\n" + 509 " [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]\n" + 510 " [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]\n" + 511 " [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]\n" + 512 " [-n <COMPONENT>] [-f <FLAGS>] [<URI>]\n" 513 ); 514 } 515} 516