android后台截屏实现(2)--screencap源码修改

时间:2021-08-28 10:44:21

首先找到screencap类在Android源码中的位置,/442/frameworks/base/cmds/screencap/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 except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h> #include <linux/fb.h>
#include <sys/ioctl.h>
#include <sys/mman.h> #include <binder/ProcessState.h> #include <gui/SurfaceComposerClient.h>
#include <gui/ISurfaceComposer.h> #include <ui/PixelFormat.h> #include <SkImageEncoder.h>
#include <SkBitmap.h>
#include <SkData.h>
#include <SkStream.h> using namespace android; static uint32_t DEFAULT_DISPLAY_ID = ISurfaceComposer::eDisplayIdMain; static void usage(const char* pname)
{
fprintf(stderr,
"usage: %s [-hp] [-d display-id] [FILENAME]\n"
" -h: this message\n"
" -p: save the file as a png.\n"
" -d: specify the display id to capture, default %d.\n"
"If FILENAME ends with .png it will be saved as a png.\n"
"If FILENAME is not given, the results will be printed to stdout.\n",
pname, DEFAULT_DISPLAY_ID
);
} static SkBitmap::Config flinger2skia(PixelFormat f)
{
switch (f) {
case PIXEL_FORMAT_RGB_565:
return SkBitmap::kRGB_565_Config;
default:
return SkBitmap::kARGB_8888_Config;
}
} static status_t vinfoToPixelFormat(const fb_var_screeninfo& vinfo,
uint32_t* bytespp, uint32_t* f)
{ switch (vinfo.bits_per_pixel) {
case :
*f = PIXEL_FORMAT_RGB_565;
*bytespp = ;
break;
case :
*f = PIXEL_FORMAT_RGB_888;
*bytespp = ;
break;
case :
// TODO: do better decoding of vinfo here
*f = PIXEL_FORMAT_RGBX_8888;
*bytespp = ;
break;
default:
return BAD_VALUE;
}
return NO_ERROR;
} int main(int argc, char** argv)
{
ProcessState::self()->startThreadPool(); const char* pname = argv[];
bool png = false;
int32_t displayId = DEFAULT_DISPLAY_ID;
int c;
while ((c = getopt(argc, argv, "phd:")) != -) {
switch (c) {
case 'p':
png = true;
break;
case 'd':
displayId = atoi(optarg);
break;
case '?':
case 'h':
usage(pname);
return ;
}
}
argc -= optind;
argv += optind; int fd = -;
if (argc == ) {
fd = dup(STDOUT_FILENO);
} else if (argc == ) {
const char* fn = argv[];
fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, );
if (fd == -) {
fprintf(stderr, "Error opening file: %s (%s)\n", fn, strerror(errno));
return ;
}
const int len = strlen(fn);
if (len >= && == strcmp(fn+len-, ".png")) {
png = true;
}
} if (fd == -) {
usage(pname);
return ;
} void const* mapbase = MAP_FAILED;
ssize_t mapsize = -; void const* base = ;
uint32_t w, s, h, f;
size_t size = ; ScreenshotClient screenshot;
sp<IBinder> display = SurfaceComposerClient::getBuiltInDisplay(displayId);
if (display != NULL && screenshot.update(display) == NO_ERROR) {
base = screenshot.getPixels();
w = screenshot.getWidth();
h = screenshot.getHeight();
s = screenshot.getStride();
f = screenshot.getFormat();
size = screenshot.getSize();
} else {
const char* fbpath = "/dev/graphics/fb0";
int fb = open(fbpath, O_RDONLY);
if (fb >= ) {
struct fb_var_screeninfo vinfo;
if (ioctl(fb, FBIOGET_VSCREENINFO, &vinfo) == ) {
uint32_t bytespp;
if (vinfoToPixelFormat(vinfo, &bytespp, &f) == NO_ERROR) {
size_t offset = (vinfo.xoffset + vinfo.yoffset*vinfo.xres) * bytespp;
w = vinfo.xres;
h = vinfo.yres;
s = vinfo.xres;
size = w*h*bytespp;
mapsize = offset + size;
mapbase = mmap(, mapsize, PROT_READ, MAP_PRIVATE, fb, );
if (mapbase != MAP_FAILED) {
base = (void const *)((char const *)mapbase + offset);
}
}
}
close(fb);
}
} if (base) {
if (png) {
SkBitmap b;
b.setConfig(flinger2skia(f), w, h, s*bytesPerPixel(f));
b.setPixels((void*)base);
SkDynamicMemoryWStream stream;
SkImageEncoder::EncodeStream(&stream, b,
SkImageEncoder::kPNG_Type, SkImageEncoder::kDefaultQuality);
SkData* streamData = stream.copyToData();
write(fd, streamData->data(), streamData->size());
streamData->unref();
} else {
write(fd, &w, );
write(fd, &h, );
write(fd, &f, );
size_t Bpp = bytesPerPixel(f);
for (size_t y= ; y<h ; y++) {
write(fd, base, w*Bpp);
base = (void *)((char *)base + s*Bpp);
}
}
}
close(fd);
if (mapbase != MAP_FAILED) {
munmap((void *)mapbase, mapsize);
}
return ;
}

