【问题标题】:How to add custom system service name to @ServiceName StringDef?如何将自定义系统服务名称添加到@ServiceName StringDef?
【发布时间】:2015-02-04 12:31:35
【问题描述】:

在我们的一些活动中,我们重写了getSystemService() 方法以返回一些自定义对象以用于自定义服务名称。它对我们很有效,将一些对象传递给此类 Activity 深处的某个视图。

但在 Android Studio 中,我们在获取自定义系统服务的行中收到由 lint 检查生成的错误:

return (CustomService) context.getSystemService(SERVICE_NAME);

我知道 lint 在 getSystemService() 上使用了 @ServiceName 注释,它是通过 Context 类中的 @StringDef 定义的。我想知道如何扩展此定义以包含我们的自定义服务名称。

每次我们使用自定义系统服务时,我都不想关闭这个非常有用的检查,也不想抑制这个错误。这就是为什么我希望可以为 lint 添加自定义名称以识别此调用是正确的。

【问题讨论】:

  • 如果编辑 Context.java 不是一个选项(即,您没有构建自定义 ROM),那么除了可能以某种方式抑制错误之外,您无能为力——this 可能会这样做?

标签: android android-studio android-lint


【解决方案1】:
public class SomeClass{

    public static final String SERVICE_1= "SERVICE_1";
    public static final String SERVICE_2= "SERVICE_2";
    public static final String SERVICE_3= "SERVICE_1";

    @StringDef({SERVICE_1, SERVICE_2, SERVICE_3})
    @Retention(RetentionPolicy.SOURCE)
    public @interface ServiceName{}

    ...

    public Object getService(@ServiceName String name){
        //Resolve service by string name
        ...
    }

}

要使用@StringDef 注解,将以下依赖项添加到 gradle 构建文件中

dependencies {
    compile 'com.android.support:support-annotations:23.1.1'
}

更多信息请使用Support Annotations

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-29
    • 2013-03-16
    • 2014-08-04
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多