android am 启动activity service or broadcast及参数传递

android中启动activity、service或broadcast 的shell命令可通过adb shell am方式实现


关于am若查看其用法可在终端依次通过

sudo adb kill-server

sudo adb start-server

adb devices

adb shell

am


帮助信息结果如下:

$ am
usage: am [subcommand] [options]

    start an Activity: am start [-D] [-W] 
        -D: enable debugging
        -W: wait for launch to complete

    start a Service: am startservice 

    send a broadcast Intent: am broadcast 

    start an Instrumentation: am instrument [flags] 
        -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)
        -e  : set argument  to 
        -p : write profiling data to 
        -w: wait for instrumentation to finish before returning

    start profiling: am profile  start 
    stop profiling: am profile  stop

    start monitoring: am monitor [--gdb ]
        --gdb: start gdbserv on the given port at crash/ANR

     specifications include these flags:
        [-a ] [-d ] [-t ]
        [-c  [-c ] ...]
        [-e|--es   ...]
        [--esn  ...]
        [--ez   ...]
        [-e|--ei   ...]
        [-n ] [-f ]
        [--grant-read-uri-permission] [--grant-write-uri-permission]
        [--debug-log-resolution]
        [--activity-brought-to-front] [--activity-clear-top]
        [--activity-clear-when-task-reset] [--activity-exclude-from-recents]
        [--activity-launched-from-history] [--activity-multiple-task]
        [--activity-no-animation] [--activity-no-history]
        [--activity-no-user-action] [--activity-previous-is-top]
        [--activity-reorder-to-front] [--activity-reset-task-if-needed]
        [--activity-single-top]
        [--receiver-registered-only] [--receiver-replace-pending]
        []


1. 启动activity  adb shell am start -n /.


设置参数

COMMAND_START = "adb -s "+ deviceNum + " shell am start -n com.gps/com.compal.suspend.GPS -d "
					+ gpsOntime + "/" + gpsOfftime + "," + playCycle;


Runtime.getRuntime().exec(COMMAND_START)


activity获取参数

intentData = getIntent().getDataString();



2. 关于service / broadcast的启动可参考一篇比较好的博文:

   http://blog.csdn.net/androidbluetooth/article/details/7664319


3. 当然am的作用并不只是如上这些,从am帮助信息即可明白


4.启动并传递参数的方法:

法一:查看am的帮助信息中的部分-d

     


法二:可参考另一篇好的博文:

http://www.yurushao.net/?p=784


比如,我们要启动的Acitvity所在的app是net.yurushao.demo,需要启动的是其中的ExampleActivity,并给他传递两个参数:
1. pid 整数,值为10
2. str 字符串,”hello, world”

那么,完整的命令为(在Android Shell中执行):

am start -a android.intent.action.MAIN -n \
net.yurushao.demo/net.yurushao.demo.ExampleActivity \
 --ei pid 10 --es str "hello, world"

简单说明一下,–ei表示参数类型为整型(extra integer),–es表示参数的类型为字符串(extra string),然后它们后面分别跟一个键值对,标识参数名和具体值。需要其他类型可以参考开头提到的那篇文章或者使用 am -h 查看帮助。

在ExampleActivity中获取传递来的参数也非常简单,在onCreate回调函数中添加:


Intent intent = getIntent();
int pid = intent.getIntExtra("pid", -1); // 第二个参数为default value
String str = intent.getStringExtra("str");

然后在AndroidManifest.xml中表示ExampleActivity的标签下,添加并接受 android.intent.action.MAIN


    
        
    





你可能感兴趣的:(android)