3 ** Copyright 2007, The Android Open Source Project
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
9 ** http://www.apache.org/licenses/LICENSE-2.0
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.
19 package com.android.commands.am;
21 import static android.app.ActivityManager.RESIZE_MODE_SYSTEM;
22 import static android.app.ActivityManager.RESIZE_MODE_USER;
23 import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
24 import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
26 import android.app.ActivityManager;
27 import android.app.ActivityManager.StackInfo;
28 import android.app.ActivityManagerNative;
29 import android.app.ActivityOptions;
30 import android.app.IActivityContainer;
31 import android.app.IActivityController;
32 import android.app.IActivityManager;
33 import android.app.IInstrumentationWatcher;
34 import android.app.Instrumentation;
35 import android.app.IStopUserCallback;
36 import android.app.ProfilerInfo;
37 import android.app.UiAutomationConnection;
38 import android.app.usage.ConfigurationStats;
39 import android.app.usage.IUsageStatsManager;
40 import android.app.usage.UsageStatsManager;
41 import android.content.ComponentCallbacks2;
42 import android.content.ComponentName;
43 import android.content.Context;
44 import android.content.IIntentReceiver;
45 import android.content.Intent;
46 import android.content.pm.IPackageManager;
47 import android.content.pm.InstrumentationInfo;
48 import android.content.pm.ParceledListSlice;
49 import android.content.pm.ResolveInfo;
50 import android.content.pm.UserInfo;
51 import android.content.res.Configuration;
52 import android.graphics.Rect;
53 import android.os.Binder;
54 import android.os.Build;
55 import android.os.Bundle;
56 import android.os.ParcelFileDescriptor;
57 import android.os.RemoteException;
58 import android.os.SELinux;
59 import android.os.ServiceManager;
60 import android.os.ShellCommand;
61 import android.os.SystemClock;
62 import android.os.SystemProperties;
63 import android.os.UserHandle;
64 import android.text.TextUtils;
65 import android.util.AndroidException;
66 import android.util.ArrayMap;
67 import android.view.IWindowManager;
69 import com.android.internal.os.BaseCommand;
70 import com.android.internal.util.HexDump;
71 import com.android.internal.util.Preconditions;
73 import java.io.BufferedReader;
75 import java.io.FileNotFoundException;
76 import java.io.IOException;
77 import java.io.InputStreamReader;
78 import java.io.PrintStream;
79 import java.io.PrintWriter;
80 import java.net.URISyntaxException;
81 import java.util.ArrayList;
82 import java.util.Collections;
83 import java.util.Comparator;
84 import java.util.List;
86 public class Am extends BaseCommand {
88 private static final String SHELL_PACKAGE_NAME = "com.android.shell";
90 // Is the object moving in a positive direction?
91 private static final boolean MOVING_FORWARD = true;
92 // Is the object moving in the horizontal plan?
93 private static final boolean MOVING_HORIZONTALLY = true;
94 // Is the object current point great then its target point?
95 private static final boolean GREATER_THAN_TARGET = true;
96 // Amount we reduce the stack size by when testing a task re-size.
97 private static final int STACK_BOUNDS_INSET = 10;
99 private IActivityManager mAm;
100 private IPackageManager mPm;
102 private int mStartFlags = 0;
103 private boolean mWaitOption = false;
104 private boolean mStopOption = false;
106 private int mRepeat = 0;
108 private String mReceiverPermission;
110 private String mProfileFile;
111 private int mSamplingInterval;
112 private boolean mAutoStop;
113 private int mStackId;
116 * Command-line entry point.
118 * @param args The command-line arguments
120 public static void main(String[] args) {
121 (new Am()).run(args);
125 public void onShowUsage(PrintStream out) {
126 PrintWriter pw = new PrintWriter(out);
128 "usage: am [subcommand] [options]\n" +
129 "usage: am start [-D] [-N] [-W] [-P <FILE>] [--start-profiler <FILE>]\n" +
130 " [--sampling INTERVAL] [-R COUNT] [-S]\n" +
131 " [--track-allocation] [--user <USER_ID> | current] <INTENT>\n" +
132 " am startservice [--user <USER_ID> | current] <INTENT>\n" +
133 " am stopservice [--user <USER_ID> | current] <INTENT>\n" +
134 " am force-stop [--user <USER_ID> | all | current] <PACKAGE>\n" +
135 " am kill [--user <USER_ID> | all | current] <PACKAGE>\n" +
137 " am broadcast [--user <USER_ID> | all | current] <INTENT>\n" +
138 " am instrument [-r] [-e <NAME> <VALUE>] [-p <FILE>] [-w]\n" +
139 " [--user <USER_ID> | current]\n" +
140 " [--no-window-animation] [--abi <ABI>] <COMPONENT>\n" +
141 " am profile start [--user <USER_ID> current] [--sampling INTERVAL] <PROCESS> <FILE>\n" +
142 " am profile stop [--user <USER_ID> current] [<PROCESS>]\n" +
143 " am dumpheap [--user <USER_ID> current] [-n] <PROCESS> <FILE>\n" +
144 " am set-debug-app [-w] [--persistent] <PACKAGE>\n" +
145 " am clear-debug-app\n" +
146 " am set-watch-heap <PROCESS> <MEM-LIMIT>\n" +
147 " am clear-watch-heap\n" +
148 " am bug-report [--progress]\n" +
149 " am monitor [--gdb <port>]\n" +
150 " am hang [--allow-restart]\n" +
152 " am idle-maintenance\n" +
153 " am screen-compat [on|off] <PACKAGE>\n" +
154 " am package-importance <PACKAGE>\n" +
155 " am to-uri [INTENT]\n" +
156 " am to-intent-uri [INTENT]\n" +
157 " am to-app-uri [INTENT]\n" +
158 " am switch-user <USER_ID>\n" +
159 " am start-user <USER_ID>\n" +
160 " am unlock-user <USER_ID> [TOKEN_HEX]\n" +
161 " am stop-user [-w] [-f] <USER_ID>\n" +
162 " am stack start <DISPLAY_ID> <INTENT>\n" +
163 " am stack movetask <TASK_ID> <STACK_ID> [true|false]\n" +
164 " am stack resize <STACK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" +
165 " am stack resize-animated <STACK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" +
166 " am stack resize-docked-stack <LEFT,TOP,RIGHT,BOTTOM> [<TASK_LEFT,TASK_TOP,TASK_RIGHT,TASK_BOTTOM>]\n" +
167 " am stack size-docked-stack-test: <STEP_SIZE> <l|t|r|b> [DELAY_MS]\n" +
168 " am stack move-top-activity-to-pinned-stack: <STACK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" +
169 " am stack positiontask <TASK_ID> <STACK_ID> <POSITION>\n" +
171 " am stack info <STACK_ID>\n" +
172 " am stack remove <STACK_ID>\n" +
173 " am task lock <TASK_ID>\n" +
174 " am task lock stop\n" +
175 " am task resizeable <TASK_ID> [0 (unresizeable) | 1 (crop_windows) | 2 (resizeable) | 3 (resizeable_and_pipable)]\n" +
176 " am task resize <TASK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" +
177 " am task drag-task-test <TASK_ID> <STEP_SIZE> [DELAY_MS] \n" +
178 " am task size-task-test <TASK_ID> <STEP_SIZE> [DELAY_MS] \n" +
180 " am suppress-resize-config-changes <true|false>\n" +
181 " am set-inactive [--user <USER_ID>] <PACKAGE> true|false\n" +
182 " am get-inactive [--user <USER_ID>] <PACKAGE>\n" +
183 " am send-trim-memory [--user <USER_ID>] <PROCESS>\n" +
184 " [HIDDEN|RUNNING_MODERATE|BACKGROUND|RUNNING_LOW|MODERATE|RUNNING_CRITICAL|COMPLETE]\n" +
185 " am get-current-user\n" +
187 "am start: start an Activity. Options are:\n" +
188 " -D: enable debugging\n" +
189 " -N: enable native debugging\n" +
190 " -W: wait for launch to complete\n" +
191 " --start-profiler <FILE>: start profiler and send results to <FILE>\n" +
192 " --sampling INTERVAL: use sample profiling with INTERVAL microseconds\n" +
193 " between samples (use with --start-profiler)\n" +
194 " -P <FILE>: like above, but profiling stops when app goes idle\n" +
195 " -R: repeat the activity launch <COUNT> times. Prior to each repeat,\n" +
196 " the top activity will be finished.\n" +
197 " -S: force stop the target app before starting the activity\n" +
198 " --track-allocation: enable tracking of object allocations\n" +
199 " --user <USER_ID> | current: Specify which user to run as; if not\n" +
200 " specified then run as the current user.\n" +
201 " --stack <STACK_ID>: Specify into which stack should the activity be put." +
203 "am startservice: start a Service. Options are:\n" +
204 " --user <USER_ID> | current: Specify which user to run as; if not\n" +
205 " specified then run as the current user.\n" +
207 "am stopservice: stop a Service. Options are:\n" +
208 " --user <USER_ID> | current: Specify which user to run as; if not\n" +
209 " specified then run as the current user.\n" +
211 "am force-stop: force stop everything associated with <PACKAGE>.\n" +
212 " --user <USER_ID> | all | current: Specify user to force stop;\n" +
213 " all users if not specified.\n" +
215 "am kill: Kill all processes associated with <PACKAGE>. Only kills.\n" +
216 " processes that are safe to kill -- that is, will not impact the user\n" +
218 " --user <USER_ID> | all | current: Specify user whose processes to kill;\n" +
219 " all users if not specified.\n" +
221 "am kill-all: Kill all background processes.\n" +
223 "am broadcast: send a broadcast Intent. Options are:\n" +
224 " --user <USER_ID> | all | current: Specify which user to send to; if not\n" +
225 " specified then send to all users.\n" +
226 " --receiver-permission <PERMISSION>: Require receiver to hold permission.\n" +
228 "am instrument: start an Instrumentation. Typically this target <COMPONENT>\n" +
229 " is the form <TEST_PACKAGE>/<RUNNER_CLASS> or only <TEST_PACKAGE> if there \n" +
230 " is only one instrumentation. Options are:\n" +
231 " -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT). Use with\n" +
232 " [-e perf true] to generate raw output for performance measurements.\n" +
233 " -e <NAME> <VALUE>: set argument <NAME> to <VALUE>. For test runners a\n" +
234 " common form is [-e <testrunner_flag> <value>[,<value>...]].\n" +
235 " -p <FILE>: write profiling data to <FILE>\n" +
236 " -w: wait for instrumentation to finish before returning. Required for\n" +
238 " --user <USER_ID> | current: Specify user instrumentation runs in;\n" +
239 " current user if not specified.\n" +
240 " --no-window-animation: turn off window animations while running.\n" +
241 " --abi <ABI>: Launch the instrumented process with the selected ABI.\n" +
242 " This assumes that the process supports the selected ABI.\n" +
244 "am trace-ipc: Trace IPC transactions.\n" +
245 " start: start tracing IPC transactions.\n" +
246 " stop: stop tracing IPC transactions and dump the results to file.\n" +
247 " --dump-file <FILE>: Specify the file the trace should be dumped to.\n" +
249 "am profile: start and stop profiler on a process. The given <PROCESS> argument\n" +
250 " may be either a process name or pid. Options are:\n" +
251 " --user <USER_ID> | current: When supplying a process name,\n" +
252 " specify user of process to profile; uses current user if not specified.\n" +
254 "am dumpheap: dump the heap of a process. The given <PROCESS> argument may\n" +
255 " be either a process name or pid. Options are:\n" +
256 " -n: dump native heap instead of managed heap\n" +
257 " --user <USER_ID> | current: When supplying a process name,\n" +
258 " specify user of process to dump; uses current user if not specified.\n" +
260 "am set-debug-app: set application <PACKAGE> to debug. Options are:\n" +
261 " -w: wait for debugger when application starts\n" +
262 " --persistent: retain this value\n" +
264 "am clear-debug-app: clear the previously set-debug-app.\n" +
266 "am set-watch-heap: start monitoring pss size of <PROCESS>, if it is at or\n" +
267 " above <HEAP-LIMIT> then a heap dump is collected for the user to report\n" +
269 "am clear-watch-heap: clear the previously set-watch-heap.\n" +
271 "am bug-report: request bug report generation; will launch a notification\n" +
272 " when done to select where it should be delivered. Options are: \n" +
273 " --progress: will launch a notification right away to show its progress.\n" +
275 "am monitor: start monitoring for crashes or ANRs.\n" +
276 " --gdb: start gdbserv on the given port at crash/ANR\n" +
278 "am hang: hang the system.\n" +
279 " --allow-restart: allow watchdog to perform normal system restart\n" +
281 "am restart: restart the user-space system.\n" +
283 "am idle-maintenance: perform idle maintenance now.\n" +
285 "am screen-compat: control screen compatibility mode of <PACKAGE>.\n" +
287 "am package-importance: print current importance of <PACKAGE>.\n" +
289 "am to-uri: print the given Intent specification as a URI.\n" +
291 "am to-intent-uri: print the given Intent specification as an intent: URI.\n" +
293 "am to-app-uri: print the given Intent specification as an android-app: URI.\n" +
295 "am switch-user: switch to put USER_ID in the foreground, starting\n" +
296 " execution of that user if it is currently stopped.\n" +
298 "am start-user: start USER_ID in background if it is currently stopped,\n" +
299 " use switch-user if you want to start the user in foreground.\n" +
301 "am stop-user: stop execution of USER_ID, not allowing it to run any\n" +
302 " code until a later explicit start or switch to it.\n" +
303 " -w: wait for stop-user to complete.\n" +
304 " -f: force stop even if there are related users that cannot be stopped.\n" +
306 "am stack start: start a new activity on <DISPLAY_ID> using <INTENT>.\n" +
308 "am stack movetask: move <TASK_ID> from its current stack to the top (true) or" +
309 " bottom (false) of <STACK_ID>.\n" +
311 "am stack resize: change <STACK_ID> size and position to <LEFT,TOP,RIGHT,BOTTOM>.\n" +
313 "am stack resize-docked-stack: change docked stack to <LEFT,TOP,RIGHT,BOTTOM>\n" +
314 " and supplying temporary different task bounds indicated by\n" +
315 " <TASK_LEFT,TOP,RIGHT,BOTTOM>\n" +
317 "am stack size-docked-stack-test: test command for sizing docked stack by\n" +
318 " <STEP_SIZE> increments from the side <l>eft, <t>op, <r>ight, or <b>ottom\n" +
319 " applying the optional [DELAY_MS] between each step.\n" +
321 "am stack move-top-activity-to-pinned-stack: moves the top activity from\n" +
322 " <STACK_ID> to the pinned stack using <LEFT,TOP,RIGHT,BOTTOM> for the\n" +
323 " bounds of the pinned stack.\n" +
325 "am stack positiontask: place <TASK_ID> in <STACK_ID> at <POSITION>" +
327 "am stack list: list all of the activity stacks and their sizes.\n" +
329 "am stack info: display the information about activity stack <STACK_ID>.\n" +
331 "am stack remove: remove stack <STACK_ID>.\n" +
333 "am task lock: bring <TASK_ID> to the front and don't allow other tasks to run.\n" +
335 "am task lock stop: end the current task lock.\n" +
337 "am task resizeable: change resizeable mode of <TASK_ID>.\n" +
338 " 0 (unresizeable) | 1 (crop_windows) | 2 (resizeable) | 3 (resizeable_and_pipable)\n" +
340 "am task resize: makes sure <TASK_ID> is in a stack with the specified bounds.\n" +
341 " Forces the task to be resizeable and creates a stack if no existing stack\n" +
342 " has the specified bounds.\n" +
344 "am task drag-task-test: test command for dragging/moving <TASK_ID> by\n" +
345 " <STEP_SIZE> increments around the screen applying the optional [DELAY_MS]\n" +
346 " between each step.\n" +
348 "am task size-task-test: test command for sizing <TASK_ID> by <STEP_SIZE>" +
349 " increments within the screen applying the optional [DELAY_MS] between\n" +
352 "am get-config: retrieve the configuration and any recent configurations\n" +
353 " of the device.\n" +
354 "am suppress-resize-config-changes: suppresses configuration changes due to\n" +
355 " user resizing an activity/task.\n" +
357 "am set-inactive: sets the inactive state of an app.\n" +
359 "am get-inactive: returns the inactive state of an app.\n" +
361 "am send-trim-memory: send a memory trim event to a <PROCESS>.\n" +
363 "am get-current-user: returns id of the current foreground user.\n" +
366 Intent.printIntentArgsHelp(pw, "");
371 public void onRun() throws Exception {
373 mAm = ActivityManagerNative.getDefault();
375 System.err.println(NO_SYSTEM_ERROR_CODE);
376 throw new AndroidException("Can't connect to activity manager; is the system running?");
379 mPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
381 System.err.println(NO_SYSTEM_ERROR_CODE);
382 throw new AndroidException("Can't connect to package manager; is the system running?");
385 String op = nextArgRequired();
387 if (op.equals("start")) {
389 } else if (op.equals("startservice")) {
391 } else if (op.equals("stopservice")) {
393 } else if (op.equals("force-stop")) {
395 } else if (op.equals("kill")) {
397 } else if (op.equals("kill-all")) {
399 } else if (op.equals("instrument")) {
401 } else if (op.equals("trace-ipc")) {
403 } else if (op.equals("broadcast")) {
405 } else if (op.equals("profile")) {
407 } else if (op.equals("dumpheap")) {
409 } else if (op.equals("set-debug-app")) {
411 } else if (op.equals("clear-debug-app")) {
413 } else if (op.equals("set-watch-heap")) {
415 } else if (op.equals("clear-watch-heap")) {
417 } else if (op.equals("bug-report")) {
419 } else if (op.equals("monitor")) {
421 } else if (op.equals("hang")) {
423 } else if (op.equals("restart")) {
425 } else if (op.equals("idle-maintenance")) {
426 runIdleMaintenance();
427 } else if (op.equals("screen-compat")) {
429 } else if (op.equals("package-importance")) {
430 runPackageImportance();
431 } else if (op.equals("to-uri")) {
433 } else if (op.equals("to-intent-uri")) {
434 runToUri(Intent.URI_INTENT_SCHEME);
435 } else if (op.equals("to-app-uri")) {
436 runToUri(Intent.URI_ANDROID_APP_SCHEME);
437 } else if (op.equals("switch-user")) {
439 } else if (op.equals("start-user")) {
440 runStartUserInBackground();
441 } else if (op.equals("unlock-user")) {
443 } else if (op.equals("stop-user")) {
445 } else if (op.equals("stack")) {
447 } else if (op.equals("task")) {
449 } else if (op.equals("get-config")) {
451 } else if (op.equals("suppress-resize-config-changes")) {
452 runSuppressResizeConfigChanges();
453 } else if (op.equals("set-inactive")) {
455 } else if (op.equals("get-inactive")) {
457 } else if (op.equals("send-trim-memory")) {
459 } else if (op.equals("get-current-user")) {
462 showError("Error: unknown command '" + op + "'");
466 int parseUserArg(String arg) {
468 if ("all".equals(arg)) {
469 userId = UserHandle.USER_ALL;
470 } else if ("current".equals(arg) || "cur".equals(arg)) {
471 userId = UserHandle.USER_CURRENT;
473 userId = Integer.parseInt(arg);
478 private Intent makeIntent(int defUser) throws URISyntaxException {
484 mSamplingInterval = 0;
487 mStackId = INVALID_STACK_ID;
489 return Intent.parseCommandArgs(mArgs, new Intent.CommandOptionHandler() {
491 public boolean handleOption(String opt, ShellCommand cmd) {
492 if (opt.equals("-D")) {
493 mStartFlags |= ActivityManager.START_FLAG_DEBUG;
494 } else if (opt.equals("-N")) {
495 mStartFlags |= ActivityManager.START_FLAG_NATIVE_DEBUGGING;
496 } else if (opt.equals("-W")) {
498 } else if (opt.equals("-P")) {
499 mProfileFile = nextArgRequired();
501 } else if (opt.equals("--start-profiler")) {
502 mProfileFile = nextArgRequired();
504 } else if (opt.equals("--sampling")) {
505 mSamplingInterval = Integer.parseInt(nextArgRequired());
506 } else if (opt.equals("-R")) {
507 mRepeat = Integer.parseInt(nextArgRequired());
508 } else if (opt.equals("-S")) {
510 } else if (opt.equals("--track-allocation")) {
511 mStartFlags |= ActivityManager.START_FLAG_TRACK_ALLOCATION;
512 } else if (opt.equals("--user")) {
513 mUserId = parseUserArg(nextArgRequired());
514 } else if (opt.equals("--receiver-permission")) {
515 mReceiverPermission = nextArgRequired();
516 } else if (opt.equals("--stack")) {
517 mStackId = Integer.parseInt(nextArgRequired());
526 private void runStartService() throws Exception {
527 Intent intent = makeIntent(UserHandle.USER_CURRENT);
528 if (mUserId == UserHandle.USER_ALL) {
529 System.err.println("Error: Can't start activity with user 'all'");
532 System.out.println("Starting service: " + intent);
533 ComponentName cn = mAm.startService(null, intent, intent.getType(),
534 SHELL_PACKAGE_NAME, mUserId);
536 System.err.println("Error: Not found; no service started.");
537 } else if (cn.getPackageName().equals("!")) {
538 System.err.println("Error: Requires permission " + cn.getClassName());
539 } else if (cn.getPackageName().equals("!!")) {
540 System.err.println("Error: " + cn.getClassName());
544 private void runStopService() throws Exception {
545 Intent intent = makeIntent(UserHandle.USER_CURRENT);
546 if (mUserId == UserHandle.USER_ALL) {
547 System.err.println("Error: Can't stop activity with user 'all'");
550 System.out.println("Stopping service: " + intent);
551 int result = mAm.stopService(null, intent, intent.getType(), mUserId);
553 System.err.println("Service not stopped: was not running.");
554 } else if (result == 1) {
555 System.err.println("Service stopped");
556 } else if (result == -1) {
557 System.err.println("Error stopping service");
561 private void runStart() throws Exception {
562 Intent intent = makeIntent(UserHandle.USER_CURRENT);
564 if (mUserId == UserHandle.USER_ALL) {
565 System.err.println("Error: Can't start service with user 'all'");
569 String mimeType = intent.getType();
570 if (mimeType == null && intent.getData() != null
571 && "content".equals(intent.getData().getScheme())) {
572 mimeType = mAm.getProviderMimeType(intent.getData(), mUserId);
579 if (intent.getComponent() != null) {
580 packageName = intent.getComponent().getPackageName();
582 List<ResolveInfo> activities = mPm.queryIntentActivities(intent, mimeType, 0,
584 if (activities == null || activities.size() <= 0) {
585 System.err.println("Error: Intent does not match any activities: "
588 } else if (activities.size() > 1) {
589 System.err.println("Error: Intent matches multiple activities; can't stop: "
593 packageName = activities.get(0).activityInfo.packageName;
595 System.out.println("Stopping: " + packageName);
596 mAm.forceStopPackage(packageName, mUserId);
600 System.out.println("Starting: " + intent);
601 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
603 ParcelFileDescriptor fd = null;
604 ProfilerInfo profilerInfo = null;
606 if (mProfileFile != null) {
608 fd = openForSystemServer(
609 new File(mProfileFile),
610 ParcelFileDescriptor.MODE_CREATE |
611 ParcelFileDescriptor.MODE_TRUNCATE |
612 ParcelFileDescriptor.MODE_WRITE_ONLY);
613 } catch (FileNotFoundException e) {
614 System.err.println("Error: Unable to open file: " + mProfileFile);
615 System.err.println("Consider using a file under /data/local/tmp/");
618 profilerInfo = new ProfilerInfo(mProfileFile, fd, mSamplingInterval, mAutoStop);
621 IActivityManager.WaitResult result = null;
623 final long startTime = SystemClock.uptimeMillis();
624 ActivityOptions options = null;
625 if (mStackId != INVALID_STACK_ID) {
626 options = ActivityOptions.makeBasic();
627 options.setLaunchStackId(mStackId);
630 result = mAm.startActivityAndWait(null, null, intent, mimeType,
631 null, null, 0, mStartFlags, profilerInfo,
632 options != null ? options.toBundle() : null, mUserId);
635 res = mAm.startActivityAsUser(null, null, intent, mimeType,
636 null, null, 0, mStartFlags, profilerInfo,
637 options != null ? options.toBundle() : null, mUserId);
639 final long endTime = SystemClock.uptimeMillis();
640 PrintStream out = mWaitOption ? System.out : System.err;
641 boolean launched = false;
643 case ActivityManager.START_SUCCESS:
646 case ActivityManager.START_SWITCHES_CANCELED:
649 "Warning: Activity not started because the "
650 + " current activity is being kept for the user.");
652 case ActivityManager.START_DELIVERED_TO_TOP:
655 "Warning: Activity not started, intent has "
656 + "been delivered to currently running "
657 + "top-most instance.");
659 case ActivityManager.START_RETURN_INTENT_TO_CALLER:
662 "Warning: Activity not started because intent "
663 + "should be handled by the caller");
665 case ActivityManager.START_TASK_TO_FRONT:
668 "Warning: Activity not started, its current "
669 + "task has been brought to the front");
671 case ActivityManager.START_INTENT_NOT_RESOLVED:
673 "Error: Activity not started, unable to "
674 + "resolve " + intent.toString());
676 case ActivityManager.START_CLASS_NOT_FOUND:
677 out.println(NO_CLASS_ERROR_CODE);
678 out.println("Error: Activity class " +
679 intent.getComponent().toShortString()
680 + " does not exist.");
682 case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
684 "Error: Activity not started, you requested to "
685 + "both forward and receive its result");
687 case ActivityManager.START_PERMISSION_DENIED:
689 "Error: Activity not started, you do not "
690 + "have permission to access it.");
692 case ActivityManager.START_NOT_VOICE_COMPATIBLE:
694 "Error: Activity not started, voice control not allowed for: "
697 case ActivityManager.START_NOT_CURRENT_USER_ACTIVITY:
699 "Error: Not allowed to start background user activity"
700 + " that shouldn't be displayed for all users.");
704 "Error: Activity not started, unknown error code " + res);
707 if (mWaitOption && launched) {
708 if (result == null) {
709 result = new IActivityManager.WaitResult();
710 result.who = intent.getComponent();
712 System.out.println("Status: " + (result.timeout ? "timeout" : "ok"));
713 if (result.who != null) {
714 System.out.println("Activity: " + result.who.flattenToShortString());
716 if (result.thisTime >= 0) {
717 System.out.println("ThisTime: " + result.thisTime);
719 if (result.totalTime >= 0) {
720 System.out.println("TotalTime: " + result.totalTime);
722 System.out.println("WaitTime: " + (endTime-startTime));
723 System.out.println("Complete");
729 } while (mRepeat > 1);
732 private void runForceStop() throws Exception {
733 int userId = UserHandle.USER_ALL;
736 while ((opt=nextOption()) != null) {
737 if (opt.equals("--user")) {
738 userId = parseUserArg(nextArgRequired());
740 System.err.println("Error: Unknown option: " + opt);
744 mAm.forceStopPackage(nextArgRequired(), userId);
747 private void runKill() throws Exception {
748 int userId = UserHandle.USER_ALL;
751 while ((opt=nextOption()) != null) {
752 if (opt.equals("--user")) {
753 userId = parseUserArg(nextArgRequired());
755 System.err.println("Error: Unknown option: " + opt);
759 mAm.killBackgroundProcesses(nextArgRequired(), userId);
762 private void runKillAll() throws Exception {
763 mAm.killAllBackgroundProcesses();
766 private void sendBroadcast() throws Exception {
767 Intent intent = makeIntent(UserHandle.USER_CURRENT);
768 IntentReceiver receiver = new IntentReceiver();
769 String[] requiredPermissions = mReceiverPermission == null ? null
770 : new String[] {mReceiverPermission};
771 System.out.println("Broadcasting: " + intent);
772 mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, requiredPermissions,
773 android.app.AppOpsManager.OP_NONE, null, true, false, mUserId);
774 receiver.waitForFinish();
777 private void runInstrument() throws Exception {
778 String profileFile = null;
779 boolean wait = false;
780 boolean rawMode = false;
781 boolean no_window_animation = false;
782 int userId = UserHandle.USER_CURRENT;
783 Bundle args = new Bundle();
784 String argKey = null, argValue = null;
785 IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
789 while ((opt=nextOption()) != null) {
790 if (opt.equals("-p")) {
791 profileFile = nextArgRequired();
792 } else if (opt.equals("-w")) {
794 } else if (opt.equals("-r")) {
796 } else if (opt.equals("-e")) {
797 argKey = nextArgRequired();
798 argValue = nextArgRequired();
799 args.putString(argKey, argValue);
800 } else if (opt.equals("--no_window_animation")
801 || opt.equals("--no-window-animation")) {
802 no_window_animation = true;
803 } else if (opt.equals("--user")) {
804 userId = parseUserArg(nextArgRequired());
805 } else if (opt.equals("--abi")) {
806 abi = nextArgRequired();
808 System.err.println("Error: Unknown option: " + opt);
813 if (userId == UserHandle.USER_ALL) {
814 System.err.println("Error: Can't start instrumentation with user 'all'");
818 String cnArg = nextArgRequired();
821 if (cnArg.contains("/")) {
822 cn = ComponentName.unflattenFromString(cnArg);
823 if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg);
825 List<InstrumentationInfo> infos = mPm.queryInstrumentation(null, 0).getList();
827 final int numInfos = infos == null ? 0: infos.size();
828 List<ComponentName> cns = new ArrayList<>();
829 for (int i = 0; i < numInfos; i++) {
830 InstrumentationInfo info = infos.get(i);
832 ComponentName c = new ComponentName(info.packageName, info.name);
833 if (cnArg.equals(info.packageName)) {
838 if (cns.size() == 0) {
839 throw new IllegalArgumentException("No instrumentation found for: " + cnArg);
840 } else if (cns.size() == 1) {
843 StringBuilder cnsStr = new StringBuilder();
844 final int numCns = cns.size();
845 for (int i = 0; i < numCns; i++) {
846 cnsStr.append(cns.get(i).flattenToString());
851 cnsStr.setLength(cnsStr.length() - 2);
853 throw new IllegalArgumentException("Found multiple instrumentations: "
854 + cnsStr.toString());
858 InstrumentationWatcher watcher = null;
859 UiAutomationConnection connection = null;
861 watcher = new InstrumentationWatcher();
862 watcher.setRawOutput(rawMode);
863 connection = new UiAutomationConnection();
866 float[] oldAnims = null;
867 if (no_window_animation) {
868 oldAnims = wm.getAnimationScales();
869 wm.setAnimationScale(0, 0.0f);
870 wm.setAnimationScale(1, 0.0f);
874 final String[] supportedAbis = Build.SUPPORTED_ABIS;
875 boolean matched = false;
876 for (String supportedAbi : supportedAbis) {
877 if (supportedAbi.equals(abi)) {
884 throw new AndroidException(
885 "INSTRUMENTATION_FAILED: Unsupported instruction set " + abi);
889 if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher, connection, userId, abi)) {
890 throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString());
893 if (watcher != null) {
894 if (!watcher.waitForFinish()) {
895 System.out.println("INSTRUMENTATION_ABORTED: System has crashed.");
899 if (oldAnims != null) {
900 wm.setAnimationScales(oldAnims);
904 private void runTraceIpc() throws Exception {
905 String op = nextArgRequired();
906 if (op.equals("start")) {
908 } else if (op.equals("stop")) {
911 showError("Error: unknown command '" + op + "'");
916 private void runTraceIpcStart() throws Exception {
917 System.out.println("Starting IPC tracing.");
918 mAm.startBinderTracking();
921 private void runTraceIpcStop() throws Exception {
923 String filename = null;
924 while ((opt=nextOption()) != null) {
925 if (opt.equals("--dump-file")) {
926 filename = nextArgRequired();
928 System.err.println("Error: Unknown option: " + opt);
932 if (filename == null) {
933 System.err.println("Error: Specify filename to dump logs to.");
937 ParcelFileDescriptor fd = null;
940 File file = new File(filename);
942 fd = openForSystemServer(file,
943 ParcelFileDescriptor.MODE_CREATE |
944 ParcelFileDescriptor.MODE_TRUNCATE |
945 ParcelFileDescriptor.MODE_WRITE_ONLY);
946 } catch (FileNotFoundException e) {
947 System.err.println("Error: Unable to open file: " + filename);
948 System.err.println("Consider using a file under /data/local/tmp/");
953 if (!mAm.stopBinderTrackingAndDump(fd)) {
954 throw new AndroidException("STOP TRACE FAILED.");
957 System.out.println("Stopped IPC tracing. Dumping logs to: " + filename);
960 static void removeWallOption() {
961 String props = SystemProperties.get("dalvik.vm.extra-opts");
962 if (props != null && props.contains("-Xprofile:wallclock")) {
963 props = props.replace("-Xprofile:wallclock", "");
964 props = props.trim();
965 SystemProperties.set("dalvik.vm.extra-opts", props);
969 private void runProfile() throws Exception {
970 String profileFile = null;
971 boolean start = false;
972 boolean wall = false;
973 int userId = UserHandle.USER_CURRENT;
975 mSamplingInterval = 0;
977 String process = null;
979 String cmd = nextArgRequired();
981 if ("start".equals(cmd)) {
984 while ((opt=nextOption()) != null) {
985 if (opt.equals("--user")) {
986 userId = parseUserArg(nextArgRequired());
987 } else if (opt.equals("--wall")) {
989 } else if (opt.equals("--sampling")) {
990 mSamplingInterval = Integer.parseInt(nextArgRequired());
992 System.err.println("Error: Unknown option: " + opt);
996 process = nextArgRequired();
997 } else if ("stop".equals(cmd)) {
999 while ((opt=nextOption()) != null) {
1000 if (opt.equals("--user")) {
1001 userId = parseUserArg(nextArgRequired());
1003 System.err.println("Error: Unknown option: " + opt);
1007 process = nextArg();
1009 // Compatibility with old syntax: process is specified first.
1011 cmd = nextArgRequired();
1012 if ("start".equals(cmd)) {
1014 } else if (!"stop".equals(cmd)) {
1015 throw new IllegalArgumentException("Profile command " + process + " not valid");
1019 if (userId == UserHandle.USER_ALL) {
1020 System.err.println("Error: Can't profile with user 'all'");
1024 ParcelFileDescriptor fd = null;
1025 ProfilerInfo profilerInfo = null;
1028 profileFile = nextArgRequired();
1030 fd = openForSystemServer(
1031 new File(profileFile),
1032 ParcelFileDescriptor.MODE_CREATE |
1033 ParcelFileDescriptor.MODE_TRUNCATE |
1034 ParcelFileDescriptor.MODE_WRITE_ONLY);
1035 } catch (FileNotFoundException e) {
1036 System.err.println("Error: Unable to open file: " + profileFile);
1037 System.err.println("Consider using a file under /data/local/tmp/");
1040 profilerInfo = new ProfilerInfo(profileFile, fd, mSamplingInterval, false);
1045 // XXX doesn't work -- this needs to be set before booting.
1046 String props = SystemProperties.get("dalvik.vm.extra-opts");
1047 if (props == null || !props.contains("-Xprofile:wallclock")) {
1048 props = props + " -Xprofile:wallclock";
1049 //SystemProperties.set("dalvik.vm.extra-opts", props);
1052 //removeWallOption();
1054 if (!mAm.profileControl(process, userId, start, profilerInfo, profileType)) {
1056 throw new AndroidException("PROFILE FAILED on process " + process);
1060 //removeWallOption();
1065 private void runDumpHeap() throws Exception {
1066 boolean managed = true;
1067 int userId = UserHandle.USER_CURRENT;
1070 while ((opt=nextOption()) != null) {
1071 if (opt.equals("--user")) {
1072 userId = parseUserArg(nextArgRequired());
1073 if (userId == UserHandle.USER_ALL) {
1074 System.err.println("Error: Can't dump heap with user 'all'");
1077 } else if (opt.equals("-n")) {
1080 System.err.println("Error: Unknown option: " + opt);
1084 String process = nextArgRequired();
1085 String heapFile = nextArgRequired();
1086 ParcelFileDescriptor fd = null;
1089 File file = new File(heapFile);
1091 fd = openForSystemServer(file,
1092 ParcelFileDescriptor.MODE_CREATE |
1093 ParcelFileDescriptor.MODE_TRUNCATE |
1094 ParcelFileDescriptor.MODE_WRITE_ONLY);
1095 } catch (FileNotFoundException e) {
1096 System.err.println("Error: Unable to open file: " + heapFile);
1097 System.err.println("Consider using a file under /data/local/tmp/");
1101 if (!mAm.dumpHeap(process, userId, managed, heapFile, fd)) {
1102 throw new AndroidException("HEAP DUMP FAILED on process " + process);
1106 private void runSetDebugApp() throws Exception {
1107 boolean wait = false;
1108 boolean persistent = false;
1111 while ((opt=nextOption()) != null) {
1112 if (opt.equals("-w")) {
1114 } else if (opt.equals("--persistent")) {
1117 System.err.println("Error: Unknown option: " + opt);
1122 String pkg = nextArgRequired();
1123 mAm.setDebugApp(pkg, wait, persistent);
1126 private void runClearDebugApp() throws Exception {
1127 mAm.setDebugApp(null, false, true);
1130 private void runSetWatchHeap() throws Exception {
1131 String proc = nextArgRequired();
1132 String limit = nextArgRequired();
1133 mAm.setDumpHeapDebugLimit(proc, 0, Long.parseLong(limit), null);
1136 private void runClearWatchHeap() throws Exception {
1137 String proc = nextArgRequired();
1138 mAm.setDumpHeapDebugLimit(proc, 0, -1, null);
1141 private void runBugReport() throws Exception {
1143 int bugreportType = ActivityManager.BUGREPORT_OPTION_FULL;
1144 while ((opt=nextOption()) != null) {
1145 if (opt.equals("--progress")) {
1146 bugreportType = ActivityManager.BUGREPORT_OPTION_INTERACTIVE;
1148 System.err.println("Error: Unknown option: " + opt);
1152 mAm.requestBugReport(bugreportType);
1153 System.out.println("Your lovely bug report is being created; please be patient.");
1156 private void runSwitchUser() throws Exception {
1157 String user = nextArgRequired();
1158 mAm.switchUser(Integer.parseInt(user));
1161 private void runStartUserInBackground() throws Exception {
1162 String user = nextArgRequired();
1163 boolean success = mAm.startUserInBackground(Integer.parseInt(user));
1165 System.out.println("Success: user started");
1167 System.err.println("Error: could not start user");
1171 private byte[] argToBytes(String arg) {
1172 if (arg.equals("!")) {
1175 return HexDump.hexStringToByteArray(arg);
1179 private void runUnlockUser() throws Exception {
1180 int userId = Integer.parseInt(nextArgRequired());
1181 byte[] token = argToBytes(nextArgRequired());
1182 byte[] secret = argToBytes(nextArgRequired());
1183 boolean success = mAm.unlockUser(userId, token, secret, null);
1185 System.out.println("Success: user unlocked");
1187 System.err.println("Error: could not unlock user");
1191 private static class StopUserCallback extends IStopUserCallback.Stub {
1192 private boolean mFinished = false;
1194 public synchronized void waitForFinish() {
1196 while (!mFinished) wait();
1197 } catch (InterruptedException e) {
1198 throw new IllegalStateException(e);
1203 public synchronized void userStopped(int userId) {
1209 public synchronized void userStopAborted(int userId) {
1215 private void runStopUser() throws Exception {
1216 boolean wait = false;
1217 boolean force = false;
1219 while ((opt = nextOption()) != null) {
1220 if ("-w".equals(opt)) {
1222 } else if ("-f".equals(opt)) {
1225 System.err.println("Error: unknown option: " + opt);
1229 int user = Integer.parseInt(nextArgRequired());
1230 StopUserCallback callback = wait ? new StopUserCallback() : null;
1232 int res = mAm.stopUser(user, force, callback);
1233 if (res != ActivityManager.USER_OP_SUCCESS) {
1236 case ActivityManager.USER_OP_IS_CURRENT:
1237 txt = " (Can't stop current user)";
1239 case ActivityManager.USER_OP_UNKNOWN_USER:
1240 txt = " (Unknown user " + user + ")";
1242 case ActivityManager.USER_OP_ERROR_IS_SYSTEM:
1243 txt = " (System user cannot be stopped)";
1245 case ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP:
1246 txt = " (Can't stop user " + user
1247 + " - one of its related users can't be stopped)";
1250 System.err.println("Switch failed: " + res + txt);
1251 } else if (callback != null) {
1252 callback.waitForFinish();
1256 class MyActivityController extends IActivityController.Stub {
1257 final String mGdbPort;
1258 final boolean mMonkey;
1260 static final int STATE_NORMAL = 0;
1261 static final int STATE_CRASHED = 1;
1262 static final int STATE_EARLY_ANR = 2;
1263 static final int STATE_ANR = 3;
1267 static final int RESULT_DEFAULT = 0;
1269 static final int RESULT_CRASH_DIALOG = 0;
1270 static final int RESULT_CRASH_KILL = 1;
1272 static final int RESULT_EARLY_ANR_CONTINUE = 0;
1273 static final int RESULT_EARLY_ANR_KILL = 1;
1275 static final int RESULT_ANR_DIALOG = 0;
1276 static final int RESULT_ANR_KILL = 1;
1277 static final int RESULT_ANR_WAIT = 1;
1281 Process mGdbProcess;
1283 boolean mGotGdbPrint;
1285 MyActivityController(String gdbPort, boolean monkey) {
1291 public boolean activityResuming(String pkg) {
1292 synchronized (this) {
1293 System.out.println("** Activity resuming: " + pkg);
1299 public boolean activityStarting(Intent intent, String pkg) {
1300 synchronized (this) {
1301 System.out.println("** Activity starting: " + pkg);
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;
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;
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;
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.");
1364 void killGdbLocked() {
1365 mGotGdbPrint = false;
1366 if (mGdbProcess != null) {
1367 System.out.println("Stopping gdbserver");
1368 mGdbProcess.destroy();
1371 if (mGdbThread != null) {
1372 mGdbThread.interrupt();
1377 int waitControllerLocked(int pid, int state) {
1378 if (mGdbPort != null) {
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);
1387 mGdbProcess = Runtime.getRuntime().exec(new String[] {
1388 "gdbserver", ":" + mGdbPort, "--attach", Integer.toString(pid)
1390 final InputStreamReader converter = new InputStreamReader(
1391 mGdbProcess.getInputStream());
1392 mGdbThread = new Thread() {
1395 BufferedReader in = new BufferedReader(converter);
1399 synchronized (MyActivityController.this) {
1400 if (mGdbThread == null) {
1404 mGotGdbPrint = true;
1405 MyActivityController.this.notifyAll();
1409 line = in.readLine();
1413 System.out.println("GDB: " + line);
1415 } catch (IOException e) {
1423 // Stupid waiting for .5s. Doesn't matter if we end early.
1426 } catch (InterruptedException e) {
1429 } catch (IOException e) {
1430 System.err.println("Failure starting gdbserver: " + e);
1435 System.out.println("");
1436 printMessageForState();
1438 while (mState != STATE_NORMAL) {
1441 } catch (InterruptedException e) {
1450 void resumeController(int result) {
1451 synchronized (this) {
1452 mState = STATE_NORMAL;
1458 void printMessageForState() {
1461 System.out.println("Monitoring activity manager... available commands:");
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");
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");
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");
1480 System.out.println("(q)uit: finish monitoring");
1483 void run() throws RemoteException {
1485 printMessageForState();
1487 mAm.setActivityController(this, mMonkey);
1488 mState = STATE_NORMAL;
1490 InputStreamReader converter = new InputStreamReader(System.in);
1491 BufferedReader in = new BufferedReader(converter);
1494 while ((line = in.readLine()) != null) {
1495 boolean addNewline = true;
1496 if (line.length() <= 0) {
1498 } else if ("q".equals(line) || "quit".equals(line)) {
1499 resumeController(RESULT_DEFAULT);
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);
1507 System.out.println("Invalid command: " + line);
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);
1517 System.out.println("Invalid command: " + line);
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);
1525 System.out.println("Invalid command: " + line);
1528 System.out.println("Invalid command: " + line);
1531 synchronized (this) {
1533 System.out.println("");
1535 printMessageForState();
1539 } catch (IOException e) {
1540 e.printStackTrace();
1542 mAm.setActivityController(null, mMonkey);
1547 private void runMonitor() throws Exception {
1549 String gdbPort = null;
1550 boolean monkey = false;
1551 while ((opt=nextOption()) != null) {
1552 if (opt.equals("--gdb")) {
1553 gdbPort = nextArgRequired();
1554 } else if (opt.equals("-m")) {
1557 System.err.println("Error: Unknown option: " + opt);
1562 MyActivityController controller = new MyActivityController(gdbPort, monkey);
1566 private void runHang() throws Exception {
1568 boolean allowRestart = false;
1569 while ((opt=nextOption()) != null) {
1570 if (opt.equals("--allow-restart")) {
1571 allowRestart = true;
1573 System.err.println("Error: Unknown option: " + opt);
1578 System.out.println("Hanging the system...");
1579 mAm.hang(new Binder(), allowRestart);
1582 private void runRestart() throws Exception {
1584 while ((opt=nextOption()) != null) {
1585 System.err.println("Error: Unknown option: " + opt);
1589 System.out.println("Restart the system...");
1593 private void runIdleMaintenance() throws Exception {
1595 while ((opt=nextOption()) != null) {
1596 System.err.println("Error: Unknown option: " + opt);
1600 System.out.println("Performing idle maintenance...");
1602 mAm.sendIdleJobTrigger();
1603 } catch (RemoteException e) {
1607 private void runScreenCompat() throws Exception {
1608 String mode = nextArgRequired();
1610 if ("on".equals(mode)) {
1612 } else if ("off".equals(mode)) {
1615 System.err.println("Error: enabled mode must be 'on' or 'off' at " + mode);
1619 String packageName = nextArgRequired();
1622 mAm.setPackageScreenCompatMode(packageName, enabled
1623 ? ActivityManager.COMPAT_MODE_ENABLED
1624 : ActivityManager.COMPAT_MODE_DISABLED);
1625 } catch (RemoteException e) {
1627 packageName = nextArg();
1628 } while (packageName != null);
1631 private void runPackageImportance() throws Exception {
1632 String packageName = nextArgRequired();
1634 int procState = mAm.getPackageProcessState(packageName, "com.android.shell");
1636 ActivityManager.RunningAppProcessInfo.procStateToImportance(procState));
1637 } catch (RemoteException e) {
1641 private void runToUri(int flags) throws Exception {
1642 Intent intent = makeIntent(UserHandle.USER_CURRENT);
1643 System.out.println(intent.toUri(flags));
1646 private class IntentReceiver extends IIntentReceiver.Stub {
1647 private boolean mFinished = false;
1650 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
1651 boolean ordered, boolean sticky, int sendingUser) {
1652 String line = "Broadcast completed: result=" + resultCode;
1653 if (data != null) line = line + ", data=\"" + data + "\"";
1654 if (extras != null) line = line + ", extras: " + extras;
1655 System.out.println(line);
1656 synchronized (this) {
1662 public synchronized void waitForFinish() {
1664 while (!mFinished) wait();
1665 } catch (InterruptedException e) {
1666 throw new IllegalStateException(e);
1671 private class InstrumentationWatcher extends IInstrumentationWatcher.Stub {
1672 private boolean mFinished = false;
1673 private boolean mRawMode = false;
1676 * Set or reset "raw mode". In "raw mode", all bundles are dumped. In "pretty mode",
1677 * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that.
1678 * @param rawMode true for raw mode, false for pretty mode.
1680 public void setRawOutput(boolean rawMode) {
1685 public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) {
1686 synchronized (this) {
1687 // pretty printer mode?
1688 String pretty = null;
1689 if (!mRawMode && results != null) {
1690 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
1692 if (pretty != null) {
1693 System.out.print(pretty);
1695 if (results != null) {
1696 for (String key : results.keySet()) {
1698 "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key));
1701 System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode);
1708 public void instrumentationFinished(ComponentName name, int resultCode,
1710 synchronized (this) {
1711 // pretty printer mode?
1712 String pretty = null;
1713 if (!mRawMode && results != null) {
1714 pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
1716 if (pretty != null) {
1717 System.out.println(pretty);
1719 if (results != null) {
1720 for (String key : results.keySet()) {
1722 "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key));
1725 System.out.println("INSTRUMENTATION_CODE: " + resultCode);
1732 public boolean waitForFinish() {
1733 synchronized (this) {
1734 while (!mFinished) {
1736 if (!mAm.asBinder().pingBinder()) {
1740 } catch (InterruptedException e) {
1741 throw new IllegalStateException(e);
1749 private void runStack() throws Exception {
1750 String op = nextArgRequired();
1761 case "resize-animated":
1762 runStackResizeAnimated();
1764 case "resize-docked-stack":
1765 runStackResizeDocked();
1767 case "positiontask":
1768 runStackPositionTask();
1776 case "move-top-activity-to-pinned-stack":
1777 runMoveTopActivityToPinnedStack();
1779 case "size-docked-stack-test":
1780 runStackSizeDockedStackTest();
1786 showError("Error: unknown command '" + op + "'");
1791 private void runStackStart() throws Exception {
1792 String displayIdStr = nextArgRequired();
1793 int displayId = Integer.parseInt(displayIdStr);
1794 Intent intent = makeIntent(UserHandle.USER_CURRENT);
1797 IActivityContainer container = mAm.createStackOnDisplay(displayId);
1798 if (container != null) {
1799 container.startActivity(intent);
1801 } catch (RemoteException e) {
1805 private void runStackMoveTask() throws Exception {
1806 String taskIdStr = nextArgRequired();
1807 int taskId = Integer.parseInt(taskIdStr);
1808 String stackIdStr = nextArgRequired();
1809 int stackId = Integer.parseInt(stackIdStr);
1810 String toTopStr = nextArgRequired();
1811 final boolean toTop;
1812 if ("true".equals(toTopStr)) {
1814 } else if ("false".equals(toTopStr)) {
1817 System.err.println("Error: bad toTop arg: " + toTopStr);
1822 mAm.moveTaskToStack(taskId, stackId, toTop);
1823 } catch (RemoteException e) {
1827 private void runStackResize() throws Exception {
1828 String stackIdStr = nextArgRequired();
1829 int stackId = Integer.parseInt(stackIdStr);
1830 final Rect bounds = getBounds();
1831 if (bounds == null) {
1832 System.err.println("Error: invalid input bounds");
1835 resizeStack(stackId, bounds, 0);
1838 private void runStackResizeAnimated() throws Exception {
1839 String stackIdStr = nextArgRequired();
1840 int stackId = Integer.parseInt(stackIdStr);
1842 if ("null".equals(mArgs.peekNextArg())) {
1845 bounds = getBounds();
1846 if (bounds == null) {
1847 System.err.println("Error: invalid input bounds");
1851 resizeStackUnchecked(stackId, bounds, 0, true);
1854 private void resizeStackUnchecked(int stackId, Rect bounds, int delayMs, boolean animate) {
1856 mAm.resizeStack(stackId, bounds, false, false, animate, -1);
1857 Thread.sleep(delayMs);
1858 } catch (RemoteException e) {
1859 showError("Error: resizing stack " + e);
1860 } catch (InterruptedException e) {
1864 private void runStackResizeDocked() throws Exception {
1865 final Rect bounds = getBounds();
1866 final Rect taskBounds = getBounds();
1867 if (bounds == null || taskBounds == null) {
1868 System.err.println("Error: invalid input bounds");
1872 mAm.resizeDockedStack(bounds, taskBounds, null, null, null);
1873 } catch (RemoteException e) {
1874 showError("Error: resizing docked stack " + e);
1878 private void resizeStack(int stackId, Rect bounds, int delayMs)
1880 if (bounds == null) {
1881 showError("Error: invalid input bounds");
1884 resizeStackUnchecked(stackId, bounds, delayMs, false);
1887 private void runStackPositionTask() throws Exception {
1888 String taskIdStr = nextArgRequired();
1889 int taskId = Integer.parseInt(taskIdStr);
1890 String stackIdStr = nextArgRequired();
1891 int stackId = Integer.parseInt(stackIdStr);
1892 String positionStr = nextArgRequired();
1893 int position = Integer.parseInt(positionStr);
1896 mAm.positionTaskInStack(taskId, stackId, position);
1897 } catch (RemoteException e) {
1901 private void runStackList() throws Exception {
1903 List<StackInfo> stacks = mAm.getAllStackInfos();
1904 for (StackInfo info : stacks) {
1905 System.out.println(info);
1907 } catch (RemoteException e) {
1911 private void runStackInfo() throws Exception {
1913 String stackIdStr = nextArgRequired();
1914 int stackId = Integer.parseInt(stackIdStr);
1915 StackInfo info = mAm.getStackInfo(stackId);
1916 System.out.println(info);
1917 } catch (RemoteException e) {
1921 private void runStackRemove() throws Exception {
1922 String stackIdStr = nextArgRequired();
1923 int stackId = Integer.parseInt(stackIdStr);
1924 mAm.removeStack(stackId);
1927 private void runMoveTopActivityToPinnedStack() throws Exception {
1928 int stackId = Integer.parseInt(nextArgRequired());
1929 final Rect bounds = getBounds();
1930 if (bounds == null) {
1931 System.err.println("Error: invalid input bounds");
1936 if (!mAm.moveTopActivityToPinnedStack(stackId, bounds)) {
1937 showError("Didn't move top activity to pinned stack.");
1939 } catch (RemoteException e) {
1940 showError("Unable to move top activity: " + e);
1945 private void runStackSizeDockedStackTest() throws Exception {
1946 final int stepSize = Integer.parseInt(nextArgRequired());
1947 final String side = nextArgRequired();
1948 final String delayStr = nextArg();
1949 final int delayMs = (delayStr != null) ? Integer.parseInt(delayStr) : 0;
1953 StackInfo info = mAm.getStackInfo(DOCKED_STACK_ID);
1955 showError("Docked stack doesn't exist");
1958 if (info.bounds == null) {
1959 showError("Docked stack doesn't have a bounds");
1962 bounds = info.bounds;
1963 } catch (RemoteException e) {
1964 showError("Unable to get docked stack info:" + e);
1968 final boolean horizontalGrowth = "l".equals(side) || "r".equals(side);
1969 final int changeSize = (horizontalGrowth ? bounds.width() : bounds.height()) / 2;
1973 currentPoint = bounds.left;
1976 currentPoint = bounds.right;
1979 currentPoint = bounds.top;
1982 currentPoint = bounds.bottom;
1985 showError("Unknown growth side: " + side);
1989 final int startPoint = currentPoint;
1990 final int minPoint = currentPoint - changeSize;
1991 final int maxPoint = currentPoint + changeSize;
1994 System.out.println("Shrinking docked stack side=" + side);
1995 while (currentPoint > minPoint) {
1996 maxChange = Math.min(stepSize, currentPoint - minPoint);
1997 currentPoint -= maxChange;
1998 setBoundsSide(bounds, side, currentPoint);
1999 resizeStack(DOCKED_STACK_ID, bounds, delayMs);
2002 System.out.println("Growing docked stack side=" + side);
2003 while (currentPoint < maxPoint) {
2004 maxChange = Math.min(stepSize, maxPoint - currentPoint);
2005 currentPoint += maxChange;
2006 setBoundsSide(bounds, side, currentPoint);
2007 resizeStack(DOCKED_STACK_ID, bounds, delayMs);
2010 System.out.println("Back to Original size side=" + side);
2011 while (currentPoint > startPoint) {
2012 maxChange = Math.min(stepSize, currentPoint - startPoint);
2013 currentPoint -= maxChange;
2014 setBoundsSide(bounds, side, currentPoint);
2015 resizeStack(DOCKED_STACK_ID, bounds, delayMs);
2019 private void setBoundsSide(Rect bounds, String side, int value) {
2022 bounds.left = value;
2025 bounds.right = value;
2031 bounds.bottom = value;
2034 showError("Unknown set side: " + side);
2039 private void runTask() throws Exception {
2040 String op = nextArgRequired();
2041 if (op.equals("lock")) {
2043 } else if (op.equals("resizeable")) {
2044 runTaskResizeable();
2045 } else if (op.equals("resize")) {
2047 } else if (op.equals("drag-task-test")) {
2048 runTaskDragTaskTest();
2049 } else if (op.equals("size-task-test")) {
2050 runTaskSizeTaskTest();
2052 showError("Error: unknown command '" + op + "'");
2057 private void runTaskLock() throws Exception {
2058 String taskIdStr = nextArgRequired();
2060 if (taskIdStr.equals("stop")) {
2061 mAm.stopLockTaskMode();
2063 int taskId = Integer.parseInt(taskIdStr);
2064 mAm.startLockTaskMode(taskId);
2066 System.err.println("Activity manager is " + (mAm.isInLockTaskMode() ? "" : "not ") +
2068 } catch (RemoteException e) {
2072 private void runTaskResizeable() throws Exception {
2073 final String taskIdStr = nextArgRequired();
2074 final int taskId = Integer.parseInt(taskIdStr);
2075 final String resizeableStr = nextArgRequired();
2076 final int resizeableMode = Integer.parseInt(resizeableStr);
2079 mAm.setTaskResizeable(taskId, resizeableMode);
2080 } catch (RemoteException e) {
2084 private void runTaskResize() throws Exception {
2085 final String taskIdStr = nextArgRequired();
2086 final int taskId = Integer.parseInt(taskIdStr);
2087 final Rect bounds = getBounds();
2088 if (bounds == null) {
2089 System.err.println("Error: invalid input bounds");
2092 taskResize(taskId, bounds, 0, false);
2095 private void taskResize(int taskId, Rect bounds, int delay_ms, boolean pretendUserResize) {
2097 final int resizeMode = pretendUserResize ? RESIZE_MODE_USER : RESIZE_MODE_SYSTEM;
2098 mAm.resizeTask(taskId, bounds, resizeMode);
2099 Thread.sleep(delay_ms);
2100 } catch (RemoteException e) {
2101 System.err.println("Error changing task bounds: " + e);
2102 } catch (InterruptedException e) {
2106 private void runTaskDragTaskTest() {
2107 final int taskId = Integer.parseInt(nextArgRequired());
2108 final int stepSize = Integer.parseInt(nextArgRequired());
2109 final String delayStr = nextArg();
2110 final int delay_ms = (delayStr != null) ? Integer.parseInt(delayStr) : 0;
2111 final StackInfo stackInfo;
2114 stackInfo = mAm.getStackInfo(mAm.getFocusedStackId());
2115 taskBounds = mAm.getTaskBounds(taskId);
2116 } catch (RemoteException e) {
2117 System.err.println("Error getting focus stack info or task bounds: " + e);
2120 final Rect stackBounds = stackInfo.bounds;
2121 int travelRight = stackBounds.width() - taskBounds.width();
2122 int travelLeft = -travelRight;
2123 int travelDown = stackBounds.height() - taskBounds.height();
2124 int travelUp = -travelDown;
2127 // We do 2 passes to get back to the original location of the task.
2128 while (passes < 2) {
2130 System.out.println("Moving right...");
2131 travelRight = moveTask(taskId, taskBounds, stackBounds, stepSize,
2132 travelRight, MOVING_FORWARD, MOVING_HORIZONTALLY, delay_ms);
2133 System.out.println("Still need to travel right by " + travelRight);
2136 System.out.println("Moving down...");
2137 travelDown = moveTask(taskId, taskBounds, stackBounds, stepSize,
2138 travelDown, MOVING_FORWARD, !MOVING_HORIZONTALLY, delay_ms);
2139 System.out.println("Still need to travel down by " + travelDown);
2142 System.out.println("Moving left...");
2143 travelLeft = moveTask(taskId, taskBounds, stackBounds, stepSize,
2144 travelLeft, !MOVING_FORWARD, MOVING_HORIZONTALLY, delay_ms);
2145 System.out.println("Still need to travel left by " + travelLeft);
2148 System.out.println("Moving up...");
2149 travelUp = moveTask(taskId, taskBounds, stackBounds, stepSize,
2150 travelUp, !MOVING_FORWARD, !MOVING_HORIZONTALLY, delay_ms);
2151 System.out.println("Still need to travel up by " + travelUp);
2154 taskBounds = mAm.getTaskBounds(taskId);
2155 } catch (RemoteException e) {
2156 System.err.println("Error getting task bounds: " + e);
2163 private int moveTask(int taskId, Rect taskRect, Rect stackRect, int stepSize,
2164 int maxToTravel, boolean movingForward, boolean horizontal, int delay_ms) {
2166 if (movingForward) {
2167 while (maxToTravel > 0
2168 && ((horizontal && taskRect.right < stackRect.right)
2169 ||(!horizontal && taskRect.bottom < stackRect.bottom))) {
2171 maxMove = Math.min(stepSize, stackRect.right - taskRect.right);
2172 maxToTravel -= maxMove;
2173 taskRect.right += maxMove;
2174 taskRect.left += maxMove;
2176 maxMove = Math.min(stepSize, stackRect.bottom - taskRect.bottom);
2177 maxToTravel -= maxMove;
2178 taskRect.top += maxMove;
2179 taskRect.bottom += maxMove;
2181 taskResize(taskId, taskRect, delay_ms, false);
2184 while (maxToTravel < 0
2185 && ((horizontal && taskRect.left > stackRect.left)
2186 ||(!horizontal && taskRect.top > stackRect.top))) {
2188 maxMove = Math.min(stepSize, taskRect.left - stackRect.left);
2189 maxToTravel -= maxMove;
2190 taskRect.right -= maxMove;
2191 taskRect.left -= maxMove;
2193 maxMove = Math.min(stepSize, taskRect.top - stackRect.top);
2194 maxToTravel -= maxMove;
2195 taskRect.top -= maxMove;
2196 taskRect.bottom -= maxMove;
2198 taskResize(taskId, taskRect, delay_ms, false);
2201 // Return the remaining distance we didn't travel because we reached the target location.
2205 private void runTaskSizeTaskTest() {
2206 final int taskId = Integer.parseInt(nextArgRequired());
2207 final int stepSize = Integer.parseInt(nextArgRequired());
2208 final String delayStr = nextArg();
2209 final int delay_ms = (delayStr != null) ? Integer.parseInt(delayStr) : 0;
2210 final StackInfo stackInfo;
2211 final Rect initialTaskBounds;
2213 stackInfo = mAm.getStackInfo(mAm.getFocusedStackId());
2214 initialTaskBounds = mAm.getTaskBounds(taskId);
2215 } catch (RemoteException e) {
2216 System.err.println("Error getting focus stack info or task bounds: " + e);
2219 final Rect stackBounds = stackInfo.bounds;
2220 stackBounds.inset(STACK_BOUNDS_INSET, STACK_BOUNDS_INSET);
2221 final Rect currentTaskBounds = new Rect(initialTaskBounds);
2224 System.out.println("Growing top-left");
2226 currentTaskBounds.top -= getStepSize(
2227 currentTaskBounds.top, stackBounds.top, stepSize, GREATER_THAN_TARGET);
2229 currentTaskBounds.left -= getStepSize(
2230 currentTaskBounds.left, stackBounds.left, stepSize, GREATER_THAN_TARGET);
2232 taskResize(taskId, currentTaskBounds, delay_ms, true);
2233 } while (stackBounds.top < currentTaskBounds.top
2234 || stackBounds.left < currentTaskBounds.left);
2236 // Back to original size
2237 System.out.println("Shrinking top-left");
2239 currentTaskBounds.top += getStepSize(
2240 currentTaskBounds.top, initialTaskBounds.top, stepSize, !GREATER_THAN_TARGET);
2242 currentTaskBounds.left += getStepSize(
2243 currentTaskBounds.left, initialTaskBounds.left, stepSize, !GREATER_THAN_TARGET);
2245 taskResize(taskId, currentTaskBounds, delay_ms, true);
2246 } while (initialTaskBounds.top > currentTaskBounds.top
2247 || initialTaskBounds.left > currentTaskBounds.left);
2249 // Size by top-right
2250 System.out.println("Growing top-right");
2252 currentTaskBounds.top -= getStepSize(
2253 currentTaskBounds.top, stackBounds.top, stepSize, GREATER_THAN_TARGET);
2255 currentTaskBounds.right += getStepSize(
2256 currentTaskBounds.right, stackBounds.right, stepSize, !GREATER_THAN_TARGET);
2258 taskResize(taskId, currentTaskBounds, delay_ms, true);
2259 } while (stackBounds.top < currentTaskBounds.top
2260 || stackBounds.right > currentTaskBounds.right);
2262 // Back to original size
2263 System.out.println("Shrinking top-right");
2265 currentTaskBounds.top += getStepSize(
2266 currentTaskBounds.top, initialTaskBounds.top, stepSize, !GREATER_THAN_TARGET);
2268 currentTaskBounds.right -= getStepSize(currentTaskBounds.right, initialTaskBounds.right,
2269 stepSize, GREATER_THAN_TARGET);
2271 taskResize(taskId, currentTaskBounds, delay_ms, true);
2272 } while (initialTaskBounds.top > currentTaskBounds.top
2273 || initialTaskBounds.right < currentTaskBounds.right);
2275 // Size by bottom-left
2276 System.out.println("Growing bottom-left");
2278 currentTaskBounds.bottom += getStepSize(
2279 currentTaskBounds.bottom, stackBounds.bottom, stepSize, !GREATER_THAN_TARGET);
2281 currentTaskBounds.left -= getStepSize(
2282 currentTaskBounds.left, stackBounds.left, stepSize, GREATER_THAN_TARGET);
2284 taskResize(taskId, currentTaskBounds, delay_ms, true);
2285 } while (stackBounds.bottom > currentTaskBounds.bottom
2286 || stackBounds.left < currentTaskBounds.left);
2288 // Back to original size
2289 System.out.println("Shrinking bottom-left");
2291 currentTaskBounds.bottom -= getStepSize(currentTaskBounds.bottom,
2292 initialTaskBounds.bottom, stepSize, GREATER_THAN_TARGET);
2294 currentTaskBounds.left += getStepSize(
2295 currentTaskBounds.left, initialTaskBounds.left, stepSize, !GREATER_THAN_TARGET);
2297 taskResize(taskId, currentTaskBounds, delay_ms, true);
2298 } while (initialTaskBounds.bottom < currentTaskBounds.bottom
2299 || initialTaskBounds.left > currentTaskBounds.left);
2301 // Size by bottom-right
2302 System.out.println("Growing bottom-right");
2304 currentTaskBounds.bottom += getStepSize(
2305 currentTaskBounds.bottom, stackBounds.bottom, stepSize, !GREATER_THAN_TARGET);
2307 currentTaskBounds.right += getStepSize(
2308 currentTaskBounds.right, stackBounds.right, stepSize, !GREATER_THAN_TARGET);
2310 taskResize(taskId, currentTaskBounds, delay_ms, true);
2311 } while (stackBounds.bottom > currentTaskBounds.bottom
2312 || stackBounds.right > currentTaskBounds.right);
2314 // Back to original size
2315 System.out.println("Shrinking bottom-right");
2317 currentTaskBounds.bottom -= getStepSize(currentTaskBounds.bottom,
2318 initialTaskBounds.bottom, stepSize, GREATER_THAN_TARGET);
2320 currentTaskBounds.right -= getStepSize(currentTaskBounds.right, initialTaskBounds.right,
2321 stepSize, GREATER_THAN_TARGET);
2323 taskResize(taskId, currentTaskBounds, delay_ms, true);
2324 } while (initialTaskBounds.bottom < currentTaskBounds.bottom
2325 || initialTaskBounds.right < currentTaskBounds.right);
2328 private int getStepSize(int current, int target, int inStepSize, boolean greaterThanTarget) {
2330 if (greaterThanTarget && target < current) {
2331 current -= inStepSize;
2332 stepSize = inStepSize;
2333 if (target > current) {
2334 stepSize -= (target - current);
2337 if (!greaterThanTarget && target > current) {
2338 current += inStepSize;
2339 stepSize = inStepSize;
2340 if (target < current) {
2341 stepSize += (current - target);
2347 private List<Configuration> getRecentConfigurations(int days) {
2348 IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService(
2349 Context.USAGE_STATS_SERVICE));
2350 final long now = System.currentTimeMillis();
2351 final long nDaysAgo = now - (days * 24 * 60 * 60 * 1000);
2353 @SuppressWarnings("unchecked")
2354 ParceledListSlice<ConfigurationStats> configStatsSlice = usm.queryConfigurationStats(
2355 UsageStatsManager.INTERVAL_BEST, nDaysAgo, now, "com.android.shell");
2356 if (configStatsSlice == null) {
2357 return Collections.emptyList();
2360 final ArrayMap<Configuration, Integer> recentConfigs = new ArrayMap<>();
2361 final List<ConfigurationStats> configStatsList = configStatsSlice.getList();
2362 final int configStatsListSize = configStatsList.size();
2363 for (int i = 0; i < configStatsListSize; i++) {
2364 final ConfigurationStats stats = configStatsList.get(i);
2365 final int indexOfKey = recentConfigs.indexOfKey(stats.getConfiguration());
2366 if (indexOfKey < 0) {
2367 recentConfigs.put(stats.getConfiguration(), stats.getActivationCount());
2369 recentConfigs.setValueAt(indexOfKey,
2370 recentConfigs.valueAt(indexOfKey) + stats.getActivationCount());
2374 final Comparator<Configuration> comparator = new Comparator<Configuration>() {
2376 public int compare(Configuration a, Configuration b) {
2377 return recentConfigs.get(b).compareTo(recentConfigs.get(a));
2381 ArrayList<Configuration> configs = new ArrayList<>(recentConfigs.size());
2382 configs.addAll(recentConfigs.keySet());
2383 Collections.sort(configs, comparator);
2386 } catch (RemoteException e) {
2387 return Collections.emptyList();
2391 private void runGetConfig() throws Exception {
2393 String option = nextOption();
2394 if (option != null) {
2395 if (!option.equals("--days")) {
2396 throw new IllegalArgumentException("unrecognized option " + option);
2399 days = Integer.parseInt(nextArgRequired());
2401 throw new IllegalArgumentException("--days must be a positive integer");
2406 Configuration config = mAm.getConfiguration();
2407 if (config == null) {
2408 System.err.println("Activity manager has no configuration");
2412 System.out.println("config: " + Configuration.resourceQualifierString(config));
2413 System.out.println("abi: " + TextUtils.join(",", Build.SUPPORTED_ABIS));
2415 final List<Configuration> recentConfigs = getRecentConfigurations(days);
2416 final int recentConfigSize = recentConfigs.size();
2417 if (recentConfigSize > 0) {
2418 System.out.println("recentConfigs:");
2421 for (int i = 0; i < recentConfigSize; i++) {
2422 System.out.println(" config: " + Configuration.resourceQualifierString(
2423 recentConfigs.get(i)));
2426 } catch (RemoteException e) {
2430 private void runSuppressResizeConfigChanges() throws Exception {
2431 boolean suppress = Boolean.valueOf(nextArgRequired());
2434 mAm.suppressResizeConfigChanges(suppress);
2435 } catch (RemoteException e) {
2436 System.err.println("Error suppressing resize config changes: " + e);
2440 private void runSetInactive() throws Exception {
2441 int userId = UserHandle.USER_CURRENT;
2444 while ((opt=nextOption()) != null) {
2445 if (opt.equals("--user")) {
2446 userId = parseUserArg(nextArgRequired());
2448 System.err.println("Error: Unknown option: " + opt);
2452 String packageName = nextArgRequired();
2453 String value = nextArgRequired();
2455 IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService(
2456 Context.USAGE_STATS_SERVICE));
2457 usm.setAppInactive(packageName, Boolean.parseBoolean(value), userId);
2460 private void runGetInactive() throws Exception {
2461 int userId = UserHandle.USER_CURRENT;
2464 while ((opt=nextOption()) != null) {
2465 if (opt.equals("--user")) {
2466 userId = parseUserArg(nextArgRequired());
2468 System.err.println("Error: Unknown option: " + opt);
2472 String packageName = nextArgRequired();
2474 IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService(
2475 Context.USAGE_STATS_SERVICE));
2476 boolean isIdle = usm.isAppInactive(packageName, userId);
2477 System.out.println("Idle=" + isIdle);
2480 private void runSendTrimMemory() throws Exception {
2481 int userId = UserHandle.USER_CURRENT;
2483 while ((opt = nextOption()) != null) {
2484 if (opt.equals("--user")) {
2485 userId = parseUserArg(nextArgRequired());
2486 if (userId == UserHandle.USER_ALL) {
2487 System.err.println("Error: Can't use user 'all'");
2491 System.err.println("Error: Unknown option: " + opt);
2496 String proc = nextArgRequired();
2497 String levelArg = nextArgRequired();
2501 level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
2503 case "RUNNING_MODERATE":
2504 level = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
2507 level = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
2510 level = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
2513 level = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
2515 case "RUNNING_CRITICAL":
2516 level = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
2519 level = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
2522 System.err.println("Error: Unknown level option: " + levelArg);
2525 if (!mAm.setProcessMemoryTrimLevel(proc, userId, level)) {
2526 System.err.println("Error: Failure to set the level - probably Unknown Process: " +
2531 private void runGetCurrentUser() throws Exception {
2532 UserInfo currentUser = Preconditions.checkNotNull(mAm.getCurrentUser(),
2533 "Current user not set");
2534 System.out.println(currentUser.id);
2538 * Open the given file for sending into the system process. This verifies
2539 * with SELinux that the system will have access to the file.
2541 private static ParcelFileDescriptor openForSystemServer(File file, int mode)
2542 throws FileNotFoundException {
2543 final ParcelFileDescriptor fd = ParcelFileDescriptor.open(file, mode);
2544 final String tcon = SELinux.getFileContext(file.getAbsolutePath());
2545 if (!SELinux.checkSELinuxAccess("u:r:system_server:s0", tcon, "file", "read")) {
2546 throw new FileNotFoundException("System server has no access to file context " + tcon);
2551 private Rect getBounds() {
2552 String leftStr = nextArgRequired();
2553 int left = Integer.parseInt(leftStr);
2554 String topStr = nextArgRequired();
2555 int top = Integer.parseInt(topStr);
2556 String rightStr = nextArgRequired();
2557 int right = Integer.parseInt(rightStr);
2558 String bottomStr = nextArgRequired();
2559 int bottom = Integer.parseInt(bottomStr);
2561 System.err.println("Error: bad left arg: " + leftStr);
2565 System.err.println("Error: bad top arg: " + topStr);
2569 System.err.println("Error: bad right arg: " + rightStr);
2573 System.err.println("Error: bad bottom arg: " + bottomStr);
2576 return new Rect(left, top, right, bottom);