Android 屏幕截图(底层实现方式)

时间:2022-09-05 15:22:31


加载底层库ScreenCap.java:

public class ScreenCap {

	static {
		System.loadLibrary("scrcap");
	}

	static native void captureScreenToFile(String fileName);
}

广播接收器:

 

public class ScreenCapReceiver extends BroadcastReceiver {

	private static final String LOG_TAG = "ScreenCapReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		// Temp code, should not in main thread
		Log.d(LOG_TAG, "generate file name");
                //Checking external storage
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			mExternalStorageWriteable = false;
		} else {
			mExternalStorageWriteable = false;
		}

		if (!mExternalStorageWriteable)
	            return;

		File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "SCRCAP_"+System.currentTimeMillis()+".png");

		Log.d(LOG_TAG, "Capture screen to : " + file.getAbsolutePath());
		
		ScreenCap.captureScreenToFile(file.getAbsolutePath());

		Log.d(LOG_TAG, "screen captured");
	}

}

 

ScreenCap.cpp:

#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>

#include "com_cust_android_screencap_ScreenCap.h"

using namespace android;
/*
 * Class:     com_cust_android_screencap_ScreenCap
 * Method:    captureScreenToFile
 * Signature: (Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_com_cust_android_screencap_ScreenCap_captureScreenToFile
  (JNIEnv *env, jclass clazz, jstring fileName) {

    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));
        return;
    }

    LOGD("screen capture success: w=%u, h=%u, pixels=%p\n",
            w, h, heap->getBase());

    SkBitmap b;
    b.setConfig(SkBitmap::kARGB_8888_Config, w, h);
    b.setPixels(heap->getBase());
    SkImageEncoder::EncodeFile(env->GetStringUTFChars(fileName, 0), b,
            SkImageEncoder::kPNG_Type, SkImageEncoder::kDefaultQuality);

}

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
    return JNI_VERSION_1_6;
}

JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) {

}


下载源码:http://download.csdn.net/detail/weiyirong/5836997