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