Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

android - Send data back to the script which started the activity via adb shell am start

I want to install a diagnostic app from adb and get back data from it from within a bash script. I know how to start an activity from adb, but I can't find any way to get data back unless maybe if I print to logcat and parse the output, but that sounds like a hack. Is there a way to receive data back from an activity started using adb?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the data that you want to send back to your automation script could be serialized into a string less than 4k long - using logcat is a natural choice. Just make your activity to print the data to the log with Log.i("UNIQUE_TAG", the_data_string_you_want_to_send_back_to_your_script); and then use the following commands in your automation script to capture the output:

# 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)

In more recent Android versions (7.0+) where logcat properly supports -m <count>, -t <time> and -T <time> parameters you can use this much simpler version without having to clear the log with logcat -c first:

# 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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...