Am.java revision d6c0bb0f0f3827f1c336db20ac9dc0eb90cd46fa
1/*
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19package com.android.commands.am;
20
21import android.app.ActivityManagerNative;
22import android.app.IActivityManager;
23import android.app.IInstrumentationWatcher;
24import android.app.Instrumentation;
25import android.content.ComponentName;
26import android.content.IIntentReceiver;
27import android.content.Intent;
28import android.net.Uri;
29import android.os.Bundle;
30import android.os.ParcelFileDescriptor;
31import android.os.RemoteException;
32import android.os.ServiceManager;
33import android.util.AndroidException;
34import android.view.IWindowManager;
35
36import java.io.File;
37import java.io.FileNotFoundException;
38import java.io.PrintStream;
39import java.net.URISyntaxException;
40import java.util.Iterator;
41import java.util.Set;
42
43public class Am {
44
45    private IActivityManager mAm;
46    private String[] mArgs;
47    private int mNextArg;
48    private String mCurArgData;
49
50    private boolean mDebugOption = false;
51    private boolean mWaitOption = false;
52
53    // These are magic strings understood by the Eclipse plugin.
54    private static final String FATAL_ERROR_CODE = "Error type 1";
55    private static final String NO_SYSTEM_ERROR_CODE = "Error type 2";
56    private static final String NO_CLASS_ERROR_CODE = "Error type 3";
57
58    /**
59     * Command-line entry point.
60     *
61     * @param args The command-line arguments
62     */
63    public static void main(String[] args) {
64        try {
65            (new Am()).run(args);
66        } catch (IllegalArgumentException e) {
67            showUsage();
68            System.err.println("Error: " + e.getMessage());
69        } catch (Exception e) {
70            System.err.println(e.toString());
71            System.exit(1);
72        }
73    }
74
75    private void run(String[] args) throws Exception {
76        if (args.length < 1) {
77            showUsage();
78            return;
79        }
80
81        mAm = ActivityManagerNative.getDefault();
82        if (mAm == null) {
83            System.err.println(NO_SYSTEM_ERROR_CODE);
84            throw new AndroidException("Can't connect to activity manager; is the system running?");
85        }
86
87        mArgs = args;
88        String op = args[0];
89        mNextArg = 1;
90
91        if (op.equals("start")) {
92            runStart();
93        } else if (op.equals("startservice")) {
94            runStartService();
95        } else if (op.equals("instrument")) {
96            runInstrument();
97        } else if (op.equals("broadcast")) {
98            sendBroadcast();
99        } else if (op.equals("profile")) {
100            runProfile();
101        } else {
102            throw new IllegalArgumentException("Unknown command: " + op);
103        }
104    }
105
106    private Intent makeIntent() throws URISyntaxException {
107        Intent intent = new Intent();
108        boolean hasIntentInfo = false;
109
110        mDebugOption = false;
111        mWaitOption = false;
112        Uri data = null;
113        String type = null;
114
115        String opt;
116        while ((opt=nextOption()) != null) {
117            if (opt.equals("-a")) {
118                intent.setAction(nextArgRequired());
119                hasIntentInfo = true;
120            } else if (opt.equals("-d")) {
121                data = Uri.parse(nextArgRequired());
122                hasIntentInfo = true;
123            } else if (opt.equals("-t")) {
124                type = nextArgRequired();
125                hasIntentInfo = true;
126            } else if (opt.equals("-c")) {
127                intent.addCategory(nextArgRequired());
128                hasIntentInfo = true;
129            } else if (opt.equals("-e") || opt.equals("--es")) {
130                String key = nextArgRequired();
131                String value = nextArgRequired();
132                intent.putExtra(key, value);
133                hasIntentInfo = true;
134            } else if (opt.equals("--esn")) {
135                String key = nextArgRequired();
136                intent.putExtra(key, (String) null);
137                hasIntentInfo = true;
138            } else if (opt.equals("--ei")) {
139                String key = nextArgRequired();
140                String value = nextArgRequired();
141                intent.putExtra(key, Integer.valueOf(value));
142                hasIntentInfo = true;
143            } else if (opt.equals("--ez")) {
144                String key = nextArgRequired();
145                String value = nextArgRequired();
146                intent.putExtra(key, Boolean.valueOf(value));
147                hasIntentInfo = true;
148            } else if (opt.equals("-n")) {
149                String str = nextArgRequired();
150                ComponentName cn = ComponentName.unflattenFromString(str);
151                if (cn == null) throw new IllegalArgumentException("Bad component name: " + str);
152                intent.setComponent(cn);
153                hasIntentInfo = true;
154            } else if (opt.equals("-f")) {
155                String str = nextArgRequired();
156                intent.setFlags(Integer.decode(str).intValue());
157            } else if (opt.equals("--grant-read-uri-permission")) {
158                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
159            } else if (opt.equals("--grant-write-uri-permission")) {
160                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
161            } else if (opt.equals("--debug-log-resolution")) {
162                intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
163            } else if (opt.equals("--activity-brought-to-front")) {
164                intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
165            } else if (opt.equals("--activity-clear-top")) {
166                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
167            } else if (opt.equals("--activity-clear-when-task-reset")) {
168                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
169            } else if (opt.equals("--activity-exclude-from-recents")) {
170                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
171            } else if (opt.equals("--activity-launched-from-history")) {
172                intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
173            } else if (opt.equals("--activity-multiple-task")) {
174                intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
175            } else if (opt.equals("--activity-no-animation")) {
176                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
177            } else if (opt.equals("--activity-no-history")) {
178                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
179            } else if (opt.equals("--activity-no-user-action")) {
180                intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
181            } else if (opt.equals("--activity-previous-is-top")) {
182                intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
183            } else if (opt.equals("--activity-reorder-to-front")) {
184                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
185            } else if (opt.equals("--activity-reset-task-if-needed")) {
186                intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
187            } else if (opt.equals("--activity-single-top")) {
188                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
189            } else if (opt.equals("--receiver-registered-only")) {
190                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
191            } else if (opt.equals("--receiver-replace-pending")) {
192                intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
193            } else if (opt.equals("-D")) {
194                mDebugOption = true;
195            } else if (opt.equals("-W")) {
196                mWaitOption = true;
197            } else {
198                System.err.println("Error: Unknown option: " + opt);
199                showUsage();
200                return null;
201            }
202        }
203        intent.setDataAndType(data, type);
204
205        String uri = nextArg();
206        if (uri != null) {
207            Intent oldIntent = intent;
208            intent = Intent.parseUri(uri, 0);
209            if (oldIntent.getAction() != null) {
210                intent.setAction(oldIntent.getAction());
211            }
212            if (oldIntent.getData() != null || oldIntent.getType() != null) {
213                intent.setDataAndType(oldIntent.getData(), oldIntent.getType());
214            }
215            Set cats = oldIntent.getCategories();
216            if (cats != null) {
217                Iterator it = cats.iterator();
218                while (it.hasNext()) {
219                    intent.addCategory((String)it.next());
220                }
221            }
222            hasIntentInfo = true;
223        }
224
225        if (!hasIntentInfo) throw new IllegalArgumentException("No intent supplied");
226        return intent;
227    }
228
229    private void runStartService() throws Exception {
230        Intent intent = makeIntent();
231        System.out.println("Starting service: " + intent);
232        ComponentName cn = mAm.startService(null, intent, intent.getType());
233        if (cn == null) {
234            System.err.println("Error: Not found; no service started.");
235        }
236    }
237
238    private void runStart() throws Exception {
239        Intent intent = makeIntent();
240        System.out.println("Starting: " + intent);
241        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
242        // XXX should do something to determine the MIME type.
243        IActivityManager.WaitResult result = null;
244        int res;
245        if (mWaitOption) {
246            result = mAm.startActivityAndWait(null, intent, intent.getType(),
247                        null, 0, null, null, 0, false, mDebugOption);
248            res = result.result;
249        } else {
250            res = mAm.startActivity(null, intent, intent.getType(),
251                    null, 0, null, null, 0, false, mDebugOption);
252        }
253        PrintStream out = mWaitOption ? System.out : System.err;
254        boolean launched = false;
255        switch (res) {
256            case IActivityManager.START_SUCCESS:
257                launched = true;
258                break;
259            case IActivityManager.START_SWITCHES_CANCELED:
260                launched = true;
261                out.println(
262                        "Warning: Activity not started because the "
263                        + " current activity is being kept for the user.");
264                break;
265            case IActivityManager.START_DELIVERED_TO_TOP:
266                launched = true;
267                out.println(
268                        "Warning: Activity not started, intent has "
269                        + "been delivered to currently running "
270                        + "top-most instance.");
271                break;
272            case IActivityManager.START_RETURN_INTENT_TO_CALLER:
273                launched = true;
274                out.println(
275                        "Warning: Activity not started because intent "
276                        + "should be handled by the caller");
277                break;
278            case IActivityManager.START_TASK_TO_FRONT:
279                launched = true;
280                out.println(
281                        "Warning: Activity not started, its current "
282                        + "task has been brought to the front");
283                break;
284            case IActivityManager.START_INTENT_NOT_RESOLVED:
285                out.println(
286                        "Error: Activity not started, unable to "
287                        + "resolve " + intent.toString());
288                break;
289            case IActivityManager.START_CLASS_NOT_FOUND:
290                out.println(NO_CLASS_ERROR_CODE);
291                out.println("Error: Activity class " +
292                        intent.getComponent().toShortString()
293                        + " does not exist.");
294                break;
295            case IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
296                out.println(
297                        "Error: Activity not started, you requested to "
298                        + "both forward and receive its result");
299                break;
300            case IActivityManager.START_PERMISSION_DENIED:
301                out.println(
302                        "Error: Activity not started, you do not "
303                        + "have permission to access it.");
304                break;
305            default:
306                out.println(
307                        "Error: Activity not started, unknown error code " + res);
308                break;
309        }
310        if (mWaitOption && launched) {
311            if (result == null) {
312                result = new IActivityManager.WaitResult();
313                result.who = intent.getComponent();
314            }
315            System.out.println("Status: " + (result.timeout ? "timeout" : "ok"));
316            if (result.who != null) {
317                System.out.println("Activity: " + result.who.flattenToShortString());
318            }
319            if (result.thisTime >= 0) {
320                System.out.println("ThisTime: " + result.thisTime);
321            }
322            if (result.totalTime >= 0) {
323                System.out.println("TotalTime: " + result.totalTime);
324            }
325            System.out.println("Complete");
326        }
327    }
328
329    private void sendBroadcast() throws Exception {
330        Intent intent = makeIntent();
331        IntentReceiver receiver = new IntentReceiver();
332        System.out.println("Broadcasting: " + intent);
333        mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, null, true, false);
334        receiver.waitForFinish();
335    }
336
337    private void runInstrument() throws Exception {
338        String profileFile = null;
339        boolean wait = false;
340        boolean rawMode = false;
341        boolean no_window_animation = false;
342        Bundle args = new Bundle();
343        String argKey = null, argValue = null;
344        IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
345
346        String opt;
347        while ((opt=nextOption()) != null) {
348            if (opt.equals("-p")) {
349                profileFile = nextArgRequired();
350            } else if (opt.equals("-w")) {
351                wait = true;
352            } else if (opt.equals("-r")) {
353                rawMode = true;
354            } else if (opt.equals("-e")) {
355                argKey = nextArgRequired();
356                argValue = nextArgRequired();
357                args.putString(argKey, argValue);
358            } else if (opt.equals("--no_window_animation")) {
359                no_window_animation = true;
360            } else {
361                System.err.println("Error: Unknown option: " + opt);
362                showUsage();
363                return;
364            }
365        }
366
367        String cnArg = nextArgRequired();
368        ComponentName cn = ComponentName.unflattenFromString(cnArg);
369        if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg);
370
371        InstrumentationWatcher watcher = null;
372        if (wait) {
373            watcher = new InstrumentationWatcher();
374            watcher.setRawOutput(rawMode);
375        }
376        float[] oldAnims = null;
377        if (no_window_animation) {
378            oldAnims = wm.getAnimationScales();
379            wm.setAnimationScale(0, 0.0f);
380            wm.setAnimationScale(1, 0.0f);
381        }
382
383        if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher)) {
384            throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString());
385        }
386
387        if (watcher != null) {
388            if (!watcher.waitForFinish()) {
389                System.out.println("INSTRUMENTATION_ABORTED: System has crashed.");
390            }
391        }
392
393        if (oldAnims != null) {
394            wm.setAnimationScales(oldAnims);
395        }
396    }
397
398    private void runProfile() throws Exception {
399        String profileFile = null;
400        boolean start = false;
401        String process = nextArgRequired();
402        ParcelFileDescriptor fd = null;
403
404        String cmd = nextArgRequired();
405        if ("start".equals(cmd)) {
406            start = true;
407            profileFile = nextArgRequired();
408            try {
409                fd = ParcelFileDescriptor.open(
410                        new File(profileFile),
411                        ParcelFileDescriptor.MODE_CREATE |
412                        ParcelFileDescriptor.MODE_TRUNCATE |
413                        ParcelFileDescriptor.MODE_READ_WRITE);
414            } catch (FileNotFoundException e) {
415                System.err.println("Error: Unable to open file: " + profileFile);
416                return;
417            }
418        } else if (!"stop".equals(cmd)) {
419            throw new IllegalArgumentException("Profile command " + cmd + " not valid");
420        }
421
422        if (!mAm.profileControl(process, start, profileFile, fd)) {
423            throw new AndroidException("PROFILE FAILED on process " + process);
424        }
425    }
426
427    private class IntentReceiver extends IIntentReceiver.Stub {
428        private boolean mFinished = false;
429
430        public synchronized void performReceive(
431                Intent intent, int rc, String data, Bundle ext, boolean ord,
432                boolean sticky) {
433            String line = "Broadcast completed: result=" + rc;
434            if (data != null) line = line + ", data=\"" + data + "\"";
435            if (ext != null) line = line + ", extras: " + ext;
436            System.out.println(line);
437            mFinished = true;
438            notifyAll();
439        }
440
441        public synchronized void waitForFinish() {
442            try {
443                while (!mFinished) wait();
444            } catch (InterruptedException e) {
445                throw new IllegalStateException(e);
446            }
447        }
448    }
449
450    private class InstrumentationWatcher extends IInstrumentationWatcher.Stub {
451        private boolean mFinished = false;
452        private boolean mRawMode = false;
453
454        /**
455         * Set or reset "raw mode".  In "raw mode", all bundles are dumped.  In "pretty mode",
456         * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that.
457         * @param rawMode true for raw mode, false for pretty mode.
458         */
459        public void setRawOutput(boolean rawMode) {
460            mRawMode = rawMode;
461        }
462
463        public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) {
464            synchronized (this) {
465                // pretty printer mode?
466                String pretty = null;
467                if (!mRawMode && results != null) {
468                    pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
469                }
470                if (pretty != null) {
471                    System.out.print(pretty);
472                } else {
473                    if (results != null) {
474                        for (String key : results.keySet()) {
475                            System.out.println(
476                                    "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key));
477                        }
478                    }
479                    System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode);
480                }
481                notifyAll();
482            }
483        }
484
485        public void instrumentationFinished(ComponentName name, int resultCode,
486                Bundle results) {
487            synchronized (this) {
488                // pretty printer mode?
489                String pretty = null;
490                if (!mRawMode && results != null) {
491                    pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
492                }
493                if (pretty != null) {
494                    System.out.println(pretty);
495                } else {
496                    if (results != null) {
497                        for (String key : results.keySet()) {
498                            System.out.println(
499                                    "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key));
500                        }
501                    }
502                    System.out.println("INSTRUMENTATION_CODE: " + resultCode);
503                }
504                mFinished = true;
505                notifyAll();
506            }
507        }
508
509        public boolean waitForFinish() {
510            synchronized (this) {
511                while (!mFinished) {
512                    try {
513                        if (!mAm.asBinder().pingBinder()) {
514                            return false;
515                        }
516                        wait(1000);
517                    } catch (InterruptedException e) {
518                        throw new IllegalStateException(e);
519                    }
520                }
521            }
522            return true;
523        }
524    }
525
526    private String nextOption() {
527        if (mCurArgData != null) {
528            String prev = mArgs[mNextArg - 1];
529            throw new IllegalArgumentException("No argument expected after \"" + prev + "\"");
530        }
531        if (mNextArg >= mArgs.length) {
532            return null;
533        }
534        String arg = mArgs[mNextArg];
535        if (!arg.startsWith("-")) {
536            return null;
537        }
538        mNextArg++;
539        if (arg.equals("--")) {
540            return null;
541        }
542        if (arg.length() > 1 && arg.charAt(1) != '-') {
543            if (arg.length() > 2) {
544                mCurArgData = arg.substring(2);
545                return arg.substring(0, 2);
546            } else {
547                mCurArgData = null;
548                return arg;
549            }
550        }
551        mCurArgData = null;
552        return arg;
553    }
554
555    private String nextArg() {
556        if (mCurArgData != null) {
557            String arg = mCurArgData;
558            mCurArgData = null;
559            return arg;
560        } else if (mNextArg < mArgs.length) {
561            return mArgs[mNextArg++];
562        } else {
563            return null;
564        }
565    }
566
567    private String nextArgRequired() {
568        String arg = nextArg();
569        if (arg == null) {
570            String prev = mArgs[mNextArg - 1];
571            throw new IllegalArgumentException("Argument expected after \"" + prev + "\"");
572        }
573        return arg;
574    }
575
576    private static void showUsage() {
577        System.err.println(
578                "usage: am [subcommand] [options]\n" +
579                "\n" +
580                "    start an Activity: am start [-D] [-W] <INTENT>\n" +
581                "        -D: enable debugging\n" +
582                "        -W: wait for launch to complete\n" +
583                "\n" +
584                "    start a Service: am startservice <INTENT>\n" +
585                "\n" +
586                "    send a broadcast Intent: am broadcast <INTENT>\n" +
587                "\n" +
588                "    start an Instrumentation: am instrument [flags] <COMPONENT>\n" +
589                "        -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)\n" +
590                "        -e <NAME> <VALUE>: set argument <NAME> to <VALUE>\n" +
591                "        -p <FILE>: write profiling data to <FILE>\n" +
592                "        -w: wait for instrumentation to finish before returning\n" +
593                "\n" +
594                "    start profiling: am profile <PROCESS> start <FILE>\n" +
595                "    stop profiling: am profile <PROCESS> stop\n" +
596                "\n" +
597                "    <INTENT> specifications include these flags:\n" +
598                "        [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]\n" +
599                "        [-c <CATEGORY> [-c <CATEGORY>] ...]\n" +
600                "        [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]\n" +
601                "        [--esn <EXTRA_KEY> ...]\n" +
602                "        [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]\n" +
603                "        [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]\n" +
604                "        [-n <COMPONENT>] [-f <FLAGS>]\n" +
605                "        [--grant-read-uri-permission] [--grant-write-uri-permission]\n" +
606                "        [--debug-log-resolution]\n" +
607                "        [--activity-brought-to-front] [--activity-clear-top]\n" +
608                "        [--activity-clear-when-task-reset] [--activity-exclude-from-recents]\n" +
609                "        [--activity-launched-from-history] [--activity-multiple-task]\n" +
610                "        [--activity-no-animation] [--activity-no-history]\n" +
611                "        [--activity-no-user-action] [--activity-previous-is-top]\n" +
612                "        [--activity-reorder-to-front] [--activity-reset-task-if-needed]\n" +
613                "        [--activity-single-top]\n" +
614                "        [--receiver-registered-only] [--receiver-replace-pending]\n" +
615                "        [<URI>]\n"
616                );
617    }
618}
619