通过adb shell am start将数据发送回启动活动的脚本

Mar*_*iro 12 bash android adb

我想adb从bash脚本中安装诊断应用程序并从中获取数据.我知道如何开始一个活动adb,但我找不到任何方法来获取数据,除非我打印logcat并解析输出,但这听起来像一个黑客.有没有办法从开始使用的活动中接收数据adb

Ale*_* P. 8

如果要发送回自动化脚本的数据可以序列化为长度小于4k的字符串 - 使用logcat是一种自然的选择.只需将您的活动打印到日志中Log.i("UNIQUE_TAG", the_data_string_you_want_to_send_back_to_your_script);,然后使用自动化脚本中的以下命令捕获输出:

# clear the logcat buffer
adb logcat -c

# start your activity
adb shell am start <INTENT>

# this line will block until a string with "UNIQUE_TAG" tag and "Info" priority
# is printed to the main log
adb shell 'logcat -b main -v raw -s UNIQUE_TAG:I | (read -n 1 && kill -2 $((BASHPID-1)))'

# now you can capture the data and process it
DATA=$(adb logcat -d -b main -v raw -s UNIQUE_TAG:I)
Run Code Online (Sandbox Code Playgroud)

在最近的Android版本(7.0+),其中logcat正确的支持-m <count>,-t <time>并且-T <time>参数可以使用这个简单得多的版本,而不必清除日志,logcat -c第一:

# instead of clearing the log just get the current timestamp
TS=$(adb shell 'echo $EPOCHREALTIME; log ""')

# start your activity
adb shell am start <INTENT>

# this command will return immediately if the data has been printed already or block if not
DATA=$(adb shell "logcat -b main -T $TS -m 1 -v raw -s UNIQUE_TAG:I")
Run Code Online (Sandbox Code Playgroud)