简体   繁体   中英

Take a screenshot on Android

I'm trying to build a custom launcher for android that needs to take a screenshot of the device right after the user presses the home button and consequently right before my app (the launcher) goes back to the foreground. Pretty much the idea is to take a screenshot of whatever the device was showing right before my launcher/activity/app took over the screen.

I am aware that such a thing requires root access, but that's not a problem. Can anyone show me how to take screenshots? Some sample code? A tutorial online? I have looked online but couldn't find anything useful. I'm trying to simply take screenshots just like a gazillion apps on the Android Market already do with root access. Thanks in advance :-)

This is a security breach. You should have a rooted device in order to do it.

You can use this code with your own app: (I got this code from this answer to another question: https://stackoverflow.com/a/5651242/237838 )

// image naming and path  to include sd card  appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;   

// create bitmap screen capture
Bitmap bitmap;
View v1 = mCurrentUrlMask.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);

OutputStream fout = null;
imageFile = new File(mPath);

try {
   fout = new FileOutputStream(imageFile);
   bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
   fout.flush();
   fout.close();
} catch (FileNotFoundException e) {
   e.printStackTrace();
} catch (IOException e) {
   e.printStackTrace();
}

Try looking this code for additional help:

PS It's possible to take a screenshot from Android using DDMS, but this is another story.

PPS If you want to draw your launcher transparently over the activity below it you need to set pixel format to RGBA (only dealt with OpenGL) and render accordingly. You don't need to take a screenshot of the underlaying activity to do that.

Rooted device: use this code on the rooted device:

process = Runtime.getRuntime().exec("su -c cat /dev/graphics/fb0");
InputStream is = process.getInputStream();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM