Am.java revision 5e03e2ca7d25b899b129baad2dd5eca6bf99d88a
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.ActivityManagerNative;
23import android.app.IActivityController;
24import android.app.IActivityManager;
25import android.app.IInstrumentationWatcher;
26import android.app.Instrumentation;
27import android.content.ComponentName;
28import android.content.Context;
29import android.content.IIntentReceiver;
30import android.content.Intent;
31import android.content.pm.IPackageManager;
32import android.content.pm.ResolveInfo;
33import android.net.Uri;
34import android.os.Bundle;
35import android.os.ParcelFileDescriptor;
36import android.os.RemoteException;
37import android.os.ServiceManager;
38import android.os.SystemProperties;
39import android.os.UserHandle;
40import android.util.AndroidException;
41import android.view.Display;
42import android.view.IWindowManager;
43
44import java.io.BufferedReader;
45import java.io.File;
46import java.io.FileNotFoundException;
47import java.io.IOException;
48import java.io.InputStreamReader;
49import java.io.PrintStream;
50import java.net.URISyntaxException;
51import java.util.HashSet;
52import java.util.List;
53
54public class Am {
55
56    private IActivityManager mAm;
57    private String[] mArgs;
58    private int mNextArg;
59    private String mCurArgData;
60
61    private int mStartFlags = 0;
62    private boolean mWaitOption = false;
63    private boolean mStopOption = false;
64
65    private int mRepeat = 0;
66    private int mUserId = 0;
67
68    private String mProfileFile;
69
70    // These are magic strings understood by the Eclipse plugin.
71    private static final String FATAL_ERROR_CODE = "Error type 1";
72    private static final String NO_SYSTEM_ERROR_CODE = "Error type 2";
73    private static final String NO_CLASS_ERROR_CODE = "Error type 3";
74
75    /**
76     * Command-line entry point.
77     *
78     * @param args The command-line arguments
79     */
80    public static void main(String[] args) {
81        try {
82            (new Am()).run(args);
83        } catch (IllegalArgumentException e) {
84            showUsage();
85            System.err.println("Error: " + e.getMessage());
86        } catch (Exception e) {
87            e.printStackTrace(System.err);
88            System.exit(1);
89        }
90    }
91
92    private void run(String[] args) throws Exception {
93        if (args.length < 1) {
94            showUsage();
95            return;
96        }
97
98        mAm = ActivityManagerNative.getDefault();
99        if (mAm == null) {
100            System.err.println(NO_SYSTEM_ERROR_CODE);
101            throw new AndroidException("Can't connect to activity manager; is the system running?");
102        }
103
104        mArgs = args;
105        String op = args[0];
106        mNextArg = 1;
107
108        if (op.equals("start")) {
109            runStart();
110        } else if (op.equals("startservice")) {
111            runStartService();
112        } else if (op.equals("force-stop")) {
113            runForceStop();
114        } else if (op.equals("kill")) {
115            runKill();
116        } else if (op.equals("kill-all")) {
117            runKillAll();
118        } else if (op.equals("instrument")) {
119            runInstrument();
120        } else if (op.equals("broadcast")) {
121            sendBroadcast();
122        } else if (op.equals("profile")) {
123            runProfile();
124        } else if (op.equals("dumpheap")) {
125            runDumpHeap();
126        } else if (op.equals("set-debug-app")) {
127            runSetDebugApp();
128        } else if (op.equals("clear-debug-app")) {
129            runClearDebugApp();
130        } else if (op.equals("monitor")) {
131            runMonitor();
132        } else if (op.equals("screen-compat")) {
133            runScreenCompat();
134        } else if (op.equals("display-size")) {
135            runDisplaySize();
136        } else if (op.equals("display-density")) {
137            runDisplayDensity();
138        } else if (op.equals("to-uri")) {
139            runToUri(false);
140        } else if (op.equals("to-intent-uri")) {
141            runToUri(true);
142        } else if (op.equals("switch-user")) {
143            runSwitchUser();
144        } else if (op.equals("stop-user")) {
145            runStopUser();
146        } else {
147            throw new IllegalArgumentException("Unknown command: " + op);
148        }
149    }
150
151    int parseUserArg(String arg) {
152        int userId;
153        if ("all".equals(arg)) {
154            userId = UserHandle.USER_ALL;
155        } else if ("current".equals(arg) || "cur".equals(arg)) {
156            userId = UserHandle.USER_CURRENT;
157        } else {
158            userId = Integer.parseInt(arg);
159        }
160        return userId;
161    }
162
163    private Intent makeIntent() throws URISyntaxException {
164        Intent intent = new Intent();
165        Intent baseIntent = intent;
166        boolean hasIntentInfo = false;
167
168        mStartFlags = 0;
169        mWaitOption = false;
170        mStopOption = false;
171        mRepeat = 0;
172        mProfileFile = null;
173        mUserId = 0;
174        Uri data = null;
175        String type = null;
176
177        String opt;
178        while ((opt=nextOption()) != null) {
179            if (opt.equals("-a")) {
180                intent.setAction(nextArgRequired());
181                if (intent == baseIntent) {
182                    hasIntentInfo = true;
183                }
184            } else if (opt.equals("-d")) {
185                data = Uri.parse(nextArgRequired());
186                if (intent == baseIntent) {
187                    hasIntentInfo = true;
188                }
189            } else if (opt.equals("-t")) {
190                type = nextArgRequired();
191                if (intent == baseIntent) {
192                    hasIntentInfo = true;
193                }
194            } else if (opt.equals("-c")) {
195                intent.addCategory(nextArgRequired());
196                if (intent == baseIntent) {
197                    hasIntentInfo = true;
198                }
199            } else if (opt.equals("-e") || opt.equals("--es")) {
200                String key = nextArgRequired();
201                String value = nextArgRequired();
202                intent.putExtra(key, value);
203            } else if (opt.equals("--esn")) {
204                String key = nextArgRequired();
205                intent.putExtra(key, (String) null);
206            } else if (opt.equals("--ei")) {
207                String key = nextArgRequired();
208                String value = nextArgRequired();
209                intent.putExtra(key, Integer.valueOf(value));
210            } else if (opt.equals("--eu")) {
211                String key = nextArgRequired();
212                String value = nextArgRequired();
213                intent.putExtra(key, Uri.parse(value));
214            } else if (opt.equals("--ecn")) {
215                String key = nextArgRequired();
216                String value = nextArgRequired();
217                ComponentName cn = ComponentName.unflattenFromString(value);
218                if (cn == null) throw new IllegalArgumentException("Bad component name: " + value);
219                intent.putExtra(key, cn);
220            } else if (opt.equals("--eia")) {
221                String key = nextArgRequired();
222                String value = nextArgRequired();
223                String[] strings = value.split(",");
224                int[] list = new int[strings.length];
225                for (int i = 0; i < strings.length; i++) {
226                    list[i] = Integer.valueOf(strings[i]);
227                }
228                intent.putExtra(key, list);
229            } else if (opt.equals("--el")) {
230                String key = nextArgRequired();
231                String value = nextArgRequired();
232                intent.putExtra(key, Long.valueOf(value));
233            } else if (opt.equals("--ela")) {
234                String key = nextArgRequired();
235                String value = nextArgRequired();
236                String[] strings = value.split(",");
237                long[] list = new long[strings.length];
238                for (int i = 0; i < strings.length; i++) {
239                    list[i] = Long.valueOf(strings[i]);
240                }
241                intent.putExtra(key, list);
242                hasIntentInfo = true;
243            } else if (opt.equals("--ef")) {
244                String key = nextArgRequired();
245                String value = nextArgRequired();
246                intent.putExtra(key, Float.valueOf(value));
247                hasIntentInfo = true;
248            } else if (opt.equals("--efa")) {
249                String key = nextArgRequired();
250                String value = nextArgRequired();
251                String[] strings = value.split(",");
252                float[] list = new float[strings.length];
253                for (int i = 0; i < strings.length; i++) {
254                    list[i] = Float.valueOf(strings[i]);
255                }
256                intent.putExtra(key, list);
257                hasIntentInfo = true;
258            } else if (opt.equals("--ez")) {
259                String key = nextArgRequired();
260                String value = nextArgRequired();
261                intent.putExtra(key, Boolean.valueOf(value));
262            } else if (opt.equals("-n")) {
263                String str = nextArgRequired();
264                ComponentName cn = ComponentName.unflattenFromString(str);
265                if (cn == null) throw new IllegalArgumentException("Bad component name: " + str);
266                intent.setComponent(cn);
267                if (intent == baseIntent) {
268                    hasIntentInfo = true;
269                }
270            } else if (opt.equals("-f")) {
271                String str = nextArgRequired();
272                intent.setFlags(Integer.decode(str).intValue());
273            } else if (opt.equals("--grant-read-uri-permission")) {
274                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
275            } else if (opt.equals("--grant-write-uri-permission")) {
276                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
277            } else if (opt.equals("--exclude-stopped-packages")) {
278                intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
279            } else if (opt.equals("--include-stopped-packages")) {
280                intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
281            } else if (opt.equals("--debug-log-resolution")) {
282                intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
283            } else if (opt.equals("--activity-brought-to-front")) {
284                intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
285            } else if (opt.equals("--activity-clear-top")) {
286                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
287            } else if (opt.equals("--activity-clear-when-task-reset")) {
288                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
289            } else if (opt.equals("--activity-exclude-from-recents")) {
290                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
291            } else if (opt.equals("--activity-launched-from-history")) {
292                intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
293            } else if (opt.equals("--activity-multiple-task")) {
294                intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
295            } else if (opt.equals("--activity-no-animation")) {
296                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
297            } else if (opt.equals("--activity-no-history")) {
298                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
299            } else if (opt.equals("--activity-no-user-action")) {
300                intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
301            } else if (opt.equals("--activity-previous-is-top")) {
302                intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
303            } else if (opt.equals("--activity-reorder-to-front")) {
304                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
305            } else if (opt.equals("--activity-reset-task-if-needed")) {
306                intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
307            } else if (opt.equals("--activity-single-top")) {
308                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
309            } else if (opt.equals("--activity-clear-task")) {
310                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
311            } else if (opt.equals("--activity-task-on-home")) {
312                intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
313            } else if (opt.equals("--receiver-registered-only")) {
314                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
315            } else if (opt.equals("--receiver-replace-pending")) {
316                intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
317            } else if (opt.equals("--selector")) {
318                intent.setDataAndType(data, type);
319                intent = new Intent();
320            } else if (opt.equals("-D")) {
321                mStartFlags |= ActivityManager.START_FLAG_DEBUG;
322            } else if (opt.equals("-W")) {
323                mWaitOption = true;
324            } else if (opt.equals("-P")) {
325                mProfileFile = nextArgRequired();
326                mStartFlags |= ActivityManager.START_FLAG_AUTO_STOP_PROFILER;
327            } else if (opt.equals("--start-profiler")) {
328                mProfileFile = nextArgRequired();
329                mStartFlags &= ~ActivityManager.START_FLAG_AUTO_STOP_PROFILER;
330            } else if (opt.equals("-R")) {
331                mRepeat = Integer.parseInt(nextArgRequired());
332            } else if (opt.equals("-S")) {
333                mStopOption = true;
334            } else if (opt.equals("--opengl-trace")) {
335                mStartFlags |= ActivityManager.START_FLAG_OPENGL_TRACES;
336            } else if (opt.equals("--user")) {
337                mUserId = parseUserArg(nextArgRequired());
338            } else {
339                System.err.println("Error: Unknown option: " + opt);
340                return null;
341            }
342        }
343        intent.setDataAndType(data, type);
344
345        final boolean hasSelector = intent != baseIntent;
346        if (hasSelector) {
347            // A selector was specified; fix up.
348            baseIntent.setSelector(intent);
349            intent = baseIntent;
350        }
351
352        String arg = nextArg();
353        baseIntent = null;
354        if (arg == null) {
355            if (hasSelector) {
356                // If a selector has been specified, and no arguments
357                // have been supplied for the main Intent, then we can
358                // assume it is ACTION_MAIN CATEGORY_LAUNCHER; we don't
359                // need to have a component name specified yet, the
360                // selector will take care of that.
361                baseIntent = new Intent(Intent.ACTION_MAIN);
362                baseIntent.addCategory(Intent.CATEGORY_LAUNCHER);
363            }
364        } else if (arg.indexOf(':') >= 0) {
365            // The argument is a URI.  Fully parse it, and use that result
366            // to fill in any data not specified so far.
367            baseIntent = Intent.parseUri(arg, Intent.URI_INTENT_SCHEME);
368        } else if (arg.indexOf('/') >= 0) {
369            // The argument is a component name.  Build an Intent to launch
370            // it.
371            baseIntent = new Intent(Intent.ACTION_MAIN);
372            baseIntent.addCategory(Intent.CATEGORY_LAUNCHER);
373            baseIntent.setComponent(ComponentName.unflattenFromString(arg));
374        } else {
375            // Assume the argument is a package name.
376            baseIntent = new Intent(Intent.ACTION_MAIN);
377            baseIntent.addCategory(Intent.CATEGORY_LAUNCHER);
378            baseIntent.setPackage(arg);
379        }
380        if (baseIntent != null) {
381            Bundle extras = intent.getExtras();
382            intent.replaceExtras((Bundle)null);
383            Bundle uriExtras = baseIntent.getExtras();
384            baseIntent.replaceExtras((Bundle)null);
385            if (intent.getAction() != null && baseIntent.getCategories() != null) {
386                HashSet<String> cats = new HashSet<String>(baseIntent.getCategories());
387                for (String c : cats) {
388                    baseIntent.removeCategory(c);
389                }
390            }
391            intent.fillIn(baseIntent, Intent.FILL_IN_COMPONENT | Intent.FILL_IN_SELECTOR);
392            if (extras == null) {
393                extras = uriExtras;
394            } else if (uriExtras != null) {
395                uriExtras.putAll(extras);
396                extras = uriExtras;
397            }
398            intent.replaceExtras(extras);
399            hasIntentInfo = true;
400        }
401
402        if (!hasIntentInfo) throw new IllegalArgumentException("No intent supplied");
403        return intent;
404    }
405
406    private void runStartService() throws Exception {
407        Intent intent = makeIntent();
408        if (mUserId == UserHandle.USER_ALL) {
409            System.err.println("Error: Can't start activity with user 'all'");
410            return;
411        }
412        System.out.println("Starting service: " + intent);
413        ComponentName cn = mAm.startService(null, intent, intent.getType(), mUserId);
414        if (cn == null) {
415            System.err.println("Error: Not found; no service started.");
416        }
417    }
418
419    private void runStart() throws Exception {
420        Intent intent = makeIntent();
421
422        if (mUserId == UserHandle.USER_ALL) {
423            System.err.println("Error: Can't start service with user 'all'");
424            return;
425        }
426
427        String mimeType = intent.getType();
428        if (mimeType == null && intent.getData() != null
429                && "content".equals(intent.getData().getScheme())) {
430            mimeType = mAm.getProviderMimeType(intent.getData(), mUserId);
431        }
432
433        do {
434            if (mStopOption) {
435                String packageName;
436                if (intent.getComponent() != null) {
437                    packageName = intent.getComponent().getPackageName();
438                } else {
439                    IPackageManager pm = IPackageManager.Stub.asInterface(
440                            ServiceManager.getService("package"));
441                    if (pm == null) {
442                        System.err.println("Error: Package manager not running; aborting");
443                        return;
444                    }
445                    List<ResolveInfo> activities = pm.queryIntentActivities(intent, mimeType, 0,
446                            mUserId);
447                    if (activities == null || activities.size() <= 0) {
448                        System.err.println("Error: Intent does not match any activities: "
449                                + intent);
450                        return;
451                    } else if (activities.size() > 1) {
452                        System.err.println("Error: Intent matches multiple activities; can't stop: "
453                                + intent);
454                        return;
455                    }
456                    packageName = activities.get(0).activityInfo.packageName;
457                }
458                System.out.println("Stopping: " + packageName);
459                mAm.forceStopPackage(packageName);
460                Thread.sleep(250);
461            }
462
463            System.out.println("Starting: " + intent);
464            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
465
466            ParcelFileDescriptor fd = null;
467
468            if (mProfileFile != null) {
469                try {
470                    fd = ParcelFileDescriptor.open(
471                            new File(mProfileFile),
472                            ParcelFileDescriptor.MODE_CREATE |
473                            ParcelFileDescriptor.MODE_TRUNCATE |
474                            ParcelFileDescriptor.MODE_READ_WRITE);
475                } catch (FileNotFoundException e) {
476                    System.err.println("Error: Unable to open file: " + mProfileFile);
477                    return;
478                }
479            }
480
481            IActivityManager.WaitResult result = null;
482            int res;
483            if (mWaitOption) {
484                result = mAm.startActivityAndWait(null, intent, mimeType,
485                            null, null, 0, mStartFlags, mProfileFile, fd, null, mUserId);
486                res = result.result;
487            } else {
488                res = mAm.startActivityAsUser(null, intent, mimeType,
489                        null, null, 0, mStartFlags, mProfileFile, fd, null, mUserId);
490            }
491            PrintStream out = mWaitOption ? System.out : System.err;
492            boolean launched = false;
493            switch (res) {
494                case ActivityManager.START_SUCCESS:
495                    launched = true;
496                    break;
497                case ActivityManager.START_SWITCHES_CANCELED:
498                    launched = true;
499                    out.println(
500                            "Warning: Activity not started because the "
501                            + " current activity is being kept for the user.");
502                    break;
503                case ActivityManager.START_DELIVERED_TO_TOP:
504                    launched = true;
505                    out.println(
506                            "Warning: Activity not started, intent has "
507                            + "been delivered to currently running "
508                            + "top-most instance.");
509                    break;
510                case ActivityManager.START_RETURN_INTENT_TO_CALLER:
511                    launched = true;
512                    out.println(
513                            "Warning: Activity not started because intent "
514                            + "should be handled by the caller");
515                    break;
516                case ActivityManager.START_TASK_TO_FRONT:
517                    launched = true;
518                    out.println(
519                            "Warning: Activity not started, its current "
520                            + "task has been brought to the front");
521                    break;
522                case ActivityManager.START_INTENT_NOT_RESOLVED:
523                    out.println(
524                            "Error: Activity not started, unable to "
525                            + "resolve " + intent.toString());
526                    break;
527                case ActivityManager.START_CLASS_NOT_FOUND:
528                    out.println(NO_CLASS_ERROR_CODE);
529                    out.println("Error: Activity class " +
530                            intent.getComponent().toShortString()
531                            + " does not exist.");
532                    break;
533                case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
534                    out.println(
535                            "Error: Activity not started, you requested to "
536                            + "both forward and receive its result");
537                    break;
538                case ActivityManager.START_PERMISSION_DENIED:
539                    out.println(
540                            "Error: Activity not started, you do not "
541                            + "have permission to access it.");
542                    break;
543                default:
544                    out.println(
545                            "Error: Activity not started, unknown error code " + res);
546                    break;
547            }
548            if (mWaitOption && launched) {
549                if (result == null) {
550                    result = new IActivityManager.WaitResult();
551                    result.who = intent.getComponent();
552                }
553                System.out.println("Status: " + (result.timeout ? "timeout" : "ok"));
554                if (result.who != null) {
555                    System.out.println("Activity: " + result.who.flattenToShortString());
556                }
557                if (result.thisTime >= 0) {
558                    System.out.println("ThisTime: " + result.thisTime);
559                }
560                if (result.totalTime >= 0) {
561                    System.out.println("TotalTime: " + result.totalTime);
562                }
563                System.out.println("Complete");
564            }
565            mRepeat--;
566            if (mRepeat > 1) {
567                mAm.unhandledBack();
568            }
569        } while (mRepeat > 1);
570    }
571
572    private void runForceStop() throws Exception {
573        mAm.forceStopPackage(nextArgRequired());
574    }
575
576    private void runKill() throws Exception {
577        mAm.killBackgroundProcesses(nextArgRequired());
578    }
579
580    private void runKillAll() throws Exception {
581        mAm.killAllBackgroundProcesses();
582    }
583
584    private void sendBroadcast() throws Exception {
585        Intent intent = makeIntent();
586        IntentReceiver receiver = new IntentReceiver();
587        System.out.println("Broadcasting: " + intent);
588        mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, null, true, false,
589                mUserId);
590        receiver.waitForFinish();
591    }
592
593    private void runInstrument() throws Exception {
594        String profileFile = null;
595        boolean wait = false;
596        boolean rawMode = false;
597        boolean no_window_animation = false;
598        int userId = 0;
599        Bundle args = new Bundle();
600        String argKey = null, argValue = null;
601        IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
602
603        String opt;
604        while ((opt=nextOption()) != null) {
605            if (opt.equals("-p")) {
606                profileFile = nextArgRequired();
607            } else if (opt.equals("-w")) {
608                wait = true;
609            } else if (opt.equals("-r")) {
610                rawMode = true;
611            } else if (opt.equals("-e")) {
612                argKey = nextArgRequired();
613                argValue = nextArgRequired();
614                args.putString(argKey, argValue);
615            } else if (opt.equals("--no_window_animation")
616                    || opt.equals("--no-window-animation")) {
617                no_window_animation = true;
618            } else if (opt.equals("--user")) {
619                userId = parseUserArg(nextArgRequired());
620            } else {
621                System.err.println("Error: Unknown option: " + opt);
622                return;
623            }
624        }
625
626        if (userId == UserHandle.USER_ALL) {
627            System.err.println("Error: Can't start instrumentation with user 'all'");
628            return;
629        }
630
631        String cnArg = nextArgRequired();
632        ComponentName cn = ComponentName.unflattenFromString(cnArg);
633        if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg);
634
635        InstrumentationWatcher watcher = null;
636        if (wait) {
637            watcher = new InstrumentationWatcher();
638            watcher.setRawOutput(rawMode);
639        }
640        float[] oldAnims = null;
641        if (no_window_animation) {
642            oldAnims = wm.getAnimationScales();
643            wm.setAnimationScale(0, 0.0f);
644            wm.setAnimationScale(1, 0.0f);
645        }
646
647        if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher, userId)) {
648            throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString());
649        }
650
651        if (watcher != null) {
652            if (!watcher.waitForFinish()) {
653                System.out.println("INSTRUMENTATION_ABORTED: System has crashed.");
654            }
655        }
656
657        if (oldAnims != null) {
658            wm.setAnimationScales(oldAnims);
659        }
660    }
661
662    static void removeWallOption() {
663        String props = SystemProperties.get("dalvik.vm.extra-opts");
664        if (props != null && props.contains("-Xprofile:wallclock")) {
665            props = props.replace("-Xprofile:wallclock", "");
666            props = props.trim();
667            SystemProperties.set("dalvik.vm.extra-opts", props);
668        }
669    }
670
671    private void runProfile() throws Exception {
672        String profileFile = null;
673        boolean start = false;
674        boolean wall = false;
675        int profileType = 0;
676
677        String process = null;
678
679        String cmd = nextArgRequired();
680
681        if ("start".equals(cmd)) {
682            start = true;
683            wall = "--wall".equals(nextOption());
684            process = nextArgRequired();
685        } else if ("stop".equals(cmd)) {
686            process = nextArg();
687        } else {
688            // Compatibility with old syntax: process is specified first.
689            process = cmd;
690            cmd = nextArgRequired();
691            if ("start".equals(cmd)) {
692                start = true;
693            } else if (!"stop".equals(cmd)) {
694                throw new IllegalArgumentException("Profile command " + process + " not valid");
695            }
696        }
697
698        ParcelFileDescriptor fd = null;
699
700        if (start) {
701            profileFile = nextArgRequired();
702            try {
703                fd = ParcelFileDescriptor.open(
704                        new File(profileFile),
705                        ParcelFileDescriptor.MODE_CREATE |
706                        ParcelFileDescriptor.MODE_TRUNCATE |
707                        ParcelFileDescriptor.MODE_READ_WRITE);
708            } catch (FileNotFoundException e) {
709                System.err.println("Error: Unable to open file: " + profileFile);
710                return;
711            }
712        }
713
714        try {
715            if (wall) {
716                // XXX doesn't work -- this needs to be set before booting.
717                String props = SystemProperties.get("dalvik.vm.extra-opts");
718                if (props == null || !props.contains("-Xprofile:wallclock")) {
719                    props = props + " -Xprofile:wallclock";
720                    //SystemProperties.set("dalvik.vm.extra-opts", props);
721                }
722            } else if (start) {
723                //removeWallOption();
724            }
725            if (!mAm.profileControl(process, start, profileFile, fd, profileType)) {
726                wall = false;
727                throw new AndroidException("PROFILE FAILED on process " + process);
728            }
729        } finally {
730            if (!wall) {
731                //removeWallOption();
732            }
733        }
734    }
735
736    private void runDumpHeap() throws Exception {
737        boolean managed = !"-n".equals(nextOption());
738        String process = nextArgRequired();
739        String heapFile = nextArgRequired();
740        ParcelFileDescriptor fd = null;
741
742        try {
743            fd = ParcelFileDescriptor.open(
744                    new File(heapFile),
745                    ParcelFileDescriptor.MODE_CREATE |
746                    ParcelFileDescriptor.MODE_TRUNCATE |
747                    ParcelFileDescriptor.MODE_READ_WRITE);
748        } catch (FileNotFoundException e) {
749            System.err.println("Error: Unable to open file: " + heapFile);
750            return;
751        }
752
753        if (!mAm.dumpHeap(process, managed, heapFile, fd)) {
754            throw new AndroidException("HEAP DUMP FAILED on process " + process);
755        }
756    }
757
758    private void runSetDebugApp() throws Exception {
759        boolean wait = false;
760        boolean persistent = false;
761
762        String opt;
763        while ((opt=nextOption()) != null) {
764            if (opt.equals("-w")) {
765                wait = true;
766            } else if (opt.equals("--persistent")) {
767                persistent = true;
768            } else {
769                System.err.println("Error: Unknown option: " + opt);
770                return;
771            }
772        }
773
774        String pkg = nextArgRequired();
775        mAm.setDebugApp(pkg, wait, persistent);
776    }
777
778    private void runClearDebugApp() throws Exception {
779        mAm.setDebugApp(null, false, true);
780    }
781
782    private void runSwitchUser() throws Exception {
783        String user = nextArgRequired();
784        mAm.switchUser(Integer.parseInt(user));
785    }
786
787    private void runStopUser() throws Exception {
788        String user = nextArgRequired();
789        int res = mAm.stopUser(Integer.parseInt(user), null);
790        if (res != ActivityManager.USER_OP_SUCCESS) {
791            String txt = "";
792            switch (res) {
793                case ActivityManager.USER_OP_IS_CURRENT:
794                    txt = " (Can't stop current user)";
795                    break;
796                case ActivityManager.USER_OP_UNKNOWN_USER:
797                    txt = " (Unknown user " + user + ")";
798                    break;
799            }
800            System.err.println("Switch failed: " + res + txt);
801        }
802    }
803
804    class MyActivityController extends IActivityController.Stub {
805        final String mGdbPort;
806
807        static final int STATE_NORMAL = 0;
808        static final int STATE_CRASHED = 1;
809        static final int STATE_EARLY_ANR = 2;
810        static final int STATE_ANR = 3;
811
812        int mState;
813
814        static final int RESULT_DEFAULT = 0;
815
816        static final int RESULT_CRASH_DIALOG = 0;
817        static final int RESULT_CRASH_KILL = 1;
818
819        static final int RESULT_EARLY_ANR_CONTINUE = 0;
820        static final int RESULT_EARLY_ANR_KILL = 1;
821
822        static final int RESULT_ANR_DIALOG = 0;
823        static final int RESULT_ANR_KILL = 1;
824        static final int RESULT_ANR_WAIT = 1;
825
826        int mResult;
827
828        Process mGdbProcess;
829        Thread mGdbThread;
830        boolean mGotGdbPrint;
831
832        MyActivityController(String gdbPort) {
833            mGdbPort = gdbPort;
834        }
835
836        @Override
837        public boolean activityResuming(String pkg) throws RemoteException {
838            synchronized (this) {
839                System.out.println("** Activity resuming: " + pkg);
840            }
841            return true;
842        }
843
844        @Override
845        public boolean activityStarting(Intent intent, String pkg) throws RemoteException {
846            synchronized (this) {
847                System.out.println("** Activity starting: " + pkg);
848            }
849            return true;
850        }
851
852        @Override
853        public boolean appCrashed(String processName, int pid, String shortMsg, String longMsg,
854                long timeMillis, String stackTrace) throws RemoteException {
855            synchronized (this) {
856                System.out.println("** ERROR: PROCESS CRASHED");
857                System.out.println("processName: " + processName);
858                System.out.println("processPid: " + pid);
859                System.out.println("shortMsg: " + shortMsg);
860                System.out.println("longMsg: " + longMsg);
861                System.out.println("timeMillis: " + timeMillis);
862                System.out.println("stack:");
863                System.out.print(stackTrace);
864                System.out.println("#");
865                int result = waitControllerLocked(pid, STATE_CRASHED);
866                return result == RESULT_CRASH_KILL ? false : true;
867            }
868        }
869
870        @Override
871        public int appEarlyNotResponding(String processName, int pid, String annotation)
872                throws RemoteException {
873            synchronized (this) {
874                System.out.println("** ERROR: EARLY PROCESS NOT RESPONDING");
875                System.out.println("processName: " + processName);
876                System.out.println("processPid: " + pid);
877                System.out.println("annotation: " + annotation);
878                int result = waitControllerLocked(pid, STATE_EARLY_ANR);
879                if (result == RESULT_EARLY_ANR_KILL) return -1;
880                return 0;
881            }
882        }
883
884        @Override
885        public int appNotResponding(String processName, int pid, String processStats)
886                throws RemoteException {
887            synchronized (this) {
888                System.out.println("** ERROR: PROCESS NOT RESPONDING");
889                System.out.println("processName: " + processName);
890                System.out.println("processPid: " + pid);
891                System.out.println("processStats:");
892                System.out.print(processStats);
893                System.out.println("#");
894                int result = waitControllerLocked(pid, STATE_ANR);
895                if (result == RESULT_ANR_KILL) return -1;
896                if (result == RESULT_ANR_WAIT) return 1;
897                return 0;
898            }
899        }
900
901        void killGdbLocked() {
902            mGotGdbPrint = false;
903            if (mGdbProcess != null) {
904                System.out.println("Stopping gdbserver");
905                mGdbProcess.destroy();
906                mGdbProcess = null;
907            }
908            if (mGdbThread != null) {
909                mGdbThread.interrupt();
910                mGdbThread = null;
911            }
912        }
913
914        int waitControllerLocked(int pid, int state) {
915            if (mGdbPort != null) {
916                killGdbLocked();
917
918                try {
919                    System.out.println("Starting gdbserver on port " + mGdbPort);
920                    System.out.println("Do the following:");
921                    System.out.println("  adb forward tcp:" + mGdbPort + " tcp:" + mGdbPort);
922                    System.out.println("  gdbclient app_process :" + mGdbPort);
923
924                    mGdbProcess = Runtime.getRuntime().exec(new String[] {
925                            "gdbserver", ":" + mGdbPort, "--attach", Integer.toString(pid)
926                    });
927                    final InputStreamReader converter = new InputStreamReader(
928                            mGdbProcess.getInputStream());
929                    mGdbThread = new Thread() {
930                        @Override
931                        public void run() {
932                            BufferedReader in = new BufferedReader(converter);
933                            String line;
934                            int count = 0;
935                            while (true) {
936                                synchronized (MyActivityController.this) {
937                                    if (mGdbThread == null) {
938                                        return;
939                                    }
940                                    if (count == 2) {
941                                        mGotGdbPrint = true;
942                                        MyActivityController.this.notifyAll();
943                                    }
944                                }
945                                try {
946                                    line = in.readLine();
947                                    if (line == null) {
948                                        return;
949                                    }
950                                    System.out.println("GDB: " + line);
951                                    count++;
952                                } catch (IOException e) {
953                                    return;
954                                }
955                            }
956                        }
957                    };
958                    mGdbThread.start();
959
960                    // Stupid waiting for .5s.  Doesn't matter if we end early.
961                    try {
962                        this.wait(500);
963                    } catch (InterruptedException e) {
964                    }
965
966                } catch (IOException e) {
967                    System.err.println("Failure starting gdbserver: " + e);
968                    killGdbLocked();
969                }
970            }
971            mState = state;
972            System.out.println("");
973            printMessageForState();
974
975            while (mState != STATE_NORMAL) {
976                try {
977                    wait();
978                } catch (InterruptedException e) {
979                }
980            }
981
982            killGdbLocked();
983
984            return mResult;
985        }
986
987        void resumeController(int result) {
988            synchronized (this) {
989                mState = STATE_NORMAL;
990                mResult = result;
991                notifyAll();
992            }
993        }
994
995        void printMessageForState() {
996            switch (mState) {
997                case STATE_NORMAL:
998                    System.out.println("Monitoring activity manager...  available commands:");
999                    break;
1000                case STATE_CRASHED:
1001                    System.out.println("Waiting after crash...  available commands:");
1002                    System.out.println("(c)ontinue: show crash dialog");
1003                    System.out.println("(k)ill: immediately kill app");
1004                    break;
1005                case STATE_EARLY_ANR:
1006                    System.out.println("Waiting after early ANR...  available commands:");
1007                    System.out.println("(c)ontinue: standard ANR processing");
1008                    System.out.println("(k)ill: immediately kill app");
1009                    break;
1010                case STATE_ANR:
1011                    System.out.println("Waiting after ANR...  available commands:");
1012                    System.out.println("(c)ontinue: show ANR dialog");
1013                    System.out.println("(k)ill: immediately kill app");
1014                    System.out.println("(w)ait: wait some more");
1015                    break;
1016            }
1017            System.out.println("(q)uit: finish monitoring");
1018        }
1019
1020        void run() throws RemoteException {
1021            try {
1022                printMessageForState();
1023
1024                mAm.setActivityController(this);
1025                mState = STATE_NORMAL;
1026
1027                InputStreamReader converter = new InputStreamReader(System.in);
1028                BufferedReader in = new BufferedReader(converter);
1029                String line;
1030
1031                while ((line = in.readLine()) != null) {
1032                    boolean addNewline = true;
1033                    if (line.length() <= 0) {
1034                        addNewline = false;
1035                    } else if ("q".equals(line) || "quit".equals(line)) {
1036                        resumeController(RESULT_DEFAULT);
1037                        break;
1038                    } else if (mState == STATE_CRASHED) {
1039                        if ("c".equals(line) || "continue".equals(line)) {
1040                            resumeController(RESULT_CRASH_DIALOG);
1041                        } else if ("k".equals(line) || "kill".equals(line)) {
1042                            resumeController(RESULT_CRASH_KILL);
1043                        } else {
1044                            System.out.println("Invalid command: " + line);
1045                        }
1046                    } else if (mState == STATE_ANR) {
1047                        if ("c".equals(line) || "continue".equals(line)) {
1048                            resumeController(RESULT_ANR_DIALOG);
1049                        } else if ("k".equals(line) || "kill".equals(line)) {
1050                            resumeController(RESULT_ANR_KILL);
1051                        } else if ("w".equals(line) || "wait".equals(line)) {
1052                            resumeController(RESULT_ANR_WAIT);
1053                        } else {
1054                            System.out.println("Invalid command: " + line);
1055                        }
1056                    } else if (mState == STATE_EARLY_ANR) {
1057                        if ("c".equals(line) || "continue".equals(line)) {
1058                            resumeController(RESULT_EARLY_ANR_CONTINUE);
1059                        } else if ("k".equals(line) || "kill".equals(line)) {
1060                            resumeController(RESULT_EARLY_ANR_KILL);
1061                        } else {
1062                            System.out.println("Invalid command: " + line);
1063                        }
1064                    } else {
1065                        System.out.println("Invalid command: " + line);
1066                    }
1067
1068                    synchronized (this) {
1069                        if (addNewline) {
1070                            System.out.println("");
1071                        }
1072                        printMessageForState();
1073                    }
1074                }
1075
1076            } catch (IOException e) {
1077                e.printStackTrace();
1078            } finally {
1079                mAm.setActivityController(null);
1080            }
1081        }
1082    }
1083
1084    private void runMonitor() throws Exception {
1085        String opt;
1086        String gdbPort = null;
1087        while ((opt=nextOption()) != null) {
1088            if (opt.equals("--gdb")) {
1089                gdbPort = nextArgRequired();
1090            } else {
1091                System.err.println("Error: Unknown option: " + opt);
1092                return;
1093            }
1094        }
1095
1096        MyActivityController controller = new MyActivityController(gdbPort);
1097        controller.run();
1098    }
1099
1100    private void runScreenCompat() throws Exception {
1101        String mode = nextArgRequired();
1102        boolean enabled;
1103        if ("on".equals(mode)) {
1104            enabled = true;
1105        } else if ("off".equals(mode)) {
1106            enabled = false;
1107        } else {
1108            System.err.println("Error: enabled mode must be 'on' or 'off' at " + mode);
1109            return;
1110        }
1111
1112        String packageName = nextArgRequired();
1113        do {
1114            try {
1115                mAm.setPackageScreenCompatMode(packageName, enabled
1116                        ? ActivityManager.COMPAT_MODE_ENABLED
1117                        : ActivityManager.COMPAT_MODE_DISABLED);
1118            } catch (RemoteException e) {
1119            }
1120            packageName = nextArg();
1121        } while (packageName != null);
1122    }
1123
1124    private void runDisplaySize() throws Exception {
1125        String size = nextArgRequired();
1126        int m, n;
1127        if ("reset".equals(size)) {
1128            m = n = -1;
1129        } else {
1130            int div = size.indexOf('x');
1131            if (div <= 0 || div >= (size.length()-1)) {
1132                System.err.println("Error: bad size " + size);
1133                return;
1134            }
1135            String mstr = size.substring(0, div);
1136            String nstr = size.substring(div+1);
1137            try {
1138                m = Integer.parseInt(mstr);
1139                n = Integer.parseInt(nstr);
1140            } catch (NumberFormatException e) {
1141                System.err.println("Error: bad number " + e);
1142                return;
1143            }
1144        }
1145
1146        if (m < n) {
1147            int tmp = m;
1148            m = n;
1149            n = tmp;
1150        }
1151
1152        IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.checkService(
1153                Context.WINDOW_SERVICE));
1154        if (wm == null) {
1155            System.err.println(NO_SYSTEM_ERROR_CODE);
1156            throw new AndroidException("Can't connect to window manager; is the system running?");
1157        }
1158
1159        try {
1160            if (m >= 0 && n >= 0) {
1161                // TODO(multidisplay): For now Configuration only applies to main screen.
1162                wm.setForcedDisplaySize(Display.DEFAULT_DISPLAY, m, n);
1163            } else {
1164                wm.clearForcedDisplaySize(Display.DEFAULT_DISPLAY);
1165            }
1166        } catch (RemoteException e) {
1167        }
1168    }
1169
1170    private void runDisplayDensity() throws Exception {
1171        String densityStr = nextArgRequired();
1172        int density;
1173        if ("reset".equals(densityStr)) {
1174            density = -1;
1175        } else {
1176            try {
1177                density = Integer.parseInt(densityStr);
1178            } catch (NumberFormatException e) {
1179                System.err.println("Error: bad number " + e);
1180                return;
1181            }
1182            if (density < 72) {
1183                System.err.println("Error: density must be >= 72");
1184                return;
1185            }
1186        }
1187
1188        IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.checkService(
1189                Context.WINDOW_SERVICE));
1190        if (wm == null) {
1191            System.err.println(NO_SYSTEM_ERROR_CODE);
1192            throw new AndroidException("Can't connect to window manager; is the system running?");
1193        }
1194
1195        try {
1196            if (density > 0) {
1197                // TODO(multidisplay): For now Configuration only applies to main screen.
1198                wm.setForcedDisplayDensity(Display.DEFAULT_DISPLAY, density);
1199            } else {
1200                wm.clearForcedDisplayDensity(Display.DEFAULT_DISPLAY);
1201            }
1202        } catch (RemoteException e) {
1203        }
1204    }
1205
1206    private void runToUri(boolean intentScheme) throws Exception {
1207        Intent intent = makeIntent();
1208        System.out.println(intent.toUri(intentScheme ? Intent.URI_INTENT_SCHEME : 0));
1209    }
1210
1211    private class IntentReceiver extends IIntentReceiver.Stub {
1212        private boolean mFinished = false;
1213
1214        @Override
1215        public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
1216                boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
1217            String line = "Broadcast completed: result=" + resultCode;
1218            if (data != null) line = line + ", data=\"" + data + "\"";
1219            if (extras != null) line = line + ", extras: " + extras;
1220            System.out.println(line);
1221            mFinished = true;
1222            notifyAll();
1223        }
1224
1225        public synchronized void waitForFinish() {
1226            try {
1227                while (!mFinished) wait();
1228            } catch (InterruptedException e) {
1229                throw new IllegalStateException(e);
1230            }
1231        }
1232    }
1233
1234    private class InstrumentationWatcher extends IInstrumentationWatcher.Stub {
1235        private boolean mFinished = false;
1236        private boolean mRawMode = false;
1237
1238        /**
1239         * Set or reset "raw mode".  In "raw mode", all bundles are dumped.  In "pretty mode",
1240         * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that.
1241         * @param rawMode true for raw mode, false for pretty mode.
1242         */
1243        public void setRawOutput(boolean rawMode) {
1244            mRawMode = rawMode;
1245        }
1246
1247        public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) {
1248            synchronized (this) {
1249                // pretty printer mode?
1250                String pretty = null;
1251                if (!mRawMode && results != null) {
1252                    pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
1253                }
1254                if (pretty != null) {
1255                    System.out.print(pretty);
1256                } else {
1257                    if (results != null) {
1258                        for (String key : results.keySet()) {
1259                            System.out.println(
1260                                    "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key));
1261                        }
1262                    }
1263                    System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode);
1264                }
1265                notifyAll();
1266            }
1267        }
1268
1269        public void instrumentationFinished(ComponentName name, int resultCode,
1270                Bundle results) {
1271            synchronized (this) {
1272                // pretty printer mode?
1273                String pretty = null;
1274                if (!mRawMode && results != null) {
1275                    pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
1276                }
1277                if (pretty != null) {
1278                    System.out.println(pretty);
1279                } else {
1280                    if (results != null) {
1281                        for (String key : results.keySet()) {
1282                            System.out.println(
1283                                    "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key));
1284                        }
1285                    }
1286                    System.out.println("INSTRUMENTATION_CODE: " + resultCode);
1287                }
1288                mFinished = true;
1289                notifyAll();
1290            }
1291        }
1292
1293        public boolean waitForFinish() {
1294            synchronized (this) {
1295                while (!mFinished) {
1296                    try {
1297                        if (!mAm.asBinder().pingBinder()) {
1298                            return false;
1299                        }
1300                        wait(1000);
1301                    } catch (InterruptedException e) {
1302                        throw new IllegalStateException(e);
1303                    }
1304                }
1305            }
1306            return true;
1307        }
1308    }
1309
1310    private String nextOption() {
1311        if (mCurArgData != null) {
1312            String prev = mArgs[mNextArg - 1];
1313            throw new IllegalArgumentException("No argument expected after \"" + prev + "\"");
1314        }
1315        if (mNextArg >= mArgs.length) {
1316            return null;
1317        }
1318        String arg = mArgs[mNextArg];
1319        if (!arg.startsWith("-")) {
1320            return null;
1321        }
1322        mNextArg++;
1323        if (arg.equals("--")) {
1324            return null;
1325        }
1326        if (arg.length() > 1 && arg.charAt(1) != '-') {
1327            if (arg.length() > 2) {
1328                mCurArgData = arg.substring(2);
1329                return arg.substring(0, 2);
1330            } else {
1331                mCurArgData = null;
1332                return arg;
1333            }
1334        }
1335        mCurArgData = null;
1336        return arg;
1337    }
1338
1339    private String nextArg() {
1340        if (mCurArgData != null) {
1341            String arg = mCurArgData;
1342            mCurArgData = null;
1343            return arg;
1344        } else if (mNextArg < mArgs.length) {
1345            return mArgs[mNextArg++];
1346        } else {
1347            return null;
1348        }
1349    }
1350
1351    private String nextArgRequired() {
1352        String arg = nextArg();
1353        if (arg == null) {
1354            String prev = mArgs[mNextArg - 1];
1355            throw new IllegalArgumentException("Argument expected after \"" + prev + "\"");
1356        }
1357        return arg;
1358    }
1359
1360    private static void showUsage() {
1361        System.err.println(
1362                "usage: am [subcommand] [options]\n" +
1363                "usage: am start [-D] [-W] [-P <FILE>] [--start-profiler <FILE>]\n" +
1364                "               [--R COUNT] [-S] [--opengl-trace] <INTENT>\n" +
1365                "       am startservice <INTENT>\n" +
1366                "       am force-stop <PACKAGE>\n" +
1367                "       am kill <PACKAGE>\n" +
1368                "       am kill-all\n" +
1369                "       am broadcast <INTENT>\n" +
1370                "       am instrument [-r] [-e <NAME> <VALUE>] [-p <FILE>] [-w]\n" +
1371                "               [--user <USER_ID> | all | current]\n" +
1372                "               [--no-window-animation] <COMPONENT>\n" +
1373                "       am profile start <PROCESS> <FILE>\n" +
1374                "       am profile stop [<PROCESS>]\n" +
1375                "       am dumpheap [flags] <PROCESS> <FILE>\n" +
1376                "       am set-debug-app [-w] [--persistent] <PACKAGE>\n" +
1377                "       am clear-debug-app\n" +
1378                "       am monitor [--gdb <port>]\n" +
1379                "       am screen-compat [on|off] <PACKAGE>\n" +
1380                "       am display-size [reset|MxN]\n" +
1381                "       am display-density [reset|DENSITY]\n" +
1382                "       am to-uri [INTENT]\n" +
1383                "       am to-intent-uri [INTENT]\n" +
1384                "       am switch-user <USER_ID>\n" +
1385                "       am stop-user <USER_ID>\n" +
1386                "\n" +
1387                "am start: start an Activity.  Options are:\n" +
1388                "    -D: enable debugging\n" +
1389                "    -W: wait for launch to complete\n" +
1390                "    --start-profiler <FILE>: start profiler and send results to <FILE>\n" +
1391                "    -P <FILE>: like above, but profiling stops when app goes idle\n" +
1392                "    -R: repeat the activity launch <COUNT> times.  Prior to each repeat,\n" +
1393                "        the top activity will be finished.\n" +
1394                "    -S: force stop the target app before starting the activity\n" +
1395                "    --opengl-trace: enable tracing of OpenGL functions\n" +
1396                "\n" +
1397                "am startservice: start a Service.\n" +
1398                "\n" +
1399                "am force-stop: force stop everything associated with <PACKAGE>.\n" +
1400                "\n" +
1401                "am kill: Kill all processes associated with <PACKAGE>.  Only kills.\n" +
1402                "  processes that are safe to kill -- that is, will not impact the user\n" +
1403                "  experience.\n" +
1404                "\n" +
1405                "am kill-all: Kill all background processes.\n" +
1406                "\n" +
1407                "am broadcast: send a broadcast Intent.\n" +
1408                "\n" +
1409                "am instrument: start an Instrumentation.  Typically this target <COMPONENT>\n" +
1410                "  is the form <TEST_PACKAGE>/<RUNNER_CLASS>.  Options are:\n" +
1411                "    -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT).  Use with\n" +
1412                "        [-e perf true] to generate raw output for performance measurements.\n" +
1413                "    -e <NAME> <VALUE>: set argument <NAME> to <VALUE>.  For test runners a\n" +
1414                "        common form is [-e <testrunner_flag> <value>[,<value>...]].\n" +
1415                "    -p <FILE>: write profiling data to <FILE>\n" +
1416                "    -w: wait for instrumentation to finish before returning.  Required for\n" +
1417                "        test runners.\n" +
1418                "    --user [<USER_ID> | all | current]: Specify user instrumentation runs in.\n" +
1419                "    --no-window-animation: turn off window animations will running.\n" +
1420                "\n" +
1421                "am profile: start and stop profiler on a process.\n" +
1422                "\n" +
1423                "am dumpheap: dump the heap of a process.  Options are:\n" +
1424                "    -n: dump native heap instead of managed heap\n" +
1425                "\n" +
1426                "am set-debug-app: set application <PACKAGE> to debug.  Options are:\n" +
1427                "    -w: wait for debugger when application starts\n" +
1428                "    --persistent: retain this value\n" +
1429                "\n" +
1430                "am clear-debug-app: clear the previously set-debug-app.\n" +
1431                "\n" +
1432                "am monitor: start monitoring for crashes or ANRs.\n" +
1433                "    --gdb: start gdbserv on the given port at crash/ANR\n" +
1434                "\n" +
1435                "am screen-compat: control screen compatibility mode of <PACKAGE>.\n" +
1436                "\n" +
1437                "am display-size: override display size.\n" +
1438                "\n" +
1439                "am display-density: override display density.\n" +
1440                "\n" +
1441                "am to-uri: print the given Intent specification as a URI.\n" +
1442                "\n" +
1443                "am to-intent-uri: print the given Intent specification as an intent: URI.\n" +
1444                "\n" +
1445                "am switch-user: switch to put USER_ID in the foreground, starting" +
1446                "  execution of that user if it is currently stopped.\n" +
1447                "\n" +
1448                "am stop-user: stop execution of USER_ID, not allowing it to run any" +
1449                "  code until a later explicit switch to it.\n" +
1450                "\n" +
1451                "<INTENT> specifications include these flags and arguments:\n" +
1452                "    [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]\n" +
1453                "    [-c <CATEGORY> [-c <CATEGORY>] ...]\n" +
1454                "    [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]\n" +
1455                "    [--esn <EXTRA_KEY> ...]\n" +
1456                "    [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]\n" +
1457                "    [--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]\n" +
1458                "    [--el <EXTRA_KEY> <EXTRA_LONG_VALUE> ...]\n" +
1459                "    [--ef <EXTRA_KEY> <EXTRA_FLOAT_VALUE> ...]\n" +
1460                "    [--eu <EXTRA_KEY> <EXTRA_URI_VALUE> ...]\n" +
1461                "    [--ecn <EXTRA_KEY> <EXTRA_COMPONENT_NAME_VALUE>]\n" +
1462                "    [--eia <EXTRA_KEY> <EXTRA_INT_VALUE>[,<EXTRA_INT_VALUE...]]\n" +
1463                "    [--ela <EXTRA_KEY> <EXTRA_LONG_VALUE>[,<EXTRA_LONG_VALUE...]]\n" +
1464                "    [--efa <EXTRA_KEY> <EXTRA_FLOAT_VALUE>[,<EXTRA_FLOAT_VALUE...]]\n" +
1465                "    [-n <COMPONENT>] [-f <FLAGS>]\n" +
1466                "    [--user [<USER_ID> | all | current]\n" +
1467                "    [--grant-read-uri-permission] [--grant-write-uri-permission]\n" +
1468                "    [--debug-log-resolution] [--exclude-stopped-packages]\n" +
1469                "    [--include-stopped-packages]\n" +
1470                "    [--activity-brought-to-front] [--activity-clear-top]\n" +
1471                "    [--activity-clear-when-task-reset] [--activity-exclude-from-recents]\n" +
1472                "    [--activity-launched-from-history] [--activity-multiple-task]\n" +
1473                "    [--activity-no-animation] [--activity-no-history]\n" +
1474                "    [--activity-no-user-action] [--activity-previous-is-top]\n" +
1475                "    [--activity-reorder-to-front] [--activity-reset-task-if-needed]\n" +
1476                "    [--activity-single-top] [--activity-clear-task]\n" +
1477                "    [--activity-task-on-home]\n" +
1478                "    [--receiver-registered-only] [--receiver-replace-pending]\n" +
1479                "    [--selector]\n" +
1480                "    [<URI> | <PACKAGE> | <COMPONENT>]\n"
1481                );
1482    }
1483}
1484