等待直到su中的命令完成 [英] Wait until a command in su finishes
问题描述
我正在Android中运行一个 su
进程,该进程本身在每次用户摇动手机时都会运行screencap实用程序(/system/bin/screencap
).
I am running a su
process in Android which itself runs the screencap utility (/system/bin/screencap
) every time the user shakes their phone.
我想等待每个屏幕截图完成,然后再允许用户通过摇动手机拍摄另一个屏幕截图.但是,使用 process.waitFor()
对我不起作用,因为我不想关闭 su
进程并为每个屏幕截图重新打开它(因为它会提示SuperUser应用的举杯,这会干扰屏幕截图)
I want to wait for each screencap to finish before I allow the user to take another screencap by shaking the phone. However, using process.waitFor()
doesn't work for me because I don't want to close the su
process and reopen it for each screencap (because it would prompt the SuperUser app's toast, which interferes with screencaps)
到目前为止,我有:
在服务的 onCreate()
中:
p = Runtime.getRuntime().exec("su");
os = p.getOutputStream();
在震动监听器处理程序中:
in the shake listener handler:
if (isReady) {
isReady = false;
String cmd = "/system/bin/screencap -p " + nextScreenshotFullPath + "\n";
os.write(cmd.getBytes("ASCII"));
os.flush();
[INSERT MAGIC HERE]
isReady = true;
Bitmap bm = BitmapFactory.decodeFile(nextScreenshotFullPath);
// Do something with bm
}
我正在寻找[INSERT MAGIC HERE]的地方-等待 screencap
完成的那段代码.
Where [INSERT MAGIC HERE] is what I'm looking for - the piece of code that would wait until screencap
finishes.
推荐答案
我找到了一种方法!我使用shell命令 echo -n 0
( -n
以防止换行)回显单个字符(例如 0
),然后读取回来了.在 screencap
命令完成并且 InputStream#read()
方法将阻塞之前,shell才会打印该字符,直到它可以读取该字符为止.代码说话:
I found a way! I echo a single character (say, 0
) using the shell command echo -n 0
(-n
to prevent a newline) and then reading it back. The shell won't print the character until after the screencap
command is finished and the InputStream#read()
method will block until it can read that character... or in code speak:
在服务的onCreate()中:
in service's onCreate():
p = Runtime.getRuntime().exec("su");
os = p.getOutputStream();
is = p.getInputStream(); // ADDED THIS LINE //
在震动监听器处理程序中:
in the shake listener handler:
if (isReady) {
isReady = false;
String cmd = "/system/bin/screencap -p " + nextScreenshotFullPath + "\n";
os.write(cmd.getBytes("ASCII"));
os.flush();
// ADDED LINES BELOW //
cmd = "echo -n 0\n";
os.write(cmd.getBytes("ASCII"));
os.flush();
is.read();
// ADDED LINES ABOVE //
isReady = true;
Bitmap bm = BitmapFactory.decodeFile(nextScreenshotFullPath);
// Do something with bm
}
这篇关于等待直到su中的命令完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!