由源码可以看出,screencap的入口main方法是从命令行获取参数,通过分析后执行相应的操作。我们要想在java层调用这个类,就要把它的入口改成native方法的接口,修改后的代码如下:

 #include <jni.h>
#include "com_android_servicescreencap_ScreenCap.h" #include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h> #include <linux/fb.h>
#include <sys/ioctl.h>
#include <sys/mman.h> #include <binder/ProcessState.h> #include <gui/SurfaceComposerClient.h>
#include <gui/ISurfaceComposer.h> #include <ui/PixelFormat.h> #include <SkImageEncoder.h>
#include <SkBitmap.h>
#include <SkData.h>
#include <SkStream.h> #include <android/log.h>
#define LOG_TAG "ServiceScreenCap"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) using namespace android; static uint32_t DEFAULT_DISPLAY_ID = ISurfaceComposer::eDisplayIdMain; static status_t vinfoToPixelFormat(const fb_var_screeninfo& vinfo,
uint32_t* bytespp, uint32_t* f)
{ switch (vinfo.bits_per_pixel) {
case :
*f = PIXEL_FORMAT_RGB_565;
*bytespp = ;
break;
case :
*f = PIXEL_FORMAT_RGB_888;
*bytespp = ;
break;
case :
// TODO: do better decoding of vinfo here
*f = PIXEL_FORMAT_RGBX_8888;
*bytespp = ;
break;
default:
return BAD_VALUE;
}
return NO_ERROR;
} static SkBitmap::Config flinger2skia(PixelFormat f)
{
switch (f) {
case PIXEL_FORMAT_RGB_565:
return SkBitmap::kRGB_565_Config;
default:
return SkBitmap::kARGB_8888_Config;
}
} /*
* Class: com_android_servicescreencap_ScreenCap
* Method: currentscreen
* Signature: (Ljava/lang/String;)I
*/
JNIEXPORT jint
JNICALL ScreenCap_currentscreen(JNIEnv *env,
jclass clazz, jstring jpath) { ProcessState::self()->startThreadPool(); int32_t displayId = DEFAULT_DISPLAY_ID; const char* fn = env->GetStringUTFChars(jpath,NULL);
LOGI("=====jpath:%s \n", fn); if (fn == NULL) {
LOGE("=====path = %s \n =====err: %s \n",fn, strerror(errno));
return ;
}
int fd = -;
fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, );
LOGI("=====after open ,fd:%d \n",fd);
if (fd == -) {
LOGE("=====err: %s \n", strerror(errno));
return ;
} void const* mapbase = MAP_FAILED;
ssize_t mapsize = -; void const* base = ;
uint32_t w, s, h, f;
size_t size = ; ScreenshotClient screenshot;
sp < IBinder > display = SurfaceComposerClient::getBuiltInDisplay(displayId);
if (display != NULL && screenshot.update(display) == NO_ERROR) {
base = screenshot.getPixels();
w = screenshot.getWidth();
h = screenshot.getHeight();
s = screenshot.getStride();
f = screenshot.getFormat();
size = screenshot.getSize();
} else {
const char* fbpath = "/dev/graphics/fb0";
int fb = open(fbpath, O_RDONLY);
LOGI("=====read framebuffer, fb:%d \n", fb);
if (fb >= ) {
struct fb_var_screeninfo vinfo;
if (ioctl(fb, FBIOGET_VSCREENINFO, &vinfo) == ) {
uint32_t bytespp;
if (vinfoToPixelFormat(vinfo, &bytespp, &f) == NO_ERROR) {
size_t offset = (vinfo.xoffset + vinfo.yoffset * vinfo.xres)
* bytespp;
w = vinfo.xres;
h = vinfo.yres;
s = vinfo.xres;
size = w * h * bytespp;
mapsize = offset + size;
mapbase = mmap(, mapsize, PROT_READ, MAP_PRIVATE, fb, );
if (mapbase != MAP_FAILED) {
base = (void const *) ((char const *) mapbase + offset);
}
}
}
close(fb);
}else{
LOGE("=====fb = %d , err: %s \n",fb, strerror(errno));
return ;
}
} if (base) {
SkBitmap b;
b.setConfig(flinger2skia(f), w, h, s * bytesPerPixel(f));
b.setPixels((void*) base);
SkDynamicMemoryWStream stream;
SkImageEncoder::EncodeStream(&stream, b, SkImageEncoder::kPNG_Type,
SkImageEncoder::kDefaultQuality);
SkData* streamData = stream.copyToData();
write(fd, streamData->data(), streamData->size());
streamData->unref();
}
close (fd);
if (mapbase != MAP_FAILED) {
munmap((void *) mapbase, mapsize);
}
return ;
} static JNINativeMethod methods[] = {
{"currentscreen","(Ljava/lang/String;)I",(void*)ScreenCap_currentscreen},
}; static int registerNativeMethods(JNIEnv* env,const char* classname,JNINativeMethod* gMethods,int numMethods ){
jclass clazz;
clazz = env->FindClass(classname);
if(clazz == NULL){
return JNI_FALSE;
}
if(env->RegisterNatives(clazz,gMethods,numMethods) < ){
return JNI_FALSE;
}
return JNI_TRUE;
} static int registerNatives(JNIEnv* env)
{
if (!registerNativeMethods(env, "com/android/servicescreencap/ScreenCap",
methods, sizeof(methods) / sizeof(methods[]))) {
return JNI_FALSE;
} return JNI_TRUE;
} typedef union {
JNIEnv* env;
void* venv;
} UnionJNIEnvToVoid; jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
UnionJNIEnvToVoid uenv;
uenv.venv = NULL;
jint result = -;
JNIEnv* env = NULL; if (vm->GetEnv(&uenv.venv, JNI_VERSION_1_6) != JNI_OK) {
return result;
}
env = uenv.env; if (registerNatives(env) != JNI_TRUE) {
return result;
} result = JNI_VERSION_1_6; return result;
}

修改后的代码入口是ScreenCap_currentscreen,该方法接收一个地址,将当前屏幕截取到该地址下。代码中加入了日志,可以打印native层的错误信息。


此处需采用动态方式注册本地方法,静态方式好像会有问题。

参考链接:

Android: How to Capture Screen in Gingerbread(2.3中实现截屏)

Android: How to Capture Screen in Gingerbread(2.3中实现截屏)(续)

Android系统截屏的实现(附代码)