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