Am.java revision 9f4af53561daae8ffe77157068d67ab10d9e2a4d
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.net.URISyntaxException;
39import java.util.Iterator;
40import java.util.Set;
41
42public class Am {
43
44    private IActivityManager mAm;
45    private String[] mArgs;
46    private int mNextArg;
47    private String mCurArgData;
48
49    private boolean mDebugOption = false;
50
51    // These are magic strings understood by the Eclipse plugin.
52    private static final String FATAL_ERROR_CODE = "Error type 1";
53    private static final String NO_SYSTEM_ERROR_CODE = "Error type 2";
54    private static final String NO_CLASS_ERROR_CODE = "Error type 3";
55
56    /**
57     * Command-line entry point.
58     *
59     * @param args The command-line arguments
60     */
61    public static void main(String[] args) {
62        try {
63            (new Am()).run(args);
64        } catch (IllegalArgumentException e) {
65            showUsage();
66            System.err.println("Error: " + e.getMessage());
67        } catch (Exception e) {
68            System.err.println(e.toString());
69            System.exit(1);
70        }
71    }
72
73    private void run(String[] args) throws Exception {
74        if (args.length < 1) {
75            showUsage();
76            return;
77        }
78
79        mAm = ActivityManagerNative.getDefault();
80        if (mAm == null) {
81            System.err.println(NO_SYSTEM_ERROR_CODE);
82            throw new AndroidException("Can't connect to activity manager; is the system running?");
83        }
84
85        mArgs = args;
86        String op = args[0];
87        mNextArg = 1;
88
89        if (op.equals("start")) {
90            runStart();
91        } else if (op.equals("instrument")) {
92            runInstrument();
93        } else if (op.equals("broadcast")) {
94            sendBroadcast();
95        } else if (op.equals("profile")) {
96            runProfile();
97        } else {
98            throw new IllegalArgumentException("Unknown command: " + op);
99        }
100    }
101
102    private Intent makeIntent() throws URISyntaxException {
103        Intent intent = new Intent();
104        boolean hasIntentInfo = false;
105
106        mDebugOption = false;
107        Uri data = null;
108        String type = null;
109
110        String opt;
111        while ((opt=nextOption()) != null) {
112            if (opt.equals("-a")) {
113                intent.setAction(nextArgRequired());
114                hasIntentInfo = true;
115            } else if (opt.equals("-d")) {
116                data = Uri.parse(nextArgRequired());
117                hasIntentInfo = true;
118            } else if (opt.equals("-t")) {
119                type = nextArgRequired();
120                hasIntentInfo = true;
121            } else if (opt.equals("-c")) {
122                intent.addCategory(nextArgRequired());
123                hasIntentInfo = true;
124            } else if (opt.equals("-e") || opt.equals("--es")) {
125                String key = nextArgRequired();
126                String value = nextArgRequired();
127                intent.putExtra(key, value);
128                hasIntentInfo = true;
129            } else if (opt.equals("--ei")) {
130                String key = nextArgRequired();
131                String value = nextArgRequired();
132                intent.putExtra(key, Integer.valueOf(value));
133                hasIntentInfo = true;
134            } else if (opt.equals("--ez")) {
135                String key = nextArgRequired();
136                String value = nextArgRequired();
137                intent.putExtra(key, Boolean.valueOf(value));
138                hasIntentInfo = true;
139            } else if (opt.equals("-n")) {
140                String str = nextArgRequired();
141                ComponentName cn = ComponentName.unflattenFromString(str);
142                if (cn == null) throw new IllegalArgumentException("Bad component name: " + str);
143                intent.setComponent(cn);
144                hasIntentInfo = true;
145            } else if (opt.equals("-f")) {
146                String str = nextArgRequired();
147                intent.setFlags(Integer.decode(str).intValue());
148            } else if (opt.equals("-D")) {
149                mDebugOption = true;
150            } else {
151                System.err.println("Error: Unknown option: " + opt);
152                showUsage();
153                return null;
154            }
155        }
156        intent.setDataAndType(data, type);
157
158        String uri = nextArg();
159        if (uri != null) {
160            Intent oldIntent = intent;
161            intent = Intent.getIntent(uri);
162            if (oldIntent.getAction() != null) {
163                intent.setAction(oldIntent.getAction());
164            }
165            if (oldIntent.getData() != null || oldIntent.getType() != null) {
166                intent.setDataAndType(oldIntent.getData(), oldIntent.getType());
167            }
168            Set cats = oldIntent.getCategories();
169            if (cats != null) {
170                Iterator it = cats.iterator();
171                while (it.hasNext()) {
172                    intent.addCategory((String)it.next());
173                }
174            }
175            hasIntentInfo = true;
176        }
177
178        if (!hasIntentInfo) throw new IllegalArgumentException("No intent supplied");
179        return intent;
180    }
181
182    private void runStart() throws Exception {
183        Intent intent = makeIntent();
184        System.out.println("Starting: " + intent);
185        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
186        // XXX should do something to determine the MIME type.
187        int res = mAm.startActivity(null, intent, intent.getType(),
188                null, 0, null, null, 0, false, mDebugOption);
189        switch (res) {
190            case IActivityManager.START_SUCCESS:
191                break;
192            case IActivityManager.START_SWITCHES_CANCELED:
193                System.err.println(
194                        "Warning: Activity not started because the "
195                        + " current activity is being kept for the user.");
196                break;
197            case IActivityManager.START_DELIVERED_TO_TOP:
198                System.err.println(
199                        "Warning: Activity not started, intent has "
200                        + "been delivered to currently running "
201                        + "top-most instance.");
202                break;
203            case IActivityManager.START_RETURN_INTENT_TO_CALLER:
204                System.err.println(
205                        "Warning: Activity not started because intent "
206                        + "should be handled by the caller");
207                break;
208            case IActivityManager.START_TASK_TO_FRONT:
209                System.err.println(
210                        "Warning: Activity not started, its current "
211                        + "task has been brought to the front");
212                break;
213            case IActivityManager.START_INTENT_NOT_RESOLVED:
214                System.err.println(
215                        "Error: Activity not started, unable to "
216                        + "resolve " + intent.toString());
217                break;
218            case IActivityManager.START_CLASS_NOT_FOUND:
219                System.err.println(NO_CLASS_ERROR_CODE);
220                System.err.println("Error: Activity class " +
221                        intent.getComponent().toShortString()
222                        + " does not exist.");
223                break;
224            case IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
225                System.err.println(
226                        "Error: Activity not started, you requested to "
227                        + "both forward and receive its result");
228                break;
229            case IActivityManager.START_PERMISSION_DENIED:
230                System.err.println(
231                        "Error: Activity not started, you do not "
232                        + "have permission to access it.");
233                break;
234            default:
235                System.err.println(
236                        "Error: Activity not started, unknown error code " + res);
237                break;
238        }
239    }
240
241    private void sendBroadcast() throws Exception {
242        Intent intent = makeIntent();
243        IntentReceiver receiver = new IntentReceiver();
244        System.out.println("Broadcasting: " + intent);
245        mAm.broadcastIntent(null, intent, null, receiver, 0, null, null, null, true, false);
246        receiver.waitForFinish();
247    }
248
249    private void runInstrument() throws Exception {
250        String profileFile = null;
251        boolean wait = false;
252        boolean rawMode = false;
253        boolean no_window_animation = false;
254        Bundle args = new Bundle();
255        String argKey = null, argValue = null;
256        IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
257
258        String opt;
259        while ((opt=nextOption()) != null) {
260            if (opt.equals("-p")) {
261                profileFile = nextArgRequired();
262            } else if (opt.equals("-w")) {
263                wait = true;
264            } else if (opt.equals("-r")) {
265                rawMode = true;
266            } else if (opt.equals("-e")) {
267                argKey = nextArgRequired();
268                argValue = nextArgRequired();
269                args.putString(argKey, argValue);
270            } else if (opt.equals("--no_window_animation")) {
271                no_window_animation = true;
272            } else {
273                System.err.println("Error: Unknown option: " + opt);
274                showUsage();
275                return;
276            }
277        }
278
279        String cnArg = nextArgRequired();
280        ComponentName cn = ComponentName.unflattenFromString(cnArg);
281        if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg);
282
283        InstrumentationWatcher watcher = null;
284        if (wait) {
285            watcher = new InstrumentationWatcher();
286            watcher.setRawOutput(rawMode);
287        }
288        float[] oldAnims = null;
289        if (no_window_animation) {
290            oldAnims = wm.getAnimationScales();
291            wm.setAnimationScale(0, 0.0f);
292            wm.setAnimationScale(1, 0.0f);
293        }
294
295        if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher)) {
296            throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString());
297        }
298
299        if (watcher != null) {
300            if (!watcher.waitForFinish()) {
301                System.out.println("INSTRUMENTATION_ABORTED: System has crashed.");
302            }
303        }
304
305        if (oldAnims != null) {
306            wm.setAnimationScales(oldAnims);
307        }
308    }
309
310    private void runProfile() throws Exception {
311        String profileFile = null;
312        boolean start = false;
313        String process = nextArgRequired();
314        ParcelFileDescriptor fd = null;
315
316        String cmd = nextArgRequired();
317        if ("start".equals(cmd)) {
318            start = true;
319            profileFile = nextArgRequired();
320            try {
321                fd = ParcelFileDescriptor.open(
322                        new File(profileFile),
323                        ParcelFileDescriptor.MODE_CREATE |
324                        ParcelFileDescriptor.MODE_TRUNCATE |
325                        ParcelFileDescriptor.MODE_READ_WRITE);
326            } catch (FileNotFoundException e) {
327                System.err.println("Error: Unable to open file: " + profileFile);
328                return;
329            }
330        } else if (!"stop".equals(cmd)) {
331            throw new IllegalArgumentException("Profile command " + cmd + " not valid");
332        }
333
334        if (!mAm.profileControl(process, start, profileFile, fd)) {
335            throw new AndroidException("PROFILE FAILED on process " + process);
336        }
337    }
338
339    private class IntentReceiver extends IIntentReceiver.Stub {
340        private boolean mFinished = false;
341
342        public synchronized void performReceive(
343                Intent intent, int rc, String data, Bundle ext, boolean ord) {
344            String line = "Broadcast completed: result=" + rc;
345            if (data != null) line = line + ", data=\"" + data + "\"";
346            if (ext != null) line = line + ", extras: " + ext;
347            System.out.println(line);
348            mFinished = true;
349            notifyAll();
350        }
351
352        public synchronized void waitForFinish() {
353            try {
354                while (!mFinished) wait();
355            } catch (InterruptedException e) {
356                throw new IllegalStateException(e);
357            }
358        }
359    }
360
361    private class InstrumentationWatcher extends IInstrumentationWatcher.Stub {
362        private boolean mFinished = false;
363        private boolean mRawMode = false;
364
365        /**
366         * Set or reset "raw mode".  In "raw mode", all bundles are dumped.  In "pretty mode",
367         * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that.
368         * @param rawMode true for raw mode, false for pretty mode.
369         */
370        public void setRawOutput(boolean rawMode) {
371            mRawMode = rawMode;
372        }
373
374        public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) {
375            synchronized (this) {
376                // pretty printer mode?
377                String pretty = null;
378                if (!mRawMode && results != null) {
379                    pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
380                }
381                if (pretty != null) {
382                    System.out.print(pretty);
383                } else {
384                    if (results != null) {
385                        for (String key : results.keySet()) {
386                            System.out.println(
387                                    "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key));
388                        }
389                    }
390                    System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode);
391                }
392                notifyAll();
393            }
394        }
395
396        public void instrumentationFinished(ComponentName name, int resultCode,
397                Bundle results) {
398            synchronized (this) {
399                // pretty printer mode?
400                String pretty = null;
401                if (!mRawMode && results != null) {
402                    pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT);
403                }
404                if (pretty != null) {
405                    System.out.println(pretty);
406                } else {
407                    if (results != null) {
408                        for (String key : results.keySet()) {
409                            System.out.println(
410                                    "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key));
411                        }
412                    }
413                    System.out.println("INSTRUMENTATION_CODE: " + resultCode);
414                }
415                mFinished = true;
416                notifyAll();
417            }
418        }
419
420        public boolean waitForFinish() {
421            synchronized (this) {
422                while (!mFinished) {
423                    try {
424                        if (!mAm.asBinder().pingBinder()) {
425                            return false;
426                        }
427                        wait(1000);
428                    } catch (InterruptedException e) {
429                        throw new IllegalStateException(e);
430                    }
431                }
432            }
433            return true;
434        }
435    }
436
437    private String nextOption() {
438        if (mCurArgData != null) {
439            String prev = mArgs[mNextArg - 1];
440            throw new IllegalArgumentException("No argument expected after \"" + prev + "\"");
441        }
442        if (mNextArg >= mArgs.length) {
443            return null;
444        }
445        String arg = mArgs[mNextArg];
446        if (!arg.startsWith("-")) {
447            return null;
448        }
449        mNextArg++;
450        if (arg.equals("--")) {
451            return null;
452        }
453        if (arg.length() > 1 && arg.charAt(1) != '-') {
454            if (arg.length() > 2) {
455                mCurArgData = arg.substring(2);
456                return arg.substring(0, 2);
457            } else {
458                mCurArgData = null;
459                return arg;
460            }
461        }
462        mCurArgData = null;
463        return arg;
464    }
465
466    private String nextArg() {
467        if (mCurArgData != null) {
468            String arg = mCurArgData;
469            mCurArgData = null;
470            return arg;
471        } else if (mNextArg < mArgs.length) {
472            return mArgs[mNextArg++];
473        } else {
474            return null;
475        }
476    }
477
478    private String nextArgRequired() {
479        String arg = nextArg();
480        if (arg == null) {
481            String prev = mArgs[mNextArg - 1];
482            throw new IllegalArgumentException("Argument expected after \"" + prev + "\"");
483        }
484        return arg;
485    }
486
487    private static void showUsage() {
488        System.err.println(
489                "usage: am [subcommand] [options]\n" +
490                "\n" +
491                "    start an Activity: am start [-D] <INTENT>\n" +
492                "        -D: enable debugging\n" +
493                "\n" +
494                "    send a broadcast Intent: am broadcast <INTENT>\n" +
495                "\n" +
496                "    start an Instrumentation: am instrument [flags] <COMPONENT>\n" +
497                "        -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)\n" +
498                "        -e <NAME> <VALUE>: set argument <NAME> to <VALUE>\n" +
499                "        -p <FILE>: write profiling data to <FILE>\n" +
500                "        -w: wait for instrumentation to finish before returning\n" +
501                "\n" +
502                "    start profiling: am profile <PROCESS> start <FILE>\n" +
503                "    stop profiling: am profile <PROCESS> stop\n" +
504                "\n" +
505                "    <INTENT> specifications include these flags:\n" +
506                "        [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]\n" +
507                "        [-c <CATEGORY> [-c <CATEGORY>] ...]\n" +
508                "        [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]\n" +
509                "        [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]\n" +
510                "        [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]\n" +
511                "        [-n <COMPONENT>] [-f <FLAGS>] [<URI>]\n"
512                );
513    }
514}
515