Am.java revision cf76872a62075abf9008e99ca08413fb70761dc2
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.ActivityManager.StackInfo; 23import android.app.ActivityManagerNative; 24import android.app.IActivityContainer; 25import android.app.IActivityController; 26import android.app.IActivityManager; 27import android.app.IInstrumentationWatcher; 28import android.app.Instrumentation; 29import android.app.ProfilerInfo; 30import android.app.UiAutomationConnection; 31import android.app.usage.ConfigurationStats; 32import android.app.usage.IUsageStatsManager; 33import android.app.usage.UsageStatsManager; 34import android.content.ComponentName; 35import android.content.Context; 36import android.content.IIntentReceiver; 37import android.content.Intent; 38import android.content.pm.IPackageManager; 39import android.content.pm.ParceledListSlice; 40import android.content.pm.ResolveInfo; 41import android.content.res.Configuration; 42import android.graphics.Rect; 43import android.net.Uri; 44import android.os.Binder; 45import android.os.Build; 46import android.os.Bundle; 47import android.os.ParcelFileDescriptor; 48import android.os.RemoteException; 49import android.os.SELinux; 50import android.os.ServiceManager; 51import android.os.SystemClock; 52import android.os.SystemProperties; 53import android.os.UserHandle; 54import android.text.TextUtils; 55import android.util.AndroidException; 56import android.util.ArrayMap; 57import android.view.IWindowManager; 58 59import com.android.internal.os.BaseCommand; 60 61import java.io.BufferedReader; 62import java.io.File; 63import java.io.FileNotFoundException; 64import java.io.IOException; 65import java.io.InputStreamReader; 66import java.io.PrintStream; 67import java.net.URISyntaxException; 68import java.util.ArrayList; 69import java.util.Collections; 70import java.util.Comparator; 71import java.util.HashSet; 72import java.util.List; 73 74public class Am extends BaseCommand { 75 76 private IActivityManager mAm; 77 78 private int mStartFlags = 0; 79 private boolean mWaitOption = false; 80 private boolean mStopOption = false; 81 82 private int mRepeat = 0; 83 private int mUserId; 84 private String mReceiverPermission; 85 86 private String mProfileFile; 87 private int mSamplingInterval; 88 private boolean mAutoStop; 89 90 /** 91 * Command-line entry point. 92 * 93 * @param args The command-line arguments 94 */ 95 public static void main(String[] args) { 96 (new Am()).run(args); 97 } 98 99 @Override 100 public void onShowUsage(PrintStream out) { 101 out.println( 102 "usage: am [subcommand] [options]\n" + 103 "usage: am start [-D] [-W] [-P <FILE>] [--start-profiler <FILE>]\n" + 104 " [--sampling INTERVAL] [-R COUNT] [-S] [--opengl-trace]\n" + 105 " [--user <USER_ID> | current] <INTENT>\n" + 106 " am startservice [--user <USER_ID> | current] <INTENT>\n" + 107 " am stopservice [--user <USER_ID> | current] <INTENT>\n" + 108 " am force-stop [--user <USER_ID> | all | current] <PACKAGE>\n" + 109 " am kill [--user <USER_ID> | all | current] <PACKAGE>\n" + 110 " am kill-all\n" + 111 " am broadcast [--user <USER_ID> | all | current] <INTENT>\n" + 112 " am instrument [-r] [-e <NAME> <VALUE>] [-p <FILE>] [-w]\n" + 113 " [--user <USER_ID> | current]\n" + 114 " [--no-window-animation] [--abi <ABI>] <COMPONENT>\n" + 115 " am profile start [--user <USER_ID> current] [--sampling INTERVAL] <PROCESS> <FILE>\n" + 116 " am profile stop [--user <USER_ID> current] [<PROCESS>]\n" + 117 " am dumpheap [--user <USER_ID> current] [-n] <PROCESS> <FILE>\n" + 118 " am set-debug-app [-w] [--persistent] <PACKAGE>\n" + 119 " am clear-debug-app\n" + 120 " am set-watch-heap <PROCESS> <MEM-LIMIT>\n" + 121 " am clear-watch-heap\n" + 122 " am monitor [--gdb <port>]\n" + 123 " am hang [--allow-restart]\n" + 124 " am restart\n" + 125 " am idle-maintenance\n" + 126 " am screen-compat [on|off] <PACKAGE>\n" + 127 " am package-importance <PACKAGE>\n" + 128 " am to-uri [INTENT]\n" + 129 " am to-intent-uri [INTENT]\n" + 130 " am to-app-uri [INTENT]\n" + 131 " am switch-user <USER_ID>\n" + 132 " am start-user <USER_ID>\n" + 133 " am stop-user <USER_ID>\n" + 134 " am stack start <DISPLAY_ID> <INTENT>\n" + 135 " am stack movetask <TASK_ID> <STACK_ID> [true|false]\n" + 136 " am stack resize <STACK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" + 137 " am stack split <STACK_ID> <v|h> [INTENT]\n" + 138 " am stack list\n" + 139 " am stack info <STACK_ID>\n" + 140 " am task lock <TASK_ID>\n" + 141 " am task lock stop\n" + 142 " am task resizeable <TASK_ID> [true|false]\n" + 143 " am task resize <TASK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" + 144 " am get-config\n" + 145 " am set-idle [--user <USER_ID>] <PACKAGE> true|false\n" + 146 " am get-idle [--user <USER_ID>] <PACKAGE>\n" + 147 "\n" + 148 "am start: start an Activity. Options are:\n" + 149 " -D: enable debugging\n" + 150 " -W: wait for launch to complete\n" + 151 " --start-profiler <FILE>: start profiler and send results to <FILE>\n" + 152 " --sampling INTERVAL: use sample profiling with INTERVAL microseconds\n" + 153 " between samples (use with --start-profiler)\n" + 154 " -P <FILE>: like above, but profiling stops when app goes idle\n" + 155 " -R: repeat the activity launch <COUNT> times. Prior to each repeat,\n" + 156 " the top activity will be finished.\n" + 157 " -S: force stop the target app before starting the activity\n" + 158 " --opengl-trace: enable tracing of OpenGL functions\n" + 159 " --user <USER_ID> | current: Specify which user to run as; if not\n" + 160 " specified then run as the current user.\n" + 161 "\n" + 162 "am startservice: start a Service. Options are:\n" + 163 " --user <USER_ID> | current: Specify which user to run as; if not\n" + 164 " specified then run as the current user.\n" + 165 "\n" + 166 "am stopservice: stop a Service. Options are:\n" + 167 " --user <USER_ID> | current: Specify which user to run as; if not\n" + 168 " specified then run as the current user.\n" + 169 "\n" + 170 "am force-stop: force stop everything associated with <PACKAGE>.\n" + 171 " --user <USER_ID> | all | current: Specify user to force stop;\n" + 172 " all users if not specified.\n" + 173 "\n" + 174 "am kill: Kill all processes associated with <PACKAGE>. Only kills.\n" + 175 " processes that are safe to kill -- that is, will not impact the user\n" + 176 " experience.\n" + 177 " --user <USER_ID> | all | current: Specify user whose processes to kill;\n" + 178 " all users if not specified.\n" + 179 "\n" + 180 "am kill-all: Kill all background processes.\n" + 181 "\n" + 182 "am broadcast: send a broadcast Intent. Options are:\n" + 183 " --user <USER_ID> | all | current: Specify which user to send to; if not\n" + 184 " specified then send to all users.\n" + 185 " --receiver-permission <PERMISSION>: Require receiver to hold permission.\n" + 186 "\n" + 187 "am instrument: start an Instrumentation. Typically this target <COMPONENT>\n" + 188 " is the form <TEST_PACKAGE>/<RUNNER_CLASS>. Options are:\n" + 189 " -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT). Use with\n" + 190 " [-e perf true] to generate raw output for performance measurements.\n" + 191 " -e <NAME> <VALUE>: set argument <NAME> to <VALUE>. For test runners a\n" + 192 " common form is [-e <testrunner_flag> <value>[,<value>...]].\n" + 193 " -p <FILE>: write profiling data to <FILE>\n" + 194 " -w: wait for instrumentation to finish before returning. Required for\n" + 195 " test runners.\n" + 196 " --user <USER_ID> | current: Specify user instrumentation runs in;\n" + 197 " current user if not specified.\n" + 198 " --no-window-animation: turn off window animations while running.\n" + 199 " --abi <ABI>: Launch the instrumented process with the selected ABI.\n" + 200 " This assumes that the process supports the selected ABI.\n" + 201 "\n" + 202 "am profile: start and stop profiler on a process. The given <PROCESS> argument\n" + 203 " may be either a process name or pid. Options are:\n" + 204 " --user <USER_ID> | current: When supplying a process name,\n" + 205 " specify user of process to profile; uses current user if not specified.\n" + 206 "\n" + 207 "am dumpheap: dump the heap of a process. The given <PROCESS> argument may\n" + 208 " be either a process name or pid. Options are:\n" + 209 " -n: dump native heap instead of managed heap\n" + 210 " --user <USER_ID> | current: When supplying a process name,\n" + 211 " specify user of process to dump; uses current user if not specified.\n" + 212 "\n" + 213 "am set-debug-app: set application <PACKAGE> to debug. Options are:\n" + 214 " -w: wait for debugger when application starts\n" + 215 " --persistent: retain this value\n" + 216 "\n" + 217 "am clear-debug-app: clear the previously set-debug-app.\n" + 218 "\n" + 219 "am set-watch-heap: start monitoring pss size of <PROCESS>, if it is at or\n" + 220 " above <HEAP-LIMIT> then a heap dump is collected for the user to report\n" + 221 "\n" + 222 "am clear-watch-heap: clear the previously set-watch-heap.\n" + 223 "\n" + 224 "am bug-report: request bug report generation; will launch UI\n" + 225 " when done to select where it should be delivered.\n" + 226 "\n" + 227 "am monitor: start monitoring for crashes or ANRs.\n" + 228 " --gdb: start gdbserv on the given port at crash/ANR\n" + 229 "\n" + 230 "am hang: hang the system.\n" + 231 " --allow-restart: allow watchdog to perform normal system restart\n" + 232 "\n" + 233 "am restart: restart the user-space system.\n" + 234 "\n" + 235 "am idle-maintenance: perform idle maintenance now.\n" + 236 "\n" + 237 "am screen-compat: control screen compatibility mode of <PACKAGE>.\n" + 238 "\n" + 239 "am package-importance: print current importance of <PACKAGE>.\n" + 240 "\n" + 241 "am to-uri: print the given Intent specification as a URI.\n" + 242 "\n" + 243 "am to-intent-uri: print the given Intent specification as an intent: URI.\n" + 244 "\n" + 245 "am to-app-uri: print the given Intent specification as an android-app: URI.\n" + 246 "\n" + 247 "am switch-user: switch to put USER_ID in the foreground, starting\n" + 248 " execution of that user if it is currently stopped.\n" + 249 "\n" + 250 "am start-user: start USER_ID in background if it is currently stopped,\n" + 251 " use switch-user if you want to start the user in foreground.\n" + 252 "\n" + 253 "am stop-user: stop execution of USER_ID, not allowing it to run any\n" + 254 " code until a later explicit start or switch to it.\n" + 255 "\n" + 256 "am stack start: start a new activity on <DISPLAY_ID> using <INTENT>.\n" + 257 "\n" + 258 "am stack movetask: move <TASK_ID> from its current stack to the top (true) or" + 259 " bottom (false) of <STACK_ID>.\n" + 260 "\n" + 261 "am stack resize: change <STACK_ID> size and position to <LEFT,TOP,RIGHT,BOTTOM>" + 262 ".\n" + 263 "\n" + 264 "am stack split: split <STACK_ID> into 2 stacks <v>ertically or <h>orizontally\n" + 265 " starting the new stack with [INTENT] if specified. If [INTENT] isn't\n" + 266 " specified and the current stack has more than one task, then the top task\n" + 267 " of the current task will be moved to the new stack. Command will also force\n" + 268 " all current tasks in both stacks to be resizeable.\n" + 269 "\n" + 270 "am stack list: list all of the activity stacks and their sizes.\n" + 271 "\n" + 272 "am stack info: display the information about activity stack <STACK_ID>.\n" + 273 "\n" + 274 "am task lock: bring <TASK_ID> to the front and don't allow other tasks to run\n" + 275 "\n" + 276 "am task lock stop: end the current task lock\n" + 277 "\n" + 278 "am task resizeable: change if <TASK_ID> is resizeable (true) or not (false).\n" + 279 "\n" + 280 "am task resize: makes sure <TASK_ID> is in a stack with the specified bounds.\n" + 281 " Forces the task to be resizeable and creates a stack if no existing stack\n" + 282 " has the specified bounds.\n" + 283 "\n" + 284 "am get-config: retrieve the configuration and any recent configurations\n" + 285 " of the device\n" + 286 "\n" + 287 "am set-idle: sets the idle state of an app\n" + 288 "\n" + 289 "am get-idle: returns the idle state of an app\n" + 290 "\n" + 291 "\n" + 292 "<INTENT> specifications include these flags and arguments:\n" + 293 " [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]\n" + 294 " [-c <CATEGORY> [-c <CATEGORY>] ...]\n" + 295 " [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]\n" + 296 " [--esn <EXTRA_KEY> ...]\n" + 297 " [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]\n" + 298 " [--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]\n" + 299 " [--el <EXTRA_KEY> <EXTRA_LONG_VALUE> ...]\n" + 300 " [--ef <EXTRA_KEY> <EXTRA_FLOAT_VALUE> ...]\n" + 301 " [--eu <EXTRA_KEY> <EXTRA_URI_VALUE> ...]\n" + 302 " [--ecn <EXTRA_KEY> <EXTRA_COMPONENT_NAME_VALUE>]\n" + 303 " [--eia <EXTRA_KEY> <EXTRA_INT_VALUE>[,<EXTRA_INT_VALUE...]]\n" + 304 " [--ela <EXTRA_KEY> <EXTRA_LONG_VALUE>[,<EXTRA_LONG_VALUE...]]\n" + 305 " [--efa <EXTRA_KEY> <EXTRA_FLOAT_VALUE>[,<EXTRA_FLOAT_VALUE...]]\n" + 306 " [--esa <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]\n" + 307 " (to embed a comma into a string escape it using \"\\,\")\n" + 308 " [-n <COMPONENT>] [-p <PACKAGE>] [-f <FLAGS>]\n" + 309 " [--grant-read-uri-permission] [--grant-write-uri-permission]\n" + 310 " [--grant-persistable-uri-permission] [--grant-prefix-uri-permission]\n" + 311 " [--debug-log-resolution] [--exclude-stopped-packages]\n" + 312 " [--include-stopped-packages]\n" + 313 " [--activity-brought-to-front] [--activity-clear-top]\n" + 314 " [--activity-clear-when-task-reset] [--activity-exclude-from-recents]\n" + 315 " [--activity-launched-from-history] [--activity-multiple-task]\n" + 316 " [--activity-no-animation] [--activity-no-history]\n" + 317 " [--activity-no-user-action] [--activity-previous-is-top]\n" + 318 " [--activity-reorder-to-front] [--activity-reset-task-if-needed]\n" + 319 " [--activity-single-top] [--activity-clear-task]\n" + 320 " [--activity-task-on-home]\n" + 321 " [--receiver-registered-only] [--receiver-replace-pending]\n" + 322 " [--selector]\n" + 323 " [<URI> | <PACKAGE> | <COMPONENT>]\n" 324 ); 325 } 326 327 @Override 328 public void onRun() throws Exception { 329 330 mAm = ActivityManagerNative.getDefault(); 331 if (mAm == null) { 332 System.err.println(NO_SYSTEM_ERROR_CODE); 333 throw new AndroidException("Can't connect to activity manager; is the system running?"); 334 } 335 336 String op = nextArgRequired(); 337 338 if (op.equals("start")) { 339 runStart(); 340 } else if (op.equals("startservice")) { 341 runStartService(); 342 } else if (op.equals("stopservice")) { 343 runStopService(); 344 } else if (op.equals("force-stop")) { 345 runForceStop(); 346 } else if (op.equals("kill")) { 347 runKill(); 348 } else if (op.equals("kill-all")) { 349 runKillAll(); 350 } else if (op.equals("instrument")) { 351 runInstrument(); 352 } else if (op.equals("broadcast")) { 353 sendBroadcast(); 354 } else if (op.equals("profile")) { 355 runProfile(); 356 } else if (op.equals("dumpheap")) { 357 runDumpHeap(); 358 } else if (op.equals("set-debug-app")) { 359 runSetDebugApp(); 360 } else if (op.equals("clear-debug-app")) { 361 runClearDebugApp(); 362 } else if (op.equals("set-watch-heap")) { 363 runSetWatchHeap(); 364 } else if (op.equals("clear-watch-heap")) { 365 runClearWatchHeap(); 366 } else if (op.equals("bug-report")) { 367 runBugReport(); 368 } else if (op.equals("monitor")) { 369 runMonitor(); 370 } else if (op.equals("hang")) { 371 runHang(); 372 } else if (op.equals("restart")) { 373 runRestart(); 374 } else if (op.equals("idle-maintenance")) { 375 runIdleMaintenance(); 376 } else if (op.equals("screen-compat")) { 377 runScreenCompat(); 378 } else if (op.equals("package-importance")) { 379 runPackageImportance(); 380 } else if (op.equals("to-uri")) { 381 runToUri(0); 382 } else if (op.equals("to-intent-uri")) { 383 runToUri(Intent.URI_INTENT_SCHEME); 384 } else if (op.equals("to-app-uri")) { 385 runToUri(Intent.URI_ANDROID_APP_SCHEME); 386 } else if (op.equals("switch-user")) { 387 runSwitchUser(); 388 } else if (op.equals("start-user")) { 389 runStartUserInBackground(); 390 } else if (op.equals("stop-user")) { 391 runStopUser(); 392 } else if (op.equals("stack")) { 393 runStack(); 394 } else if (op.equals("task")) { 395 runTask(); 396 } else if (op.equals("get-config")) { 397 runGetConfig(); 398 } else if (op.equals("set-idle")) { 399 runSetIdle(); 400 } else if (op.equals("get-idle")) { 401 runGetIdle(); 402 } else { 403 showError("Error: unknown command '" + op + "'"); 404 } 405 } 406 407 int parseUserArg(String arg) { 408 int userId; 409 if ("all".equals(arg)) { 410 userId = UserHandle.USER_ALL; 411 } else if ("current".equals(arg) || "cur".equals(arg)) { 412 userId = UserHandle.USER_CURRENT; 413 } else { 414 userId = Integer.parseInt(arg); 415 } 416 return userId; 417 } 418 419 private Intent makeIntent(int defUser) throws URISyntaxException { 420 Intent intent = new Intent(); 421 Intent baseIntent = intent; 422 boolean hasIntentInfo = false; 423 424 mStartFlags = 0; 425 mWaitOption = false; 426 mStopOption = false; 427 mRepeat = 0; 428 mProfileFile = null; 429 mSamplingInterval = 0; 430 mAutoStop = false; 431 mUserId = defUser; 432 Uri data = null; 433 String type = null; 434 435 String opt; 436 while ((opt=nextOption()) != null) { 437 if (opt.equals("-a")) { 438 intent.setAction(nextArgRequired()); 439 if (intent == baseIntent) { 440 hasIntentInfo = true; 441 } 442 } else if (opt.equals("-d")) { 443 data = Uri.parse(nextArgRequired()); 444 if (intent == baseIntent) { 445 hasIntentInfo = true; 446 } 447 } else if (opt.equals("-t")) { 448 type = nextArgRequired(); 449 if (intent == baseIntent) { 450 hasIntentInfo = true; 451 } 452 } else if (opt.equals("-c")) { 453 intent.addCategory(nextArgRequired()); 454 if (intent == baseIntent) { 455 hasIntentInfo = true; 456 } 457 } else if (opt.equals("-e") || opt.equals("--es")) { 458 String key = nextArgRequired(); 459 String value = nextArgRequired(); 460 intent.putExtra(key, value); 461 } else if (opt.equals("--esn")) { 462 String key = nextArgRequired(); 463 intent.putExtra(key, (String) null); 464 } else if (opt.equals("--ei")) { 465 String key = nextArgRequired(); 466 String value = nextArgRequired(); 467 intent.putExtra(key, Integer.decode(value)); 468 } else if (opt.equals("--eu")) { 469 String key = nextArgRequired(); 470 String value = nextArgRequired(); 471 intent.putExtra(key, Uri.parse(value)); 472 } else if (opt.equals("--ecn")) { 473 String key = nextArgRequired(); 474 String value = nextArgRequired(); 475 ComponentName cn = ComponentName.unflattenFromString(value); 476 if (cn == null) throw new IllegalArgumentException("Bad component name: " + value); 477 intent.putExtra(key, cn); 478 } else if (opt.equals("--eia")) { 479 String key = nextArgRequired(); 480 String value = nextArgRequired(); 481 String[] strings = value.split(","); 482 int[] list = new int[strings.length]; 483 for (int i = 0; i < strings.length; i++) { 484 list[i] = Integer.decode(strings[i]); 485 } 486 intent.putExtra(key, list); 487 } else if (opt.equals("--el")) { 488 String key = nextArgRequired(); 489 String value = nextArgRequired(); 490 intent.putExtra(key, Long.valueOf(value)); 491 } else if (opt.equals("--ela")) { 492 String key = nextArgRequired(); 493 String value = nextArgRequired(); 494 String[] strings = value.split(","); 495 long[] list = new long[strings.length]; 496 for (int i = 0; i < strings.length; i++) { 497 list[i] = Long.valueOf(strings[i]); 498 } 499 intent.putExtra(key, list); 500 hasIntentInfo = true; 501 } else if (opt.equals("--ef")) { 502 String key = nextArgRequired(); 503 String value = nextArgRequired(); 504 intent.putExtra(key, Float.valueOf(value)); 505 hasIntentInfo = true; 506 } else if (opt.equals("--efa")) { 507 String key = nextArgRequired(); 508 String value = nextArgRequired(); 509 String[] strings = value.split(","); 510 float[] list = new float[strings.length]; 511 for (int i = 0; i < strings.length; i++) { 512 list[i] = Float.valueOf(strings[i]); 513 } 514 intent.putExtra(key, list); 515 hasIntentInfo = true; 516 } else if (opt.equals("--esa")) { 517 String key = nextArgRequired(); 518 String value = nextArgRequired(); 519 // Split on commas unless they are preceeded by an escape. 520 // The escape character must be escaped for the string and 521 // again for the regex, thus four escape characters become one. 522 String[] strings = value.split("(?<!\\\\),"); 523 intent.putExtra(key, strings); 524 hasIntentInfo = true; 525 } else if (opt.equals("--ez")) { 526 String key = nextArgRequired(); 527 String value = nextArgRequired().toLowerCase(); 528 // Boolean.valueOf() results in false for anything that is not "true", which is 529 // error-prone in shell commands 530 boolean arg; 531 if ("true".equals(value) || "t".equals(value)) { 532 arg = true; 533 } else if ("false".equals(value) || "f".equals(value)) { 534 arg = false; 535 } else { 536 try { 537 arg = Integer.decode(value) != 0; 538 } catch (NumberFormatException ex) { 539 throw new IllegalArgumentException("Invalid boolean value: " + value); 540 } 541 } 542 543 intent.putExtra(key, arg); 544 } else if (opt.equals("-n")) { 545 String str = nextArgRequired(); 546 ComponentName cn = ComponentName.unflattenFromString(str); 547 if (cn == null) throw new IllegalArgumentException("Bad component name: " + str); 548 intent.setComponent(cn); 549 if (intent == baseIntent) { 550 hasIntentInfo = true; 551 } 552 } else if (opt.equals("-p")) { 553 String str = nextArgRequired(); 554 intent.setPackage(str); 555 if (intent == baseIntent) { 556 hasIntentInfo = true; 557 } 558 } else if (opt.equals("-f")) { 559 String str = nextArgRequired(); 560 intent.setFlags(Integer.decode(str).intValue()); 561 } else if (opt.equals("--grant-read-uri-permission")) { 562 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 563 } else if (opt.equals("--grant-write-uri-permission")) { 564 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 565 } else if (opt.equals("--grant-persistable-uri-permission")) { 566 intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); 567 } else if (opt.equals("--grant-prefix-uri-permission")) { 568 intent.addFlags(Intent.FLAG_GRANT_PREFIX_URI_PERMISSION); 569 } else if (opt.equals("--exclude-stopped-packages")) { 570 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); 571 } else if (opt.equals("--include-stopped-packages")) { 572 intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 573 } else if (opt.equals("--debug-log-resolution")) { 574 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 575 } else if (opt.equals("--activity-brought-to-front")) { 576 intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); 577 } else if (opt.equals("--activity-clear-top")) { 578 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 579 } else if (opt.equals("--activity-clear-when-task-reset")) { 580 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); 581 } else if (opt.equals("--activity-exclude-from-recents")) { 582 intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 583 } else if (opt.equals("--activity-launched-from-history")) { 584 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY); 585 } else if (opt.equals("--activity-multiple-task")) { 586 intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); 587 } else if (opt.equals("--activity-no-animation")) { 588 intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 589 } else if (opt.equals("--activity-no-history")) { 590 intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 591 } else if (opt.equals("--activity-no-user-action")) { 592 intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION); 593 } else if (opt.equals("--activity-previous-is-top")) { 594 intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); 595 } else if (opt.equals("--activity-reorder-to-front")) { 596 intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); 597 } else if (opt.equals("--activity-reset-task-if-needed")) { 598 intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 599 } else if (opt.equals("--activity-single-top")) { 600 intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 601 } else if (opt.equals("--activity-clear-task")) { 602 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); 603 } else if (opt.equals("--activity-task-on-home")) { 604 intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME); 605 } else if (opt.equals("--receiver-registered-only")) { 606 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 607 } else if (opt.equals("--receiver-replace-pending")) { 608 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 609 } else if (opt.equals("--selector")) { 610 intent.setDataAndType(data, type); 611 intent = new Intent(); 612 } else if (opt.equals("-D")) { 613 mStartFlags |= ActivityManager.START_FLAG_DEBUG; 614 } else if (opt.equals("-W")) { 615 mWaitOption = true; 616 } else if (opt.equals("-P")) { 617 mProfileFile = nextArgRequired(); 618 mAutoStop = true; 619 } else if (opt.equals("--start-profiler")) { 620 mProfileFile = nextArgRequired(); 621 mAutoStop = false; 622 } else if (opt.equals("--sampling")) { 623 mSamplingInterval = Integer.parseInt(nextArgRequired()); 624 } else if (opt.equals("-R")) { 625 mRepeat = Integer.parseInt(nextArgRequired()); 626 } else if (opt.equals("-S")) { 627 mStopOption = true; 628 } else if (opt.equals("--opengl-trace")) { 629 mStartFlags |= ActivityManager.START_FLAG_OPENGL_TRACES; 630 } else if (opt.equals("--user")) { 631 mUserId = parseUserArg(nextArgRequired()); 632 } else if (opt.equals("--receiver-permission")) { 633 mReceiverPermission = nextArgRequired(); 634 } else { 635 System.err.println("Error: Unknown option: " + opt); 636 return null; 637 } 638 } 639 intent.setDataAndType(data, type); 640 641 final boolean hasSelector = intent != baseIntent; 642 if (hasSelector) { 643 // A selector was specified; fix up. 644 baseIntent.setSelector(intent); 645 intent = baseIntent; 646 } 647 648 String arg = nextArg(); 649 baseIntent = null; 650 if (arg == null) { 651 if (hasSelector) { 652 // If a selector has been specified, and no arguments 653 // have been supplied for the main Intent, then we can 654 // assume it is ACTION_MAIN CATEGORY_LAUNCHER; we don't 655 // need to have a component name specified yet, the 656 // selector will take care of that. 657 baseIntent = new Intent(Intent.ACTION_MAIN); 658 baseIntent.addCategory(Intent.CATEGORY_LAUNCHER); 659 } 660 } else if (arg.indexOf(':') >= 0) { 661 // The argument is a URI. Fully parse it, and use that result 662 // to fill in any data not specified so far. 663 baseIntent = Intent.parseUri(arg, Intent.URI_INTENT_SCHEME 664 | Intent.URI_ANDROID_APP_SCHEME | Intent.URI_ALLOW_UNSAFE); 665 } else if (arg.indexOf('/') >= 0) { 666 // The argument is a component name. Build an Intent to launch 667 // it. 668 baseIntent = new Intent(Intent.ACTION_MAIN); 669 baseIntent.addCategory(Intent.CATEGORY_LAUNCHER); 670 baseIntent.setComponent(ComponentName.unflattenFromString(arg)); 671 } else { 672 // Assume the argument is a package name. 673 baseIntent = new Intent(Intent.ACTION_MAIN); 674 baseIntent.addCategory(Intent.CATEGORY_LAUNCHER); 675 baseIntent.setPackage(arg); 676 } 677 if (baseIntent != null) { 678 Bundle extras = intent.getExtras(); 679 intent.replaceExtras((Bundle)null); 680 Bundle uriExtras = baseIntent.getExtras(); 681 baseIntent.replaceExtras((Bundle)null); 682 if (intent.getAction() != null && baseIntent.getCategories() != null) { 683 HashSet<String> cats = new HashSet<String>(baseIntent.getCategories()); 684 for (String c : cats) { 685 baseIntent.removeCategory(c); 686 } 687 } 688 intent.fillIn(baseIntent, Intent.FILL_IN_COMPONENT | Intent.FILL_IN_SELECTOR); 689 if (extras == null) { 690 extras = uriExtras; 691 } else if (uriExtras != null) { 692 uriExtras.putAll(extras); 693 extras = uriExtras; 694 } 695 intent.replaceExtras(extras); 696 hasIntentInfo = true; 697 } 698 699 if (!hasIntentInfo) throw new IllegalArgumentException("No intent supplied"); 700 return intent; 701 } 702 703 private void runStartService() throws Exception { 704 Intent intent = makeIntent(UserHandle.USER_CURRENT); 705 if (mUserId == UserHandle.USER_ALL) { 706 System.err.println("Error: Can't start activity with user 'all'"); 707 return; 708 } 709 System.out.println("Starting service: " + intent); 710 ComponentName cn = mAm.startService(null, intent, intent.getType(), mUserId); 711 if (cn == null) { 712 System.err.println("Error: Not found; no service started."); 713 } else if (cn.getPackageName().equals("!")) { 714 System.err.println("Error: Requires permission " + cn.getClassName()); 715 } else if (cn.getPackageName().equals("!!")) { 716 System.err.println("Error: " + cn.getClassName()); 717 } 718 } 719 720 private void runStopService() throws Exception { 721 Intent intent = makeIntent(UserHandle.USER_CURRENT); 722 if (mUserId == UserHandle.USER_ALL) { 723 System.err.println("Error: Can't stop activity with user 'all'"); 724 return; 725 } 726 System.out.println("Stopping service: " + intent); 727 int result = mAm.stopService(null, intent, intent.getType(), mUserId); 728 if (result == 0) { 729 System.err.println("Service not stopped: was not running."); 730 } else if (result == 1) { 731 System.err.println("Service stopped"); 732 } else if (result == -1) { 733 System.err.println("Error stopping service"); 734 } 735 } 736 737 private void runStart() throws Exception { 738 Intent intent = makeIntent(UserHandle.USER_CURRENT); 739 740 if (mUserId == UserHandle.USER_ALL) { 741 System.err.println("Error: Can't start service with user 'all'"); 742 return; 743 } 744 745 String mimeType = intent.getType(); 746 if (mimeType == null && intent.getData() != null 747 && "content".equals(intent.getData().getScheme())) { 748 mimeType = mAm.getProviderMimeType(intent.getData(), mUserId); 749 } 750 751 do { 752 if (mStopOption) { 753 String packageName; 754 if (intent.getComponent() != null) { 755 packageName = intent.getComponent().getPackageName(); 756 } else { 757 IPackageManager pm = IPackageManager.Stub.asInterface( 758 ServiceManager.getService("package")); 759 if (pm == null) { 760 System.err.println("Error: Package manager not running; aborting"); 761 return; 762 } 763 List<ResolveInfo> activities = pm.queryIntentActivities(intent, mimeType, 0, 764 mUserId); 765 if (activities == null || activities.size() <= 0) { 766 System.err.println("Error: Intent does not match any activities: " 767 + intent); 768 return; 769 } else if (activities.size() > 1) { 770 System.err.println("Error: Intent matches multiple activities; can't stop: " 771 + intent); 772 return; 773 } 774 packageName = activities.get(0).activityInfo.packageName; 775 } 776 System.out.println("Stopping: " + packageName); 777 mAm.forceStopPackage(packageName, mUserId); 778 Thread.sleep(250); 779 } 780 781 System.out.println("Starting: " + intent); 782 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 783 784 ParcelFileDescriptor fd = null; 785 ProfilerInfo profilerInfo = null; 786 787 if (mProfileFile != null) { 788 try { 789 fd = openForSystemServer( 790 new File(mProfileFile), 791 ParcelFileDescriptor.MODE_CREATE | 792 ParcelFileDescriptor.MODE_TRUNCATE | 793 ParcelFileDescriptor.MODE_READ_WRITE); 794 } catch (FileNotFoundException e) { 795 System.err.println("Error: Unable to open file: " + mProfileFile); 796 System.err.println("Consider using a file under /data/local/tmp/"); 797 return; 798 } 799 profilerInfo = new ProfilerInfo(mProfileFile, fd, mSamplingInterval, mAutoStop); 800 } 801 802 IActivityManager.WaitResult result = null; 803 int res; 804 final long startTime = SystemClock.uptimeMillis(); 805 if (mWaitOption) { 806 result = mAm.startActivityAndWait(null, null, intent, mimeType, 807 null, null, 0, mStartFlags, profilerInfo, null, mUserId); 808 res = result.result; 809 } else { 810 res = mAm.startActivityAsUser(null, null, intent, mimeType, 811 null, null, 0, mStartFlags, profilerInfo, null, mUserId); 812 } 813 final long endTime = SystemClock.uptimeMillis(); 814 PrintStream out = mWaitOption ? System.out : System.err; 815 boolean launched = false; 816 switch (res) { 817 case ActivityManager.START_SUCCESS: 818 launched = true; 819 break; 820 case ActivityManager.START_SWITCHES_CANCELED: 821 launched = true; 822 out.println( 823 "Warning: Activity not started because the " 824 + " current activity is being kept for the user."); 825 break; 826 case ActivityManager.START_DELIVERED_TO_TOP: 827 launched = true; 828 out.println( 829 "Warning: Activity not started, intent has " 830 + "been delivered to currently running " 831 + "top-most instance."); 832 break; 833 case ActivityManager.START_RETURN_INTENT_TO_CALLER: 834 launched = true; 835 out.println( 836 "Warning: Activity not started because intent " 837 + "should be handled by the caller"); 838 break; 839 case ActivityManager.START_TASK_TO_FRONT: 840 launched = true; 841 out.println( 842 "Warning: Activity not started, its current " 843 + "task has been brought to the front"); 844 break; 845 case ActivityManager.START_INTENT_NOT_RESOLVED: 846 out.println( 847 "Error: Activity not started, unable to " 848 + "resolve " + intent.toString()); 849 break; 850 case ActivityManager.START_CLASS_NOT_FOUND: 851 out.println(NO_CLASS_ERROR_CODE); 852 out.println("Error: Activity class " + 853 intent.getComponent().toShortString() 854 + " does not exist."); 855 break; 856 case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT: 857 out.println( 858 "Error: Activity not started, you requested to " 859 + "both forward and receive its result"); 860 break; 861 case ActivityManager.START_PERMISSION_DENIED: 862 out.println( 863 "Error: Activity not started, you do not " 864 + "have permission to access it."); 865 break; 866 case ActivityManager.START_NOT_VOICE_COMPATIBLE: 867 out.println( 868 "Error: Activity not started, voice control not allowed for: " 869 + intent); 870 break; 871 case ActivityManager.START_NOT_CURRENT_USER_ACTIVITY: 872 out.println( 873 "Error: Not allowed to start background user activity" 874 + " that shouldn't be displayed for all users."); 875 break; 876 default: 877 out.println( 878 "Error: Activity not started, unknown error code " + res); 879 break; 880 } 881 if (mWaitOption && launched) { 882 if (result == null) { 883 result = new IActivityManager.WaitResult(); 884 result.who = intent.getComponent(); 885 } 886 System.out.println("Status: " + (result.timeout ? "timeout" : "ok")); 887 if (result.who != null) { 888 System.out.println("Activity: " + result.who.flattenToShortString()); 889 } 890 if (result.thisTime >= 0) { 891 System.out.println("ThisTime: " + result.thisTime); 892 } 893 if (result.totalTime >= 0) { 894 System.out.println("TotalTime: " + result.totalTime); 895 } 896 System.out.println("WaitTime: " + (endTime-startTime)); 897 System.out.println("Complete"); 898 } 899 mRepeat--; 900 if (mRepeat > 1) { 901 mAm.unhandledBack(); 902 } 903 } while (mRepeat > 1); 904 } 905 906 private void runForceStop() throws Exception { 907 int userId = UserHandle.USER_ALL; 908 909 String opt; 910 while ((opt=nextOption()) != null) { 911 if (opt.equals("--user")) { 912 userId = parseUserArg(nextArgRequired()); 913 } else { 914 System.err.println("Error: Unknown option: " + opt); 915 return; 916 } 917 } 918 mAm.forceStopPackage(nextArgRequired(), userId); 919 } 920 921 private void runKill() throws Exception { 922 int userId = UserHandle.USER_ALL; 923 924 String opt; 925 while ((opt=nextOption()) != null) { 926 if (opt.equals("--user")) { 927 userId = parseUserArg(nextArgRequired()); 928 } else { 929 System.err.println("Error: Unknown option: " + opt); 930 return; 931 } 932 } 933 mAm.killBackgroundProcesses(nextArgRequired(), userId); 934 } 935 936 private void runKillAll() throws Exception { 937 mAm.killAllBackgroundProcesses(); 938 } 939 940 private void sendBroadcast() throws Exception { 941 Intent intent = makeIntent(UserHandle.USER_CURRENT); 942 IntentReceiver receiver = new IntentReceiver(); 943 System.out.println("Broadcasting: " + intent); 944 mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, mReceiverPermission, 945 android.app.AppOpsManager.OP_NONE, true, false, mUserId); 946 receiver.waitForFinish(); 947 } 948 949 private void runInstrument() throws Exception { 950 String profileFile = null; 951 boolean wait = false; 952 boolean rawMode = false; 953 boolean no_window_animation = false; 954 int userId = UserHandle.USER_CURRENT; 955 Bundle args = new Bundle(); 956 String argKey = null, argValue = null; 957 IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window")); 958 String abi = null; 959 960 String opt; 961 while ((opt=nextOption()) != null) { 962 if (opt.equals("-p")) { 963 profileFile = nextArgRequired(); 964 } else if (opt.equals("-w")) { 965 wait = true; 966 } else if (opt.equals("-r")) { 967 rawMode = true; 968 } else if (opt.equals("-e")) { 969 argKey = nextArgRequired(); 970 argValue = nextArgRequired(); 971 args.putString(argKey, argValue); 972 } else if (opt.equals("--no_window_animation") 973 || opt.equals("--no-window-animation")) { 974 no_window_animation = true; 975 } else if (opt.equals("--user")) { 976 userId = parseUserArg(nextArgRequired()); 977 } else if (opt.equals("--abi")) { 978 abi = nextArgRequired(); 979 } else { 980 System.err.println("Error: Unknown option: " + opt); 981 return; 982 } 983 } 984 985 if (userId == UserHandle.USER_ALL) { 986 System.err.println("Error: Can't start instrumentation with user 'all'"); 987 return; 988 } 989 990 String cnArg = nextArgRequired(); 991 ComponentName cn = ComponentName.unflattenFromString(cnArg); 992 if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg); 993 994 InstrumentationWatcher watcher = null; 995 UiAutomationConnection connection = null; 996 if (wait) { 997 watcher = new InstrumentationWatcher(); 998 watcher.setRawOutput(rawMode); 999 connection = new UiAutomationConnection(); 1000 } 1001 1002 float[] oldAnims = null; 1003 if (no_window_animation) { 1004 oldAnims = wm.getAnimationScales(); 1005 wm.setAnimationScale(0, 0.0f); 1006 wm.setAnimationScale(1, 0.0f); 1007 } 1008 1009 if (abi != null) { 1010 final String[] supportedAbis = Build.SUPPORTED_ABIS; 1011 boolean matched = false; 1012 for (String supportedAbi : supportedAbis) { 1013 if (supportedAbi.equals(abi)) { 1014 matched = true; 1015 break; 1016 } 1017 } 1018 1019 if (!matched) { 1020 throw new AndroidException( 1021 "INSTRUMENTATION_FAILED: Unsupported instruction set " + abi); 1022 } 1023 } 1024 1025 if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher, connection, userId, abi)) { 1026 throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString()); 1027 } 1028 1029 if (watcher != null) { 1030 if (!watcher.waitForFinish()) { 1031 System.out.println("INSTRUMENTATION_ABORTED: System has crashed."); 1032 } 1033 } 1034 1035 if (oldAnims != null) { 1036 wm.setAnimationScales(oldAnims); 1037 } 1038 } 1039 1040 static void removeWallOption() { 1041 String props = SystemProperties.get("dalvik.vm.extra-opts"); 1042 if (props != null && props.contains("-Xprofile:wallclock")) { 1043 props = props.replace("-Xprofile:wallclock", ""); 1044 props = props.trim(); 1045 SystemProperties.set("dalvik.vm.extra-opts", props); 1046 } 1047 } 1048 1049 private void runProfile() throws Exception { 1050 String profileFile = null; 1051 boolean start = false; 1052 boolean wall = false; 1053 int userId = UserHandle.USER_CURRENT; 1054 int profileType = 0; 1055 mSamplingInterval = 0; 1056 1057 String process = null; 1058 1059 String cmd = nextArgRequired(); 1060 1061 if ("start".equals(cmd)) { 1062 start = true; 1063 String opt; 1064 while ((opt=nextOption()) != null) { 1065 if (opt.equals("--user")) { 1066 userId = parseUserArg(nextArgRequired()); 1067 } else if (opt.equals("--wall")) { 1068 wall = true; 1069 } else if (opt.equals("--sampling")) { 1070 mSamplingInterval = Integer.parseInt(nextArgRequired()); 1071 } else { 1072 System.err.println("Error: Unknown option: " + opt); 1073 return; 1074 } 1075 } 1076 process = nextArgRequired(); 1077 } else if ("stop".equals(cmd)) { 1078 String opt; 1079 while ((opt=nextOption()) != null) { 1080 if (opt.equals("--user")) { 1081 userId = parseUserArg(nextArgRequired()); 1082 } else { 1083 System.err.println("Error: Unknown option: " + opt); 1084 return; 1085 } 1086 } 1087 process = nextArg(); 1088 } else { 1089 // Compatibility with old syntax: process is specified first. 1090 process = cmd; 1091 cmd = nextArgRequired(); 1092 if ("start".equals(cmd)) { 1093 start = true; 1094 } else if (!"stop".equals(cmd)) { 1095 throw new IllegalArgumentException("Profile command " + process + " not valid"); 1096 } 1097 } 1098 1099 if (userId == UserHandle.USER_ALL) { 1100 System.err.println("Error: Can't profile with user 'all'"); 1101 return; 1102 } 1103 1104 ParcelFileDescriptor fd = null; 1105 ProfilerInfo profilerInfo = null; 1106 1107 if (start) { 1108 profileFile = nextArgRequired(); 1109 try { 1110 fd = openForSystemServer( 1111 new File(profileFile), 1112 ParcelFileDescriptor.MODE_CREATE | 1113 ParcelFileDescriptor.MODE_TRUNCATE | 1114 ParcelFileDescriptor.MODE_READ_WRITE); 1115 } catch (FileNotFoundException e) { 1116 System.err.println("Error: Unable to open file: " + profileFile); 1117 System.err.println("Consider using a file under /data/local/tmp/"); 1118 return; 1119 } 1120 profilerInfo = new ProfilerInfo(profileFile, fd, mSamplingInterval, false); 1121 } 1122 1123 try { 1124 if (wall) { 1125 // XXX doesn't work -- this needs to be set before booting. 1126 String props = SystemProperties.get("dalvik.vm.extra-opts"); 1127 if (props == null || !props.contains("-Xprofile:wallclock")) { 1128 props = props + " -Xprofile:wallclock"; 1129 //SystemProperties.set("dalvik.vm.extra-opts", props); 1130 } 1131 } else if (start) { 1132 //removeWallOption(); 1133 } 1134 if (!mAm.profileControl(process, userId, start, profilerInfo, profileType)) { 1135 wall = false; 1136 throw new AndroidException("PROFILE FAILED on process " + process); 1137 } 1138 } finally { 1139 if (!wall) { 1140 //removeWallOption(); 1141 } 1142 } 1143 } 1144 1145 private void runDumpHeap() throws Exception { 1146 boolean managed = true; 1147 int userId = UserHandle.USER_CURRENT; 1148 1149 String opt; 1150 while ((opt=nextOption()) != null) { 1151 if (opt.equals("--user")) { 1152 userId = parseUserArg(nextArgRequired()); 1153 if (userId == UserHandle.USER_ALL) { 1154 System.err.println("Error: Can't dump heap with user 'all'"); 1155 return; 1156 } 1157 } else if (opt.equals("-n")) { 1158 managed = false; 1159 } else { 1160 System.err.println("Error: Unknown option: " + opt); 1161 return; 1162 } 1163 } 1164 String process = nextArgRequired(); 1165 String heapFile = nextArgRequired(); 1166 ParcelFileDescriptor fd = null; 1167 1168 try { 1169 File file = new File(heapFile); 1170 file.delete(); 1171 fd = openForSystemServer(file, 1172 ParcelFileDescriptor.MODE_CREATE | 1173 ParcelFileDescriptor.MODE_TRUNCATE | 1174 ParcelFileDescriptor.MODE_READ_WRITE); 1175 } catch (FileNotFoundException e) { 1176 System.err.println("Error: Unable to open file: " + heapFile); 1177 System.err.println("Consider using a file under /data/local/tmp/"); 1178 return; 1179 } 1180 1181 if (!mAm.dumpHeap(process, userId, managed, heapFile, fd)) { 1182 throw new AndroidException("HEAP DUMP FAILED on process " + process); 1183 } 1184 } 1185 1186 private void runSetDebugApp() throws Exception { 1187 boolean wait = false; 1188 boolean persistent = false; 1189 1190 String opt; 1191 while ((opt=nextOption()) != null) { 1192 if (opt.equals("-w")) { 1193 wait = true; 1194 } else if (opt.equals("--persistent")) { 1195 persistent = true; 1196 } else { 1197 System.err.println("Error: Unknown option: " + opt); 1198 return; 1199 } 1200 } 1201 1202 String pkg = nextArgRequired(); 1203 mAm.setDebugApp(pkg, wait, persistent); 1204 } 1205 1206 private void runClearDebugApp() throws Exception { 1207 mAm.setDebugApp(null, false, true); 1208 } 1209 1210 private void runSetWatchHeap() throws Exception { 1211 String proc = nextArgRequired(); 1212 String limit = nextArgRequired(); 1213 mAm.setDumpHeapDebugLimit(proc, 0, Long.parseLong(limit), null); 1214 } 1215 1216 private void runClearWatchHeap() throws Exception { 1217 String proc = nextArgRequired(); 1218 mAm.setDumpHeapDebugLimit(proc, 0, -1, null); 1219 } 1220 1221 private void runBugReport() throws Exception { 1222 mAm.requestBugReport(); 1223 System.out.println("Your lovely bug report is being created; please be patient."); 1224 } 1225 1226 private void runSwitchUser() throws Exception { 1227 String user = nextArgRequired(); 1228 mAm.switchUser(Integer.parseInt(user)); 1229 } 1230 1231 private void runStartUserInBackground() throws Exception { 1232 String user = nextArgRequired(); 1233 boolean success = mAm.startUserInBackground(Integer.parseInt(user)); 1234 if (success) { 1235 System.out.println("Success: user started"); 1236 } else { 1237 System.err.println("Error: could not start user"); 1238 } 1239 } 1240 1241 private void runStopUser() throws Exception { 1242 String user = nextArgRequired(); 1243 int res = mAm.stopUser(Integer.parseInt(user), null); 1244 if (res != ActivityManager.USER_OP_SUCCESS) { 1245 String txt = ""; 1246 switch (res) { 1247 case ActivityManager.USER_OP_IS_CURRENT: 1248 txt = " (Can't stop current user)"; 1249 break; 1250 case ActivityManager.USER_OP_UNKNOWN_USER: 1251 txt = " (Unknown user " + user + ")"; 1252 break; 1253 } 1254 System.err.println("Switch failed: " + res + txt); 1255 } 1256 } 1257 1258 class MyActivityController extends IActivityController.Stub { 1259 final String mGdbPort; 1260 1261 static final int STATE_NORMAL = 0; 1262 static final int STATE_CRASHED = 1; 1263 static final int STATE_EARLY_ANR = 2; 1264 static final int STATE_ANR = 3; 1265 1266 int mState; 1267 1268 static final int RESULT_DEFAULT = 0; 1269 1270 static final int RESULT_CRASH_DIALOG = 0; 1271 static final int RESULT_CRASH_KILL = 1; 1272 1273 static final int RESULT_EARLY_ANR_CONTINUE = 0; 1274 static final int RESULT_EARLY_ANR_KILL = 1; 1275 1276 static final int RESULT_ANR_DIALOG = 0; 1277 static final int RESULT_ANR_KILL = 1; 1278 static final int RESULT_ANR_WAIT = 1; 1279 1280 int mResult; 1281 1282 Process mGdbProcess; 1283 Thread mGdbThread; 1284 boolean mGotGdbPrint; 1285 1286 MyActivityController(String gdbPort) { 1287 mGdbPort = gdbPort; 1288 } 1289 1290 @Override 1291 public boolean activityResuming(String pkg) { 1292 synchronized (this) { 1293 System.out.println("** Activity resuming: " + pkg); 1294 } 1295 return true; 1296 } 1297 1298 @Override 1299 public boolean activityStarting(Intent intent, String pkg) { 1300 synchronized (this) { 1301 System.out.println("** Activity starting: " + pkg); 1302 } 1303 return true; 1304 } 1305 1306 @Override 1307 public boolean appCrashed(String processName, int pid, String shortMsg, String longMsg, 1308 long timeMillis, String stackTrace) { 1309 synchronized (this) { 1310 System.out.println("** ERROR: PROCESS CRASHED"); 1311 System.out.println("processName: " + processName); 1312 System.out.println("processPid: " + pid); 1313 System.out.println("shortMsg: " + shortMsg); 1314 System.out.println("longMsg: " + longMsg); 1315 System.out.println("timeMillis: " + timeMillis); 1316 System.out.println("stack:"); 1317 System.out.print(stackTrace); 1318 System.out.println("#"); 1319 int result = waitControllerLocked(pid, STATE_CRASHED); 1320 return result == RESULT_CRASH_KILL ? false : true; 1321 } 1322 } 1323 1324 @Override 1325 public int appEarlyNotResponding(String processName, int pid, String annotation) { 1326 synchronized (this) { 1327 System.out.println("** ERROR: EARLY PROCESS NOT RESPONDING"); 1328 System.out.println("processName: " + processName); 1329 System.out.println("processPid: " + pid); 1330 System.out.println("annotation: " + annotation); 1331 int result = waitControllerLocked(pid, STATE_EARLY_ANR); 1332 if (result == RESULT_EARLY_ANR_KILL) return -1; 1333 return 0; 1334 } 1335 } 1336 1337 @Override 1338 public int appNotResponding(String processName, int pid, String processStats) { 1339 synchronized (this) { 1340 System.out.println("** ERROR: PROCESS NOT RESPONDING"); 1341 System.out.println("processName: " + processName); 1342 System.out.println("processPid: " + pid); 1343 System.out.println("processStats:"); 1344 System.out.print(processStats); 1345 System.out.println("#"); 1346 int result = waitControllerLocked(pid, STATE_ANR); 1347 if (result == RESULT_ANR_KILL) return -1; 1348 if (result == RESULT_ANR_WAIT) return 1; 1349 return 0; 1350 } 1351 } 1352 1353 @Override 1354 public int systemNotResponding(String message) { 1355 synchronized (this) { 1356 System.out.println("** ERROR: PROCESS NOT RESPONDING"); 1357 System.out.println("message: " + message); 1358 System.out.println("#"); 1359 System.out.println("Allowing system to die."); 1360 return -1; 1361 } 1362 } 1363 1364 void killGdbLocked() { 1365 mGotGdbPrint = false; 1366 if (mGdbProcess != null) { 1367 System.out.println("Stopping gdbserver"); 1368 mGdbProcess.destroy(); 1369 mGdbProcess = null; 1370 } 1371 if (mGdbThread != null) { 1372 mGdbThread.interrupt(); 1373 mGdbThread = null; 1374 } 1375 } 1376 1377 int waitControllerLocked(int pid, int state) { 1378 if (mGdbPort != null) { 1379 killGdbLocked(); 1380 1381 try { 1382 System.out.println("Starting gdbserver on port " + mGdbPort); 1383 System.out.println("Do the following:"); 1384 System.out.println(" adb forward tcp:" + mGdbPort + " tcp:" + mGdbPort); 1385 System.out.println(" gdbclient app_process :" + mGdbPort); 1386 1387 mGdbProcess = Runtime.getRuntime().exec(new String[] { 1388 "gdbserver", ":" + mGdbPort, "--attach", Integer.toString(pid) 1389 }); 1390 final InputStreamReader converter = new InputStreamReader( 1391 mGdbProcess.getInputStream()); 1392 mGdbThread = new Thread() { 1393 @Override 1394 public void run() { 1395 BufferedReader in = new BufferedReader(converter); 1396 String line; 1397 int count = 0; 1398 while (true) { 1399 synchronized (MyActivityController.this) { 1400 if (mGdbThread == null) { 1401 return; 1402 } 1403 if (count == 2) { 1404 mGotGdbPrint = true; 1405 MyActivityController.this.notifyAll(); 1406 } 1407 } 1408 try { 1409 line = in.readLine(); 1410 if (line == null) { 1411 return; 1412 } 1413 System.out.println("GDB: " + line); 1414 count++; 1415 } catch (IOException e) { 1416 return; 1417 } 1418 } 1419 } 1420 }; 1421 mGdbThread.start(); 1422 1423 // Stupid waiting for .5s. Doesn't matter if we end early. 1424 try { 1425 this.wait(500); 1426 } catch (InterruptedException e) { 1427 } 1428 1429 } catch (IOException e) { 1430 System.err.println("Failure starting gdbserver: " + e); 1431 killGdbLocked(); 1432 } 1433 } 1434 mState = state; 1435 System.out.println(""); 1436 printMessageForState(); 1437 1438 while (mState != STATE_NORMAL) { 1439 try { 1440 wait(); 1441 } catch (InterruptedException e) { 1442 } 1443 } 1444 1445 killGdbLocked(); 1446 1447 return mResult; 1448 } 1449 1450 void resumeController(int result) { 1451 synchronized (this) { 1452 mState = STATE_NORMAL; 1453 mResult = result; 1454 notifyAll(); 1455 } 1456 } 1457 1458 void printMessageForState() { 1459 switch (mState) { 1460 case STATE_NORMAL: 1461 System.out.println("Monitoring activity manager... available commands:"); 1462 break; 1463 case STATE_CRASHED: 1464 System.out.println("Waiting after crash... available commands:"); 1465 System.out.println("(c)ontinue: show crash dialog"); 1466 System.out.println("(k)ill: immediately kill app"); 1467 break; 1468 case STATE_EARLY_ANR: 1469 System.out.println("Waiting after early ANR... available commands:"); 1470 System.out.println("(c)ontinue: standard ANR processing"); 1471 System.out.println("(k)ill: immediately kill app"); 1472 break; 1473 case STATE_ANR: 1474 System.out.println("Waiting after ANR... available commands:"); 1475 System.out.println("(c)ontinue: show ANR dialog"); 1476 System.out.println("(k)ill: immediately kill app"); 1477 System.out.println("(w)ait: wait some more"); 1478 break; 1479 } 1480 System.out.println("(q)uit: finish monitoring"); 1481 } 1482 1483 void run() throws RemoteException { 1484 try { 1485 printMessageForState(); 1486 1487 mAm.setActivityController(this); 1488 mState = STATE_NORMAL; 1489 1490 InputStreamReader converter = new InputStreamReader(System.in); 1491 BufferedReader in = new BufferedReader(converter); 1492 String line; 1493 1494 while ((line = in.readLine()) != null) { 1495 boolean addNewline = true; 1496 if (line.length() <= 0) { 1497 addNewline = false; 1498 } else if ("q".equals(line) || "quit".equals(line)) { 1499 resumeController(RESULT_DEFAULT); 1500 break; 1501 } else if (mState == STATE_CRASHED) { 1502 if ("c".equals(line) || "continue".equals(line)) { 1503 resumeController(RESULT_CRASH_DIALOG); 1504 } else if ("k".equals(line) || "kill".equals(line)) { 1505 resumeController(RESULT_CRASH_KILL); 1506 } else { 1507 System.out.println("Invalid command: " + line); 1508 } 1509 } else if (mState == STATE_ANR) { 1510 if ("c".equals(line) || "continue".equals(line)) { 1511 resumeController(RESULT_ANR_DIALOG); 1512 } else if ("k".equals(line) || "kill".equals(line)) { 1513 resumeController(RESULT_ANR_KILL); 1514 } else if ("w".equals(line) || "wait".equals(line)) { 1515 resumeController(RESULT_ANR_WAIT); 1516 } else { 1517 System.out.println("Invalid command: " + line); 1518 } 1519 } else if (mState == STATE_EARLY_ANR) { 1520 if ("c".equals(line) || "continue".equals(line)) { 1521 resumeController(RESULT_EARLY_ANR_CONTINUE); 1522 } else if ("k".equals(line) || "kill".equals(line)) { 1523 resumeController(RESULT_EARLY_ANR_KILL); 1524 } else { 1525 System.out.println("Invalid command: " + line); 1526 } 1527 } else { 1528 System.out.println("Invalid command: " + line); 1529 } 1530 1531 synchronized (this) { 1532 if (addNewline) { 1533 System.out.println(""); 1534 } 1535 printMessageForState(); 1536 } 1537 } 1538 1539 } catch (IOException e) { 1540 e.printStackTrace(); 1541 } finally { 1542 mAm.setActivityController(null); 1543 } 1544 } 1545 } 1546 1547 private void runMonitor() throws Exception { 1548 String opt; 1549 String gdbPort = null; 1550 while ((opt=nextOption()) != null) { 1551 if (opt.equals("--gdb")) { 1552 gdbPort = nextArgRequired(); 1553 } else { 1554 System.err.println("Error: Unknown option: " + opt); 1555 return; 1556 } 1557 } 1558 1559 MyActivityController controller = new MyActivityController(gdbPort); 1560 controller.run(); 1561 } 1562 1563 private void runHang() throws Exception { 1564 String opt; 1565 boolean allowRestart = false; 1566 while ((opt=nextOption()) != null) { 1567 if (opt.equals("--allow-restart")) { 1568 allowRestart = true; 1569 } else { 1570 System.err.println("Error: Unknown option: " + opt); 1571 return; 1572 } 1573 } 1574 1575 System.out.println("Hanging the system..."); 1576 mAm.hang(new Binder(), allowRestart); 1577 } 1578 1579 private void runRestart() throws Exception { 1580 String opt; 1581 while ((opt=nextOption()) != null) { 1582 System.err.println("Error: Unknown option: " + opt); 1583 return; 1584 } 1585 1586 System.out.println("Restart the system..."); 1587 mAm.restart(); 1588 } 1589 1590 private void runIdleMaintenance() throws Exception { 1591 String opt; 1592 while ((opt=nextOption()) != null) { 1593 System.err.println("Error: Unknown option: " + opt); 1594 return; 1595 } 1596 1597 System.out.println("Performing idle maintenance..."); 1598 Intent intent = new Intent( 1599 "com.android.server.task.controllers.IdleController.ACTION_TRIGGER_IDLE"); 1600 mAm.broadcastIntent(null, intent, null, null, 0, null, null, null, 1601 android.app.AppOpsManager.OP_NONE, true, false, UserHandle.USER_ALL); 1602 } 1603 1604 private void runScreenCompat() throws Exception { 1605 String mode = nextArgRequired(); 1606 boolean enabled; 1607 if ("on".equals(mode)) { 1608 enabled = true; 1609 } else if ("off".equals(mode)) { 1610 enabled = false; 1611 } else { 1612 System.err.println("Error: enabled mode must be 'on' or 'off' at " + mode); 1613 return; 1614 } 1615 1616 String packageName = nextArgRequired(); 1617 do { 1618 try { 1619 mAm.setPackageScreenCompatMode(packageName, enabled 1620 ? ActivityManager.COMPAT_MODE_ENABLED 1621 : ActivityManager.COMPAT_MODE_DISABLED); 1622 } catch (RemoteException e) { 1623 } 1624 packageName = nextArg(); 1625 } while (packageName != null); 1626 } 1627 1628 private void runPackageImportance() throws Exception { 1629 String packageName = nextArgRequired(); 1630 try { 1631 int procState = mAm.getPackageProcessState(packageName); 1632 System.out.println( 1633 ActivityManager.RunningAppProcessInfo.procStateToImportance(procState)); 1634 } catch (RemoteException e) { 1635 } 1636 } 1637 1638 private void runToUri(int flags) throws Exception { 1639 Intent intent = makeIntent(UserHandle.USER_CURRENT); 1640 System.out.println(intent.toUri(flags)); 1641 } 1642 1643 private class IntentReceiver extends IIntentReceiver.Stub { 1644 private boolean mFinished = false; 1645 1646 @Override 1647 public void performReceive(Intent intent, int resultCode, String data, Bundle extras, 1648 boolean ordered, boolean sticky, int sendingUser) { 1649 String line = "Broadcast completed: result=" + resultCode; 1650 if (data != null) line = line + ", data=\"" + data + "\""; 1651 if (extras != null) line = line + ", extras: " + extras; 1652 System.out.println(line); 1653 synchronized (this) { 1654 mFinished = true; 1655 notifyAll(); 1656 } 1657 } 1658 1659 public synchronized void waitForFinish() { 1660 try { 1661 while (!mFinished) wait(); 1662 } catch (InterruptedException e) { 1663 throw new IllegalStateException(e); 1664 } 1665 } 1666 } 1667 1668 private class InstrumentationWatcher extends IInstrumentationWatcher.Stub { 1669 private boolean mFinished = false; 1670 private boolean mRawMode = false; 1671 1672 /** 1673 * Set or reset "raw mode". In "raw mode", all bundles are dumped. In "pretty mode", 1674 * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that. 1675 * @param rawMode true for raw mode, false for pretty mode. 1676 */ 1677 public void setRawOutput(boolean rawMode) { 1678 mRawMode = rawMode; 1679 } 1680 1681 @Override 1682 public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) { 1683 synchronized (this) { 1684 // pretty printer mode? 1685 String pretty = null; 1686 if (!mRawMode && results != null) { 1687 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); 1688 } 1689 if (pretty != null) { 1690 System.out.print(pretty); 1691 } else { 1692 if (results != null) { 1693 for (String key : results.keySet()) { 1694 System.out.println( 1695 "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key)); 1696 } 1697 } 1698 System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode); 1699 } 1700 notifyAll(); 1701 } 1702 } 1703 1704 @Override 1705 public void instrumentationFinished(ComponentName name, int resultCode, 1706 Bundle results) { 1707 synchronized (this) { 1708 // pretty printer mode? 1709 String pretty = null; 1710 if (!mRawMode && results != null) { 1711 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); 1712 } 1713 if (pretty != null) { 1714 System.out.println(pretty); 1715 } else { 1716 if (results != null) { 1717 for (String key : results.keySet()) { 1718 System.out.println( 1719 "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key)); 1720 } 1721 } 1722 System.out.println("INSTRUMENTATION_CODE: " + resultCode); 1723 } 1724 mFinished = true; 1725 notifyAll(); 1726 } 1727 } 1728 1729 public boolean waitForFinish() { 1730 synchronized (this) { 1731 while (!mFinished) { 1732 try { 1733 if (!mAm.asBinder().pingBinder()) { 1734 return false; 1735 } 1736 wait(1000); 1737 } catch (InterruptedException e) { 1738 throw new IllegalStateException(e); 1739 } 1740 } 1741 } 1742 return true; 1743 } 1744 } 1745 1746 private void runStack() throws Exception { 1747 String op = nextArgRequired(); 1748 if (op.equals("start")) { 1749 runStackStart(); 1750 } else if (op.equals("movetask")) { 1751 runStackMoveTask(); 1752 } else if (op.equals("resize")) { 1753 runStackResize(); 1754 } else if (op.equals("list")) { 1755 runStackList(); 1756 } else if (op.equals("info")) { 1757 runStackInfo(); 1758 } else if (op.equals("split")) { 1759 runStackSplit(); 1760 } else { 1761 showError("Error: unknown command '" + op + "'"); 1762 return; 1763 } 1764 } 1765 1766 private void runStackStart() throws Exception { 1767 String displayIdStr = nextArgRequired(); 1768 int displayId = Integer.valueOf(displayIdStr); 1769 Intent intent = makeIntent(UserHandle.USER_CURRENT); 1770 1771 try { 1772 IActivityContainer container = mAm.createStackOnDisplay(displayId); 1773 if (container != null) { 1774 container.startActivity(intent); 1775 } 1776 } catch (RemoteException e) { 1777 } 1778 } 1779 1780 private void runStackMoveTask() throws Exception { 1781 String taskIdStr = nextArgRequired(); 1782 int taskId = Integer.valueOf(taskIdStr); 1783 String stackIdStr = nextArgRequired(); 1784 int stackId = Integer.valueOf(stackIdStr); 1785 String toTopStr = nextArgRequired(); 1786 final boolean toTop; 1787 if ("true".equals(toTopStr)) { 1788 toTop = true; 1789 } else if ("false".equals(toTopStr)) { 1790 toTop = false; 1791 } else { 1792 System.err.println("Error: bad toTop arg: " + toTopStr); 1793 return; 1794 } 1795 1796 try { 1797 mAm.moveTaskToStack(taskId, stackId, toTop); 1798 } catch (RemoteException e) { 1799 } 1800 } 1801 1802 private void runStackResize() throws Exception { 1803 String stackIdStr = nextArgRequired(); 1804 int stackId = Integer.valueOf(stackIdStr); 1805 final Rect bounds = getBounds(); 1806 if (bounds == null) { 1807 System.err.println("Error: invalid input bounds"); 1808 return; 1809 } 1810 1811 try { 1812 mAm.resizeStack(stackId, bounds); 1813 } catch (RemoteException e) { 1814 } 1815 } 1816 1817 private void runStackList() throws Exception { 1818 try { 1819 List<StackInfo> stacks = mAm.getAllStackInfos(); 1820 for (StackInfo info : stacks) { 1821 System.out.println(info); 1822 } 1823 } catch (RemoteException e) { 1824 } 1825 } 1826 1827 private void runStackInfo() throws Exception { 1828 try { 1829 String stackIdStr = nextArgRequired(); 1830 int stackId = Integer.valueOf(stackIdStr); 1831 StackInfo info = mAm.getStackInfo(stackId); 1832 System.out.println(info); 1833 } catch (RemoteException e) { 1834 } 1835 } 1836 1837 private void runStackSplit() throws Exception { 1838 final int stackId = Integer.valueOf(nextArgRequired()); 1839 final String splitDirection = nextArgRequired(); 1840 Intent intent = null; 1841 try { 1842 intent = makeIntent(UserHandle.USER_CURRENT); 1843 } catch (IllegalArgumentException e) { 1844 // no intent supplied. 1845 } 1846 1847 try { 1848 final StackInfo currentStackInfo = mAm.getStackInfo(stackId); 1849 // Calculate bounds for new and current stack. 1850 final Rect currentStackBounds = new Rect(currentStackInfo.bounds); 1851 final Rect newStackBounds = new Rect(currentStackInfo.bounds); 1852 if ("v".equals(splitDirection)) { 1853 currentStackBounds.right = newStackBounds.left = currentStackInfo.bounds.centerX(); 1854 } else if ("h".equals(splitDirection)) { 1855 currentStackBounds.bottom = newStackBounds.top = currentStackInfo.bounds.centerY(); 1856 } else { 1857 showError("Error: unknown split direction '" + splitDirection + "'"); 1858 return; 1859 } 1860 1861 // Create new stack 1862 IActivityContainer container = mAm.createStackOnDisplay(currentStackInfo.displayId); 1863 if (container == null) { 1864 showError("Error: Unable to create new stack..."); 1865 } 1866 1867 final int newStackId = container.getStackId(); 1868 1869 if (intent != null) { 1870 container.startActivity(intent); 1871 } else if (currentStackInfo.taskIds != null && currentStackInfo.taskIds.length > 1) { 1872 // Move top task over to new stack 1873 mAm.moveTaskToStack(currentStackInfo.taskIds[currentStackInfo.taskIds.length - 1], 1874 newStackId, true); 1875 } 1876 1877 final StackInfo newStackInfo = mAm.getStackInfo(newStackId); 1878 1879 // Make all tasks in the stacks resizeable. 1880 for (int taskId : currentStackInfo.taskIds) { 1881 mAm.setTaskResizeable(taskId, true); 1882 } 1883 1884 for (int taskId : newStackInfo.taskIds) { 1885 mAm.setTaskResizeable(taskId, true); 1886 } 1887 1888 // Resize stacks 1889 mAm.resizeStack(currentStackInfo.stackId, currentStackBounds); 1890 mAm.resizeStack(newStackInfo.stackId, newStackBounds); 1891 } catch (RemoteException e) { 1892 } 1893 } 1894 1895 private void runTask() throws Exception { 1896 String op = nextArgRequired(); 1897 if (op.equals("lock")) { 1898 runTaskLock(); 1899 } else if (op.equals("resizeable")) { 1900 runTaskResizeable(); 1901 } else if (op.equals("resize")) { 1902 runTaskResize(); 1903 } else { 1904 showError("Error: unknown command '" + op + "'"); 1905 return; 1906 } 1907 } 1908 1909 private void runTaskLock() throws Exception { 1910 String taskIdStr = nextArgRequired(); 1911 try { 1912 if (taskIdStr.equals("stop")) { 1913 mAm.stopLockTaskMode(); 1914 } else { 1915 int taskId = Integer.valueOf(taskIdStr); 1916 mAm.startLockTaskMode(taskId); 1917 } 1918 System.err.println("Activity manager is " + (mAm.isInLockTaskMode() ? "" : "not ") + 1919 "in lockTaskMode"); 1920 } catch (RemoteException e) { 1921 } 1922 } 1923 1924 private void runTaskResizeable() throws Exception { 1925 final String taskIdStr = nextArgRequired(); 1926 final int taskId = Integer.valueOf(taskIdStr); 1927 final String resizeableStr = nextArgRequired(); 1928 final boolean resizeable = Boolean.valueOf(resizeableStr); 1929 1930 try { 1931 mAm.setTaskResizeable(taskId, resizeable); 1932 } catch (RemoteException e) { 1933 } 1934 } 1935 1936 private void runTaskResize() throws Exception { 1937 final String taskIdStr = nextArgRequired(); 1938 final int taskId = Integer.valueOf(taskIdStr); 1939 final Rect bounds = getBounds(); 1940 if (bounds == null) { 1941 System.err.println("Error: invalid input bounds"); 1942 return; 1943 } 1944 try { 1945 mAm.resizeTask(taskId, bounds); 1946 } catch (RemoteException e) { 1947 } 1948 } 1949 1950 private List<Configuration> getRecentConfigurations(int days) { 1951 IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService( 1952 Context.USAGE_STATS_SERVICE)); 1953 final long now = System.currentTimeMillis(); 1954 final long nDaysAgo = now - (days * 24 * 60 * 60 * 1000); 1955 try { 1956 @SuppressWarnings("unchecked") 1957 ParceledListSlice<ConfigurationStats> configStatsSlice = usm.queryConfigurationStats( 1958 UsageStatsManager.INTERVAL_BEST, nDaysAgo, now, "com.android.shell"); 1959 if (configStatsSlice == null) { 1960 return Collections.emptyList(); 1961 } 1962 1963 final ArrayMap<Configuration, Integer> recentConfigs = new ArrayMap<>(); 1964 final List<ConfigurationStats> configStatsList = configStatsSlice.getList(); 1965 final int configStatsListSize = configStatsList.size(); 1966 for (int i = 0; i < configStatsListSize; i++) { 1967 final ConfigurationStats stats = configStatsList.get(i); 1968 final int indexOfKey = recentConfigs.indexOfKey(stats.getConfiguration()); 1969 if (indexOfKey < 0) { 1970 recentConfigs.put(stats.getConfiguration(), stats.getActivationCount()); 1971 } else { 1972 recentConfigs.setValueAt(indexOfKey, 1973 recentConfigs.valueAt(indexOfKey) + stats.getActivationCount()); 1974 } 1975 } 1976 1977 final Comparator<Configuration> comparator = new Comparator<Configuration>() { 1978 @Override 1979 public int compare(Configuration a, Configuration b) { 1980 return recentConfigs.get(b).compareTo(recentConfigs.get(a)); 1981 } 1982 }; 1983 1984 ArrayList<Configuration> configs = new ArrayList<>(recentConfigs.size()); 1985 configs.addAll(recentConfigs.keySet()); 1986 Collections.sort(configs, comparator); 1987 return configs; 1988 1989 } catch (RemoteException e) { 1990 return Collections.emptyList(); 1991 } 1992 } 1993 1994 private void runGetConfig() throws Exception { 1995 int days = 14; 1996 String option = nextOption(); 1997 if (option != null) { 1998 if (!option.equals("--days")) { 1999 throw new IllegalArgumentException("unrecognized option " + option); 2000 } 2001 2002 days = Integer.parseInt(nextArgRequired()); 2003 if (days <= 0) { 2004 throw new IllegalArgumentException("--days must be a positive integer"); 2005 } 2006 } 2007 2008 try { 2009 Configuration config = mAm.getConfiguration(); 2010 if (config == null) { 2011 System.err.println("Activity manager has no configuration"); 2012 return; 2013 } 2014 2015 System.out.println("config: " + Configuration.resourceQualifierString(config)); 2016 System.out.println("abi: " + TextUtils.join(",", Build.SUPPORTED_ABIS)); 2017 2018 final List<Configuration> recentConfigs = getRecentConfigurations(days); 2019 final int recentConfigSize = recentConfigs.size(); 2020 if (recentConfigSize > 0) { 2021 System.out.println("recentConfigs:"); 2022 } 2023 2024 for (int i = 0; i < recentConfigSize; i++) { 2025 System.out.println(" config: " + Configuration.resourceQualifierString( 2026 recentConfigs.get(i))); 2027 } 2028 2029 } catch (RemoteException e) { 2030 } 2031 } 2032 2033 private void runSetIdle() throws Exception { 2034 int userId = UserHandle.USER_OWNER; 2035 2036 String opt; 2037 while ((opt=nextOption()) != null) { 2038 if (opt.equals("--user")) { 2039 userId = parseUserArg(nextArgRequired()); 2040 } else { 2041 System.err.println("Error: Unknown option: " + opt); 2042 return; 2043 } 2044 } 2045 String packageName = nextArgRequired(); 2046 String value = nextArgRequired(); 2047 2048 IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService( 2049 Context.USAGE_STATS_SERVICE)); 2050 usm.setAppIdle(packageName, Boolean.parseBoolean(value), userId); 2051 } 2052 2053 private void runGetIdle() throws Exception { 2054 int userId = UserHandle.USER_OWNER; 2055 2056 String opt; 2057 while ((opt=nextOption()) != null) { 2058 if (opt.equals("--user")) { 2059 userId = parseUserArg(nextArgRequired()); 2060 } else { 2061 System.err.println("Error: Unknown option: " + opt); 2062 return; 2063 } 2064 } 2065 String packageName = nextArgRequired(); 2066 2067 IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService( 2068 Context.USAGE_STATS_SERVICE)); 2069 boolean isIdle = usm.isAppIdle(packageName, userId); 2070 System.out.println("Idle=" + isIdle); 2071 } 2072 2073 /** 2074 * Open the given file for sending into the system process. This verifies 2075 * with SELinux that the system will have access to the file. 2076 */ 2077 private static ParcelFileDescriptor openForSystemServer(File file, int mode) 2078 throws FileNotFoundException { 2079 final ParcelFileDescriptor fd = ParcelFileDescriptor.open(file, mode); 2080 final String tcon = SELinux.getFileContext(file.getAbsolutePath()); 2081 if (!SELinux.checkSELinuxAccess("u:r:system_server:s0", tcon, "file", "read")) { 2082 throw new FileNotFoundException("System server has no access to file context " + tcon); 2083 } 2084 return fd; 2085 } 2086 2087 private Rect getBounds() { 2088 String leftStr = nextArgRequired(); 2089 int left = Integer.valueOf(leftStr); 2090 String topStr = nextArgRequired(); 2091 int top = Integer.valueOf(topStr); 2092 String rightStr = nextArgRequired(); 2093 int right = Integer.valueOf(rightStr); 2094 String bottomStr = nextArgRequired(); 2095 int bottom = Integer.valueOf(bottomStr); 2096 if (left < 0) { 2097 System.err.println("Error: bad left arg: " + leftStr); 2098 return null; 2099 } 2100 if (top < 0) { 2101 System.err.println("Error: bad top arg: " + topStr); 2102 return null; 2103 } 2104 if (right <= 0) { 2105 System.err.println("Error: bad right arg: " + rightStr); 2106 return null; 2107 } 2108 if (bottom <= 0) { 2109 System.err.println("Error: bad bottom arg: " + bottomStr); 2110 return null; 2111 } 2112 return new Rect(left, top, right, bottom); 2113 } 2114} 2115