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