Am.java revision f123e49bf0708719b51a7064ae134c097abe4a54
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.ActivityManagerNative;
22import android.app.IActivityController;
23import android.app.IActivityManager;
24import android.app.IInstrumentationWatcher;
25import android.app.Instrumentation;
26import android.content.ComponentName;
27import android.content.IIntentReceiver;
28import android.content.Intent;
29import android.net.Uri;
30import android.os.Bundle;
31import android.os.ParcelFileDescriptor;
32import android.os.RemoteException;
33import android.os.ServiceManager;
34import android.util.AndroidException;
35import android.view.IWindowManager;
36
37import java.io.BufferedReader;
38import java.io.File;
39import java.io.FileNotFoundException;
40import java.io.IOException;
41import java.io.InputStreamReader;
42import java.io.PrintStream;
43import java.net.URISyntaxException;
44import java.util.Iterator;
45import java.util.Set;
46
47public class Am {
48
49    private IActivityManager mAm;
50    private String[] mArgs;
51    private int mNextArg;
52    private String mCurArgData;
53
54    private boolean mDebugOption = false;
55    private boolean mWaitOption = false;
56
57    // These are magic strings understood by the Eclipse plugin.
58    private static final String FATAL_ERROR_CODE = "Error type 1";
59    private static final String NO_SYSTEM_ERROR_CODE = "Error type 2";
60    private static final String NO_CLASS_ERROR_CODE = "Error type 3";
61
62    /**
63     * Command-line entry point.
64     *
65     * @param args The command-line arguments
66     */
67    public static void main(String[] args) {
68        try {
69            (new Am()).run(args);
70        } catch (IllegalArgumentException e) {
71            showUsage();
72            System.err.println("Error: " + e.getMessage());
73        } catch (Exception e) {
74            System.err.println(e.toString());
75            System.exit(1);
76        }
77    }
78
79    private void run(String[] args) throws Exception {
80        if (args.length < 1) {
81            showUsage();
82            return;
83        }
84
85        mAm = ActivityManagerNative.getDefault();
86        if (mAm == null) {
87            System.err.println(NO_SYSTEM_ERROR_CODE);
88            throw new AndroidException("Can't connect to activity manager; is the system running?");
89        }
90
91        mArgs = args;
92        String op = args[0];
93        mNextArg = 1;
94
95        if (op.equals("start")) {
96            runStart();
97        } else if (op.equals("startservice")) {
98            runStartService();
99        } else if (op.equals("instrument")) {
100            runInstrument();
101        } else if (op.equals("broadcast")) {
102            sendBroadcast();
103        } else if (op.equals("profile")) {
104            runProfile();
105        } else if (op.equals("monitor")) {
106            runMonitor();
107        } else {
108            throw new IllegalArgumentException("Unknown command: " + op);
109        }
110    }
111
112    private Intent makeIntent() throws URISyntaxException {
113        Intent intent = new Intent();
114        boolean hasIntentInfo = false;
115
116        mDebugOption = false;
117        mWaitOption = false;
118        Uri data = null;
119        String type = null;
120
121        String opt;
122        while ((opt=nextOption()) != null) {
123            if (opt.equals("-a")) {
124                intent.setAction(nextArgRequired());
125                hasIntentInfo = true;
126            } else if (opt.equals("-d")) {
127                data = Uri.parse(nextArgRequired());
128                hasIntentInfo = true;
129            } else if (opt.equals("-t")) {
130                type = nextArgRequired();
131                hasIntentInfo = true;
132            } else if (opt.equals("-c")) {
133                intent.addCategory(nextArgRequired());
134                hasIntentInfo = true;
135            } else if (opt.equals("-e") || opt.equals("--es")) {
136                String key = nextArgRequired();
137                String value = nextArgRequired();
138                intent.putExtra(key, value);
139                hasIntentInfo = true;
140            } else if (opt.equals("--esn")) {
141                String key = nextArgRequired();
142                intent.putExtra(key, (String) null);
143                hasIntentInfo = true;
144            } else if (opt.equals("--ei")) {
145                String key = nextArgRequired();
146                String value = nextArgRequired();
147                intent.putExtra(key, Integer.valueOf(value));
148                hasIntentInfo = true;
149            } else if (opt.equals("--ez")) {
150                String key = nextArgRequired();
151                String value = nextArgRequired();
152                intent.putExtra(key, Boolean.valueOf(value));
153                hasIntentInfo = true;
154            } else if (opt.equals("-n")) {
155                String str = nextArgRequired();
156                ComponentName cn = ComponentName.unflattenFromString(str);
157                if (cn == null) throw new IllegalArgumentException("Bad component name: " + str);
158                intent.setComponent(cn);
159                hasIntentInfo = true;
160            } else if (opt.equals("-f")) {
161                String str = nextArgRequired();
162                intent.setFlags(Integer.decode(str).intValue());
163            } else if (opt.equals("--grant-read-uri-permission")) {
164                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
165            } else if (opt.equals("--grant-write-uri-permission")) {
166                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
167            } else if (opt.equals("--debug-log-resolution")) {
168                intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
169            } else if (opt.equals("--activity-brought-to-front")) {
170                intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
171            } else if (opt.equals("--activity-clear-top")) {
172                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
173            } else if (opt.equals("--activity-clear-when-task-reset")) {
174                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
175            } else if (opt.equals("--activity-exclude-from-recents")) {
176                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
177            } else if (opt.equals("--activity-launched-from-history")) {
178                intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
179            } else if (opt.equals("--activity-multiple-task")) {
180                intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
181            } else if (opt.equals("--activity-no-animation")) {
182                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
183            } else if (opt.equals("--activity-no-history")) {
184                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
185            } else if (opt.equals("--activity-no-user-action")) {
186                intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
187            } else if (opt.equals("--activity-previous-is-top")) {
188                intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
189            } else if (opt.equals("--activity-reorder-to-front")) {
190                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
191            } else if (opt.equals("--activity-reset-task-if-needed")) {
192                intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
193            } else if (opt.equals("--activity-single-top")) {
194                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
195            } else if (opt.equals("--receiver-registered-only")) {
196                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
197            } else if (opt.equals("--receiver-replace-pending")) {
198                intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
199            } else if (opt.equals("-D")) {
200                mDebugOption = true;
201            } else if (opt.equals("-W")) {
202                mWaitOption = true;
203            } else {
204                System.err.println("Error: Unknown option: " + opt);
205                showUsage();
206                return null;
207            }
208        }
209        intent.setDataAndType(data, type);
210
211        String uri = nextArg();
212        if (uri != null) {
213            Intent oldIntent = intent;
214            intent = Intent.parseUri(uri, 0);
215            if (oldIntent.getAction() != null) {
216                intent.setAction(oldIntent.getAction());
217            }
218            if (oldIntent.getData() != null || oldIntent.getType() != null) {
219                intent.setDataAndType(oldIntent.getData(), oldIntent.getType());
220            }
221            Set cats = oldIntent.getCategories();
222            if (cats != null) {
223                Iterator it = cats.iterator();
224                while (it.hasNext()) {
225                    intent.addCategory((String)it.next());
226                }
227            }
228            hasIntentInfo = true;
229        }
230
231        if (!hasIntentInfo) throw new IllegalArgumentException("No intent supplied");
232        return intent;
233    }
234
235    private void runStartService() throws Exception {
236        Intent intent = makeIntent();
237        System.out.println("Starting service: " + intent);
238        ComponentName cn = mAm.startService(null, intent, intent.getType());
239        if (cn == null) {
240            System.err.println("Error: Not found; no service started.");
241        }
242    }
243
244    private void runStart() throws Exception {
245        Intent intent = makeIntent();
246        System.out.println("Starting: " + intent);
247        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
248        // XXX should do something to determine the MIME type.
249        IActivityManager.WaitResult result = null;
250        int res;
251        if (mWaitOption) {
252            result = mAm.startActivityAndWait(null, intent, intent.getType(),
253                        null, 0, null, null, 0, false, mDebugOption);
254            res = result.result;
255        } else {
256            res = mAm.startActivity(null, intent, intent.getType(),
257                    null, 0, null, null, 0, false, mDebugOption);
258        }
259        PrintStream out = mWaitOption ? System.out : System.err;
260        boolean launched = false;
261        switch (res) {
262            case IActivityManager.START_SUCCESS:
263                launched = true;
264                break;
265            case IActivityManager.START_SWITCHES_CANCELED:
266                launched = true;
267                out.println(
268                        "Warning: Activity not started because the "
269                        + " current activity is being kept for the user.");
270                break;
271            case IActivityManager.START_DELIVERED_TO_TOP:
272                launched = true;
273                out.println(
274                        "Warning: Activity not started, intent has "
275                        + "been delivered to currently running "
276                        + "top-most instance.");
277                break;
278            case IActivityManager.START_RETURN_INTENT_TO_CALLER:
279                launched = true;
280                out.println(
281                        "Warning: Activity not started because intent "
282                        + "should be handled by the caller");
283                break;
284            case IActivityManager.START_TASK_TO_FRONT:
285                launched = true;
286                out.println(
287                        "Warning: Activity not started, its current "
288                        + "task has been brought to the front");
289                break;
290            case IActivityManager.START_INTENT_NOT_RESOLVED:
291                out.println(
292                        "Error: Activity not started, unable to "
293                        + "resolve " + intent.toString());
294                break;
295            case IActivityManager.START_CLASS_NOT_FOUND:
296                out.println(NO_CLASS_ERROR_CODE);
297                out.println("Error: Activity class " +
298                        intent.getComponent().toShortString()
299                        + " does not exist.");
300                break;
301            case IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
302                out.println(
303                        "Error: Activity not started, you requested to "
304                        + "both forward and receive its result");
305                break;
306            case IActivityManager.START_PERMISSION_DENIED:
307                out.println(
308                        "Error: Activity not started, you do not "
309                        + "have permission to access it.");
310                break;
311            default:
312                out.println(
313                        "Error: Activity not started, unknown error code " + res);
314                break;
315        }
316        if (mWaitOption && launched) {
317            if (result == null) {
318                result = new IActivityManager.WaitResult();
319                result.who = intent.getComponent();
320            }
321            System.out.println("Status: " + (result.timeout ? "timeout" : "ok"));
322            if (result.who != null) {
323                System.out.println("Activity: " + result.who.flattenToShortString());
324            }
325            if (result.thisTime >= 0) {
326                System.out.println("ThisTime: " + result.thisTime);
327            }
328            if (result.totalTime >= 0) {
329                System.out.println("TotalTime: " + result.totalTime);
330            }
331            System.out.println("Complete");
332        }
333    }
334
335    private void sendBroadcast() throws Exception {
336        Intent intent = makeIntent();
337        IntentReceiver receiver = new IntentReceiver();
338        System.out.println("Broadcasting: " + intent);
339        mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, null, true, false);
340        receiver.waitForFinish();
341    }
342
343    private void runInstrument() throws Exception {
344        String profileFile = null;
345        boolean wait = false;
346        boolean rawMode = false;
347        boolean no_window_animation = false;
348        Bundle args = new Bundle();
349        String argKey = null, argValue = null;
350        IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
351
352        String opt;
353        while ((opt=nextOption()) != null) {
354            if (opt.equals("-p")) {
355                profileFile = nextArgRequired();
356            } else if (opt.equals("-w")) {
357                wait = true;
358            } else if (opt.equals("-r")) {
359                rawMode = true;
360            } else if (opt.equals("-e")) {
361                argKey = nextArgRequired();
362                argValue = nextArgRequired();
363                args.putString(argKey, argValue);
364            } else if (opt.equals("--no_window_animation")) {
365                no_window_animation = true;
366            } else {
367                System.err.println("Error: Unknown option: " + opt);
368                showUsage();
369                return;
370            }
371        }
372
373        String cnArg = nextArgRequired();
374        ComponentName cn = ComponentName.unflattenFromString(cnArg);
375        if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg);
376
377        InstrumentationWatcher watcher = null;
378        if (wait) {
379            watcher = new InstrumentationWatcher();
380            watcher.setRawOutput(rawMode);
381        }
382        float[] oldAnims = null;
383        if (no_window_animation) {
384            oldAnims = wm.getAnimationScales();
385            wm.setAnimationScale(0, 0.0f);
386            wm.setAnimationScale(1, 0.0f);
387        }
388
389        if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher)) {
390            throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString());
391        }
392
393        if (watcher != null) {
394            if (!watcher.waitForFinish()) {
395                System.out.println("INSTRUMENTATION_ABORTED: System has crashed.");
396            }
397        }
398
399        if (oldAnims != null) {
400            wm.setAnimationScales(oldAnims);
401        }
402    }
403
404    private void runProfile() throws Exception {
405        String profileFile = null;
406        boolean start = false;
407        String process = nextArgRequired();
408        ParcelFileDescriptor fd = null;
409
410        String cmd = nextArgRequired();
411        if ("start".equals(cmd)) {
412            start = true;
413            profileFile = nextArgRequired();
414            try {
415                fd = ParcelFileDescriptor.open(
416                        new File(profileFile),
417                        ParcelFileDescriptor.MODE_CREATE |
418                        ParcelFileDescriptor.MODE_TRUNCATE |
419                        ParcelFileDescriptor.MODE_READ_WRITE);
420            } catch (FileNotFoundException e) {
421                System.err.println("Error: Unable to open file: " + profileFile);
422                return;
423            }
424        } else if (!"stop".equals(cmd)) {
425            throw new IllegalArgumentException("Profile command " + cmd + " not valid");
426        }
427
428        if (!mAm.profileControl(process, start, profileFile, fd)) {
429            throw new AndroidException("PROFILE FAILED on process " + process);
430        }
431    }
432
433    class MyActivityController extends IActivityController.Stub {
434        final String mGdbPort;
435
436        static final int STATE_NORMAL = 0;
437        static final int STATE_CRASHED = 1;
438        static final int STATE_EARLY_ANR = 2;
439        static final int STATE_ANR = 3;
440
441        int mState;
442
443        static final int RESULT_DEFAULT = 0;
444
445        static final int RESULT_CRASH_DIALOG = 0;
446        static final int RESULT_CRASH_KILL = 1;
447
448        static final int RESULT_EARLY_ANR_CONTINUE = 0;
449        static final int RESULT_EARLY_ANR_KILL = 1;
450
451        static final int RESULT_ANR_DIALOG = 0;
452        static final int RESULT_ANR_KILL = 1;
453        static final int RESULT_ANR_WAIT = 1;
454
455        int mResult;
456
457        Process mGdbProcess;
458        Thread mGdbThread;
459        boolean mGotGdbPrint;
460
461        MyActivityController(String gdbPort) {
462            mGdbPort = gdbPort;
463        }
464
465        @Override
466        public boolean activityResuming(String pkg) throws RemoteException {
467            synchronized (this) {
468                System.out.println("** Activity resuming: " + pkg);
469            }
470            return true;
471        }
472
473        @Override
474        public boolean activityStarting(Intent intent, String pkg) throws RemoteException {
475            synchronized (this) {
476                System.out.println("** Activity starting: " + pkg);
477            }
478            return true;
479        }
480
481        @Override
482        public boolean appCrashed(String processName, int pid, String shortMsg, String longMsg,
483                long timeMillis, String stackTrace) throws RemoteException {
484            synchronized (this) {
485                System.out.println("** ERROR: PROCESS CRASHED");
486                System.out.println("processName: " + processName);
487                System.out.println("processPid: " + pid);
488                System.out.println("shortMsg: " + shortMsg);
489                System.out.println("longMsg: " + longMsg);
490                System.out.println("timeMillis: " + timeMillis);
491                System.out.println("stack:");
492                System.out.print(stackTrace);
493                System.out.println("#");
494                int result = waitControllerLocked(pid, STATE_CRASHED);
495                return result == RESULT_CRASH_KILL ? false : true;
496            }
497        }
498
499        @Override
500        public int appEarlyNotResponding(String processName, int pid, String annotation)
501                throws RemoteException {
502            synchronized (this) {
503                System.out.println("** ERROR: EARLY PROCESS NOT RESPONDING");
504                System.out.println("processName: " + processName);
505                System.out.println("processPid: " + pid);
506                System.out.println("annotation: " + annotation);
507                int result = waitControllerLocked(pid, STATE_EARLY_ANR);
508                if (result == RESULT_EARLY_ANR_KILL) return -1;
509                return 0;
510            }
511        }
512
513        @Override
514        public int appNotResponding(String processName, int pid, String processStats)
515                throws RemoteException {
516            synchronized (this) {
517                System.out.println("** ERROR: PROCESS NOT RESPONDING");
518                System.out.println("processName: " + processName);
519                System.out.println("processPid: " + pid);
520                System.out.println("processStats:");
521                System.out.print(processStats);
522                System.out.println("#");
523                int result = waitControllerLocked(pid, STATE_ANR);
524                if (result == RESULT_ANR_KILL) return -1;
525                if (result == RESULT_ANR_WAIT) return 1;
526                return 0;
527            }
528        }
529
530        void killGdbLocked() {
531            mGotGdbPrint = false;
532            if (mGdbProcess != null) {
533                System.out.println("Stopping gdbserver");
534                mGdbProcess.destroy();
535                mGdbProcess = null;
536            }
537            if (mGdbThread != null) {
538                mGdbThread.interrupt();
539                mGdbThread = null;
540            }
541        }
542
543        int waitControllerLocked(int pid, int state) {
544            if (mGdbPort != null) {
545                killGdbLocked();
546
547                try {
548                    System.out.println("Starting gdbserver on port " + mGdbPort);
549                    System.out.println("Do the following:");
550                    System.out.println("  adb forward tcp:" + mGdbPort + " tcp:" + mGdbPort);
551                    System.out.println("  gdbclient app_process :" + mGdbPort);
552
553                    mGdbProcess = Runtime.getRuntime().exec(new String[] {
554                            "gdbserver", ":" + mGdbPort, "--attach", Integer.toString(pid)
555                    });
556                    final InputStreamReader converter = new InputStreamReader(
557                            mGdbProcess.getInputStream());
558                    mGdbThread = new Thread() {
559                        @Override
560                        public void run() {
561                            BufferedReader in = new BufferedReader(converter);
562                            String line;
563                            int count = 0;
564                            while (true) {
565                                synchronized (MyActivityController.this) {
566                                    if (mGdbThread == null) {
567                                        return;
568                                    }
569                                    if (count == 2) {
570                                        mGotGdbPrint = true;
571                                        MyActivityController.this.notifyAll();
572                                    }
573                                }
574                                try {
575                                    line = in.readLine();
576                                    if (line == null) {
577                                        return;
578                                    }
579                                    System.out.println("GDB: " + line);
580                                    count++;
581                                } catch (IOException e) {
582                                    return;
583                                }
584                            }
585                        }
586                    };
587                    mGdbThread.start();
588
589                    // Stupid waiting for .5s.  Doesn't matter if we end early.
590                    try {
591                        this.wait(500);
592                    } catch (InterruptedException e) {
593                    }
594
595                } catch (IOException e) {
596                    System.err.println("Failure starting gdbserver: " + e);
597                    killGdbLocked();
598                }
599            }
600            mState = state;
601            System.out.println("");
602            printMessageForState();
603
604            while (mState != STATE_NORMAL) {
605                try {
606                    wait();
607                } catch (InterruptedException e) {
608                }
609            }
610
611            killGdbLocked();
612
613            return mResult;
614        }
615
616        void resumeController(int result) {
617            synchronized (this) {
618                mState = STATE_NORMAL;
619                mResult = result;
620                notifyAll();
621            }
622        }
623
624        void printMessageForState() {
625            switch (mState) {
626                case STATE_NORMAL:
627                    System.out.println("Monitoring activity manager...  available commands:");
628                    break;
629                case STATE_CRASHED:
630                    System.out.println("Waiting after crash...  available commands:");
631                    System.out.println("(c)ontinue: show crash dialog");
632                    System.out.println("(k)ill: immediately kill app");
633                    break;
634                case STATE_EARLY_ANR:
635                    System.out.println("Waiting after early ANR...  available commands:");
636                    System.out.println("(c)ontinue: standard ANR processing");
637                    System.out.println("(k)ill: immediately kill app");
638                    break;
639                case STATE_ANR:
640                    System.out.println("Waiting after ANR...  available commands:");
641                    System.out.println("(c)ontinue: show ANR dialog");
642                    System.out.println("(k)ill: immediately kill app");
643                    System.out.println("(w)ait: wait some more");
644                    break;
645            }
646            System.out.println("(q)uit: finish monitoring");
647        }
648
649        void run() throws RemoteException {
650            try {
651                printMessageForState();
652
653                mAm.setActivityController(this);
654                mState = STATE_NORMAL;
655
656                InputStreamReader converter = new InputStreamReader(System.in);
657                BufferedReader in = new BufferedReader(converter);
658                String line;
659
660                while ((line = in.readLine()) != null) {
661                    boolean addNewline = true;
662                    if (line.length() <= 0) {
663                        addNewline = false;
664                    } else if ("q".equals(line) || "quit".equals(line)) {
665                        resumeController(RESULT_DEFAULT);
666                        break;
667                    } else if (mState == STATE_CRASHED) {
668                        if ("c".equals(line) || "continue".equals(line)) {
669                            resumeController(RESULT_CRASH_DIALOG);
670                        } else if ("k".equals(line) || "kill".equals(line)) {
671                            resumeController(RESULT_CRASH_KILL);
672                        } else {
673                            System.out.println("Invalid command: " + line);
674                        }
675                    } else if (mState == STATE_ANR) {
676                        if ("c".equals(line) || "continue".equals(line)) {
677                            resumeController(RESULT_ANR_DIALOG);
678                        } else if ("k".equals(line) || "kill".equals(line)) {
679                            resumeController(RESULT_ANR_KILL);
680                        } else if ("w".equals(line) || "wait".equals(line)) {
681                            resumeController(RESULT_ANR_WAIT);
682                        } else {
683                            System.out.println("Invalid command: " + line);
684                        }
685                    } else if (mState == STATE_EARLY_ANR) {
686                        if ("c".equals(line) || "continue".equals(line)) {
687                            resumeController(RESULT_EARLY_ANR_CONTINUE);
688                        } else if ("k".equals(line) || "kill".equals(line)) {
689                            resumeController(RESULT_EARLY_ANR_KILL);
690                        } else {
691                            System.out.println("Invalid command: " + line);
692                        }
693                    } else {
694                        System.out.println("Invalid command: " + line);
695                    }
696
697                    synchronized (this) {
698                        if (addNewline) {
699                            System.out.println("");
700                        }
701                        printMessageForState();
702                    }
703                }
704
705            } catch (IOException e) {
706                e.printStackTrace();
707            } finally {
708                mAm.setActivityController(null);
709            }
710        }
711    }
712
713    private void runMonitor() throws Exception {
714        String opt;
715        String gdbPort = null;
716        while ((opt=nextOption()) != null) {
717            if (opt.equals("--gdb")) {
718                gdbPort = nextArgRequired();
719            } else {
720                System.err.println("Error: Unknown option: " + opt);
721                showUsage();
722                return;
723            }
724        }
725
726        MyActivityController controller = new MyActivityController(gdbPort);
727        controller.run();
728    }
729
730    private class IntentReceiver extends IIntentReceiver.Stub {
731        private boolean mFinished = false;
732
733        public synchronized void performReceive(
734                Intent intent, int rc, String data, Bundle ext, boolean ord,
735                boolean sticky) {
736            String line = "Broadcast completed: result=" + rc;
737            if (data != null) line = line + ", data=\"" + data + "\"";
738            if (ext != null) line = line + ", extras: " + ext;
739            System.out.println(line);
740            mFinished = true;
741            notifyAll();
742        }
743
744        public synchronized void waitForFinish() {
745            try {
746                while (!mFinished) wait();
747            } catch (InterruptedException e) {
748                throw new IllegalStateException(e);
749            }
750        }
751    }
752
753    private class InstrumentationWatcher extends IInstrumentationWatcher.Stub {
754        private boolean mFinished = false;
755        private boolean mRawMode = false;
756
757        /**
758         * Set or reset "raw mode".  In "raw mode", all bundles are dumped.  In "pretty mode",
759         * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that.
760         * @param rawMode true for raw mode, false for pretty mode.
761         */
762        public void setRawOutput(boolean rawMode) {
763            mRawMode = rawMode;
764        }
765
766        public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) {
767            synchronized (this) {
768                // pretty printer mode?
769                String pretty = null;
770                if (!mRawMode && results != null) {
771                    pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
772                }
773                if (pretty != null) {
774                    System.out.print(pretty);
775                } else {
776                    if (results != null) {
777                        for (String key : results.keySet()) {
778                            System.out.println(
779                                    "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key));
780                        }
781                    }
782                    System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode);
783                }
784                notifyAll();
785            }
786        }
787
788        public void instrumentationFinished(ComponentName name, int resultCode,
789                Bundle results) {
790            synchronized (this) {
791                // pretty printer mode?
792                String pretty = null;
793                if (!mRawMode && results != null) {
794                    pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
795                }
796                if (pretty != null) {
797                    System.out.println(pretty);
798                } else {
799                    if (results != null) {
800                        for (String key : results.keySet()) {
801                            System.out.println(
802                                    "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key));
803                        }
804                    }
805                    System.out.println("INSTRUMENTATION_CODE: " + resultCode);
806                }
807                mFinished = true;
808                notifyAll();
809            }
810        }
811
812        public boolean waitForFinish() {
813            synchronized (this) {
814                while (!mFinished) {
815                    try {
816                        if (!mAm.asBinder().pingBinder()) {
817                            return false;
818                        }
819                        wait(1000);
820                    } catch (InterruptedException e) {
821                        throw new IllegalStateException(e);
822                    }
823                }
824            }
825            return true;
826        }
827    }
828
829    private String nextOption() {
830        if (mCurArgData != null) {
831            String prev = mArgs[mNextArg - 1];
832            throw new IllegalArgumentException("No argument expected after \"" + prev + "\"");
833        }
834        if (mNextArg >= mArgs.length) {
835            return null;
836        }
837        String arg = mArgs[mNextArg];
838        if (!arg.startsWith("-")) {
839            return null;
840        }
841        mNextArg++;
842        if (arg.equals("--")) {
843            return null;
844        }
845        if (arg.length() > 1 && arg.charAt(1) != '-') {
846            if (arg.length() > 2) {
847                mCurArgData = arg.substring(2);
848                return arg.substring(0, 2);
849            } else {
850                mCurArgData = null;
851                return arg;
852            }
853        }
854        mCurArgData = null;
855        return arg;
856    }
857
858    private String nextArg() {
859        if (mCurArgData != null) {
860            String arg = mCurArgData;
861            mCurArgData = null;
862            return arg;
863        } else if (mNextArg < mArgs.length) {
864            return mArgs[mNextArg++];
865        } else {
866            return null;
867        }
868    }
869
870    private String nextArgRequired() {
871        String arg = nextArg();
872        if (arg == null) {
873            String prev = mArgs[mNextArg - 1];
874            throw new IllegalArgumentException("Argument expected after \"" + prev + "\"");
875        }
876        return arg;
877    }
878
879    private static void showUsage() {
880        System.err.println(
881                "usage: am [subcommand] [options]\n" +
882                "\n" +
883                "    start an Activity: am start [-D] [-W] <INTENT>\n" +
884                "        -D: enable debugging\n" +
885                "        -W: wait for launch to complete\n" +
886                "\n" +
887                "    start a Service: am startservice <INTENT>\n" +
888                "\n" +
889                "    send a broadcast Intent: am broadcast <INTENT>\n" +
890                "\n" +
891                "    start an Instrumentation: am instrument [flags] <COMPONENT>\n" +
892                "        -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)\n" +
893                "        -e <NAME> <VALUE>: set argument <NAME> to <VALUE>\n" +
894                "        -p <FILE>: write profiling data to <FILE>\n" +
895                "        -w: wait for instrumentation to finish before returning\n" +
896                "\n" +
897                "    start profiling: am profile <PROCESS> start <FILE>\n" +
898                "    stop profiling: am profile <PROCESS> stop\n" +
899                "\n" +
900                "    start monitoring: am monitor [--gdb <port>]\n" +
901                "        --gdb: start gdbserv on the given port at crash/ANR\n" +
902                "\n" +
903                "    <INTENT> specifications include these flags:\n" +
904                "        [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]\n" +
905                "        [-c <CATEGORY> [-c <CATEGORY>] ...]\n" +
906                "        [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]\n" +
907                "        [--esn <EXTRA_KEY> ...]\n" +
908                "        [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]\n" +
909                "        [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]\n" +
910                "        [-n <COMPONENT>] [-f <FLAGS>]\n" +
911                "        [--grant-read-uri-permission] [--grant-write-uri-permission]\n" +
912                "        [--debug-log-resolution]\n" +
913                "        [--activity-brought-to-front] [--activity-clear-top]\n" +
914                "        [--activity-clear-when-task-reset] [--activity-exclude-from-recents]\n" +
915                "        [--activity-launched-from-history] [--activity-multiple-task]\n" +
916                "        [--activity-no-animation] [--activity-no-history]\n" +
917                "        [--activity-no-user-action] [--activity-previous-is-top]\n" +
918                "        [--activity-reorder-to-front] [--activity-reset-task-if-needed]\n" +
919                "        [--activity-single-top]\n" +
920                "        [--receiver-registered-only] [--receiver-replace-pending]\n" +
921                "        [<URI>]\n"
922                );
923    }
924}
925