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