The sample code is as follows:
Frameworks \ base \ services \ surfaceflinger \ tests \ screencap. cpp
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License ");
* You may not use this file before t in compliance with the License.
* You may obtain a copy of the License
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* Distributed under the License is distributed on an "as is" BASIS,
* Without warranties or conditions of any kind, either express or implied.
* See the License for the specific language governing permissions and
* Limitations under the License.
*/
# Include <utils/Log. h>
# Include <binder/IPCThreadState. h>
# Include <binder/ProcessState. h>
# Include <binder/IServiceManager. h>
# Include <binder/IMemory. h>
# Include <surfaceflinger/ISurfaceComposer. h>
# Include <SkImageEncoder. h>
# Include <SkBitmap. h>
Using namespace android;
Int main (int argc, char ** argv)
{
If (argc! = 2 ){
Printf ("usage: % s path \ n", argv [0]);
Exit (0 );
}
Const String16 name ("SurfaceFlinger ");
Sp <ISurfaceComposer> composer;
GetService (name, & composer );
Sp <IMemoryHeap> heap;
Uint32_t w, h;
PixelFormat f;
Status_t err = composer-> captureScreen (0, & heap, & w, & h, & f, 0, 0 );
If (err! = NO_ERROR ){
Fprintf (stderr, "screen capture failed: % s \ n", strerror (-err ));
Exit (0 );
}
Printf ("screen capture success: w = % u, h = % u, pixels = % p \ n ",
W, h, heap-> getBase ());
Printf ("saving file as PNG in % s... \ n", argv [1]);
SkBitmap B;
B. setConfig (SkBitmap: kARGB_8888_Config, w, h );
B. setPixels (heap-> getBase ());
SkImageEncoder: EncodeFile (argv [1], B,
SkImageEncoder: kPNG_Type, SkImageEncoder: kDefaultQuality );
Return 0;
}
Compile and generate/system/bin/test-screencap
Enter test-screencap/mnt/sdcard/scapxx.png
You can see scapxx.png. The default size is the screen resolution.
If you want to write this function to your own application
Write a JNI file. Refer to the code above, but remember the permission statement.
<Span style = "font-size: 24px;"> <uses-permission android: name = "android. permission. READ_FRAME_BUFFER"/> </span>
Of course, it is best to implement it at the system level and respond to a combination of keys for screenshots, such as Android4.0.
Author zmyde2010