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