Android应用内结算 - 使用枚举

时间:2012-04-10 18:38:21

标签: android enums in-app-billing

在应用内结算的示例代码中,它使用

public enum ResponseCode {
    RESULT_OK,
    RESULT_USER_CANCELED,
    RESULT_SERVICE_UNAVAILABLE,
    RESULT_BILLING_UNAVAILABLE,
    RESULT_ITEM_UNAVAILABLE,
    RESULT_DEVELOPER_ERROR,
    RESULT_ERROR;

    // Converts from an ordinal value to the ResponseCode
    public static ResponseCode valueOf(int index) {
        ResponseCode[] values = ResponseCode.values();
        if (index < 0 || index >= values.length) {
            return RESULT_ERROR;
        }
        return values[index];
    }
}

 int responseCode = response.getInt(Consts.BILLING_RESPONSE_RESPONSE_CODE);
 boolean billingSupported = (responseCode == ResponseCode.RESULT_OK.ordinal());
对我来说,在这里使用枚举似乎很奇怪。如果枚举使用了一些不同的顺序,那么它都会失败,我认为枚举不应该依赖于某个序数值。为什么这样做而不只是检查返回码是否为零?

在Android的文档中指定了例如返回代码3为RESULT_SERVICE_UNAVAILABLE。我只能从示例代码中猜到这一点。

谢谢,A。

1 个答案:

答案 0 :(得分:0)

实际的JSON responseCode是一个int,因此您需要将其转换为枚举以在Java中使用它。他们使用枚举来表明有一组有限的响应代码。当然,它本来可能是一堆final static int,但那可读性较差。您引用的代码可能是这样编写的,这可能更适合使用枚举:

 ResponseCode responseCode = ResponseCode.valueOf(response.getInt(Consts.BILLING_RESPONSE_RESPONSE_CODE));
 boolean billingSupported = (responseCode == ResponseCode.RESULT_OK);

至于文档,它是标准的Java行为:如果您没有指定显式值,则枚举从0开始。参看http://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html#ordinal%28%29

此处列出了IAB结算回复代码等:http://developer.android.com/guide/market/billing/billing_reference.html