如何将自定义系统服务名称添加到@ServiceName StringDef? [英] How to add custom system service name to @ServiceName StringDef?

查看:411
本文介绍了如何将自定义系统服务名称添加到@ServiceName StringDef?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些活动中,我们重写了 getSystemService()方法,以返回一些用于自定义服务名称的自定义对象。

In some of our Activities, we've overridden getSystemService() method to return some custom objects for custom service names. It works well for us, to pass down some object to a View somewhere deep inside such Activity.

但是,在Android Studio中,我们通过在桌面上进行棉绒检查产生了错误获取我们的自定义系统服务的行:

But in Android Studio we get an error generated by a lint inspection in a line that gets our custom system service:

返回(CustomService)context.getSystemService(SERVICE_NAME);

我知道棉绒在 getSystemService()上使用 @ServiceName 批注这是通过 Context 类中的 @StringDef 定义的。我想知道如何扩展此定义以包括我们的自定义服务名称。

I know lint uses a @ServiceName annotation on getSystemService() which is defined via a @StringDef in Context class. I would like to know how I can extend this definition to include our custom service names.

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

I wouldn't like to turn of this very usefull inspection nor suppress this error every time we use our custom system service. That's why I hope it is possible to add custom names for lint to recognize that this call is correct.

推荐答案

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构建文件中

to use @StringDef annotation add following dependencies to gradle build file

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

有关更多信息,请使用支持注释

For more info use Support Annotations

这篇关于如何将自定义系统服务名称添加到@ServiceName StringDef?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