×

[Android 学习笔记] 判断 Android 设备是否为模拟器

96
afluy
2017.08.17 19:15* 字数 72

源码

#include <cstddef>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>

typedef void(*FunType)(void);
void (*asmcheck)(void);

int detect() {
    int a = 0;
    char code[] =
        "\xF0\x41\x2D\xE9"
        "\x00\x70\xA0\xE3"
        "\x0F\x80\xA0\xE1"
        "\x00\x40\xA0\xE3"
        "\x01\x70\x87\xE2"
        "\x00\x50\x98\xE5"
        "\x01\x40\x84\xE2"
        "\x0F\x80\xA0\xE1"
        "\x0C\x80\x48\xE2"
        "\x00\x50\x88\xE5"
        "\x0A\x00\x54\xE3"
        "\x02\x00\x00\xAA"
        "\x0A\x00\x57\xE3"
        "\x00\x00\x00\xAA"
        "\xF6\xFF\xFF\xEA"
        "\x04\x00\xA0\xE1"
        "\xF0\x81\xBD\xE8";

    void *exec = mmap(NULL, (size_t) getpagesize(), PROT_EXEC | PROT_READ | PROT_WRITE , MAP_ANONYMOUS | MAP_SHARED, -1, (off_t) 0);
    memcpy(exec, code, sizeof(code) + 1);
    asmcheck = (FunType) exec;
    asmcheck();
    __asm __volatile (
    "mov %0,r0 \n"
    :"=r"(a)
    );
    munmap(exec, getpagesize());
    return a;
}

JNIEXPORT jint JNICALL Java_com_android_util_SimulatorChecker_check
  (JNIEnv *env, jobject object) {
    int isSim = detect();
    return (jint)isSim;
}

只有当 check 方法返回是 10, 判断设备为真机, 否则为模拟器.

Android.mk

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE    := simulator_checker
LOCAL_SRC_FILES := com_android_util_SimulatorChecker.cc
LOCAL_CPPFLAGS :=  -Os
# -fvisibility=hidden
LOCAL_CFLAGS :=  -Os
#-fvisibility=hidden
LOCAL_CFLAGS += -Wno-psabi
LOCAL_CFLAGS += -funwind-tables -g
LOCAL_CFLAGS := -funwind-tables -Wl,--no-merge-exidx-entries
#-fpermissive
LOCAL_LDLIBS += -llog -ldl -landroid
include $(BUILD_SHARED_LIBRARY)

Application.mk

APP_LOCAL_PATH :=$(call my-dir)
APP_ABI := armeabi-v7a armeabi
APP_STL := stlport_static
APP_STL := gnustl_static
APP_OPTIM := release
APP_CPPFLAGS += -Wno-error=format-security

参考资料:

Android学习笔记
Web note ad 1