I keep getting deprecated API warning even with co

2019-07-30 07:44发布

问题:

I'm working on a Android project, and at some point in my code I need to get the device serial number.

In order to get it I used to use Build.SERIAL which has been deprecated since Android O. To avoid problems I started using Build.getSerial(), and created a little method that wraps up the OS version check:

private static String getSerial() throws SecurityException {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) {
        return Build.SERIAL;
    }

    return Build.getSerial();
}

Note: I'm not checking for the permission READ_PHONE_STATE (required by the getSerial() method) to be granted because I'm doing it at the start and make sure I already have it before getting to this method.

The problem is that, no matter how I write down the Android OS check I keep getting the deprecated API warning.

I tried the following and for all possible versions I keep getting the warning on Build.SERIAL

private static String getSerial() throws SecurityException {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        return Build.getSerial();
    }
    return Build.SERIAL;
}

private static String getDeviceUDI() throws SecurityException {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        return Build.getSerial();
    } else {
        return Build.SERIAL;
    }
}

private static String getDeviceUDI() throws SecurityException {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) {
        return Build.SERIAL;
    } else {
        return Build.getSerial();
    }
}

回答1:

You need something like this:

@SuppressLint("HardwareIds")
@SuppressWarnings("deprecation")
private static String getSerial() throws SecurityException {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) {
        return Build.SERIAL;
    }
    return Build.getSerial();
}

to hide all the incorrect warnings