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