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