How can I detect when an Android application is running in the emulator?

前端 未结 30 2705
无人及你
无人及你 2020-11-22 16:42

I would like to have my code run slightly differently when running on the emulator than when running on a device. (For example, using 10.0.2.2 instead of a

30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 17:36

    Whichever code you use to do emulator detection, I'd highly recommend writing unit tests to cover all the Build.FINGERPRINT, Build.HARDWARE and Build.MANUFACTURER values that you are depending on. Here are some example tests:

    @Test
    public void testIsEmulatorGenymotion() throws Exception {
        assertThat(
                DeviceUtils.isRunningOnEmulator(
                        "generic/vbox86p/vbox86p:4.1.1/JRO03S/eng.buildbot.20150217.102902:userdebug/test-keys",
                        "vbox86", "Genymotion")).isTrue();
    
        assertThat(
                DeviceUtils.isRunningOnEmulator(
                        "generic/vbox86p/vbox86p:5.1/LMY47D/buildbot06092001:userdebug/test-keys", "vbox86",
                        "Genymotion")).isTrue();
    }
    
    @Test
    public void testIsEmulatorDefaultAndroidEmulator() throws Exception {
        assertThat(
                DeviceUtils.isRunningOnEmulator(
                        "generic_x86/sdk_google_phone_x86/generic_x86:5.0.2/LSY66H/1960483:eng/test-keys", "goldfish",
                        "unknown")).isTrue();
    
        assertThat(
                DeviceUtils.isRunningOnEmulator(
                        "Android/sdk_google_phone_x86_64/generic_x86_64:6.0/MASTER/2469028:userdebug/test-keys",
                        "ranchu", "unknown")).isTrue();
    }
    
    @Test
    public void testIsEmulatorRealNexus5() throws Exception {
        assertThat(
                DeviceUtils.isRunningOnEmulator("google/hammerhead/hammerhead:6.0.1/MMB29K/2419427:user/release-keys",
                        "hammerhead", "LGE")).isFalse();
    }
    

    ...and here's our code (debug logs and comments removed for conciseness):

    public static boolean isRunningOnEmulator() {
        if (sIsRunningEmulator == null) {
            sIsRunningEmulator = isRunningOnEmulator(Build.FINGERPRINT, Build.HARDWARE, Build.MANUFACTURER);
        }
    
        return sIsRunningEmulator;
    }
    
    static boolean isRunningOnEmulator(String fingerprint, String hardware, String manufacturer) {
        boolean isEmulatorFingerprint = fingerprint.endsWith("test-keys");
        boolean isEmulatorManufacturer = manufacturer.equals("Genymotion")
                || manufacturer.equals("unknown");
    
        if (isEmulatorFingerprint && isEmulatorManufacturer) {
            return true;
        } else {
            return false;
        }
    }
    

提交回复
热议问题