1

I am using these codes to run a screencap feature on my android app, it is able to capture the screencap and convert it into a bitmap to be used, however after running it a few times. the app becomes slower and I have no idea why

Is it caused by these codes running continuous and leaving processes in the memory? And if so how do I properly close them?

Process process = Runtime.getRuntime().exec("su");
OutputStreamWriter outputStream = new OutputStreamWriter(process.getOutputStream());
outputStream.write("/system/bin/screencap -p\n");
outputStream.flush();
Bitmap screen = BitmapFactory.decodeStream(process.getInputStream());
outputStream.write("exit\n");
outputStream.flush();
outputStream.close();
LuxuryWaffles
  • 1,518
  • 4
  • 27
  • 50
  • Any reason you're not doing something like this? http://stackoverflow.com/a/5651242/608347 – Scott Tomaszewski Mar 23 '16 at 03:41
  • 2
    You should terminate the processes when you're done with them. `process.destroy();`. This will close any streams associated with them, as well. – Mike M. Mar 23 '16 at 03:42

1 Answers1

0

If you are using jdk 7 you can use the try-with-resources approach:

Process process = Runtime.getRuntime().exec("su");
try (OutputStream out = process.getOutputStream();
     InputStream in = process.getInputStream()) {
    OutputStreamWriter outputStream = new OutputStreamWriter(out);
    outputStream.write("/system/bin/screencap -p\n");
    outputStream.flush();
    outputStream.write("exit\n");
    Bitmap screen = BitmapFactory.decodeStream(in);
}

By putting the InputStream and OutputStream in the try block's parentheses, both streams will automatically be closed at the end of the try block.

Alternatively you can use the Google Guava library (which is awesome, btw). I can post that code if you need it, but its on their site here (https://github.com/google/guava/wiki/ClosingResourcesExplained)

Scott Tomaszewski
  • 1,009
  • 8
  • 27