关键约定:参数不能放在命令最后面,而要放在包名前面。
Activity与Service都是如此,放在最后不会被识别。
启动 Activity 并传参
用 am 命令启动 Activity 并传递参数,也可以作为 C 层与 Java 层传递数据的手段。
假设要启动的 App 包名为 net.yurushao.demo,目标 Activity 为 ExampleActivity,传递两个参数:
pid:整型,值10str:字符串"hello, world"
adb 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,字符串 |
--ez | extra boolean,布尔值 |
--el | extra long,长整型 |
更多类型可用 am -h 查看帮助。
在 ExampleActivity 的 onCreate 中取值:
Intent intent = getIntent();
int pid = intent.getIntExtra("pid", -1); // 第二个参数为默认值
String str = intent.getStringExtra("str");
同时在 AndroidManifest.xml 中该 Activity 的标签下声明接收 android.intent.action.MAIN。
启动 Service
adb shell am startservice com.example.serviceoftestethernet/com.example.lxm.Myservice
adb shell am startservice --user 0 -n com.example.serviceoftestethernet/com.example.lxm.Myservice
带参数启动(参数在包名之前):
adb shell am startservice --es cmd "startService" --ei inttest 10 \
com.example.serviceoftestethernet/com.example.lxm.Myservice
发送广播
adb shell am broadcast -a com.android.vending.INSTALL_REFERRER \
-n "com.zqgames.luxuryclub/com.appsflyer.SingleInstallBroadcastReceiver" \
--es referrer "utm_source=google-play&utm_medium=cpc"