5

我在 Android 中运行一个进程,每次用户摇晃手机时su,它本身都会运行 screencap 实用程序 ( )。/system/bin/screencap

我想等待每个屏幕截图完成,然后我才允许用户通过摇晃手机来获取另一个屏幕截图。但是,使用process.waitFor()对我不起作用,因为我不想关闭su进程并为每个屏幕截图重新打开它(因为它会提示 SuperUser 应用程序的 toast,这会干扰屏幕截图)

到目前为止,我有:

在服务中onCreate()

p = Runtime.getRuntime().exec("su");
os = p.getOutputStream();

在摇动侦听器处理程序中:

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完成的一段代码。

4

2 回答 2

3

我找到了一个方法!0我使用 shell 命令echo -n 0(以防止换行)回显单个字符(例如, ) -n,然后将其读回。screencap在命令完成之前,shell 不会打印字符,并且该InputStream#read()方法将阻塞,直到它可以读取该字符......或者在代码中说话:

在服务的 onCreate() 中:

p = Runtime.getRuntime().exec("su");
os = p.getOutputStream();
is = p.getInputStream(); // ADDED THIS LINE //

在摇动侦听器处理程序中:

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
}
于 2013-04-23T04:10:08.120 回答
0

为什么不循环直到文件大小不变?您已经在分叉命令行进程:)

如果你只想要一个屏幕截图,你可以通过编程来做到这一点:

//Get a screenshot of the screen
private Bitmap getScreenShot()
{
    View v = findViewById(R.id.your_top_level_layout_or_view);

    //Save the bitmap
    v.setDrawingCacheEnabled(true);
    Bitmap screenShot = v.getDrawingCache();
    Bitmap nonRecyclableScreenShot = screenShot.copy(screenShot.getConfig(), false);

    //Restore everything we changed to get the screenshot
    v.setDrawingCacheEnabled(false);

    return nonRecyclableScreenShot;
}
于 2013-04-16T23:14:33.230 回答