Android intent Filters: better as constant or in S

2019-08-15 08:02发布

I am working on my first Android Project. I have a Service class that waits for receive intents to retrieve some information from a remote server. This service of mine looks something like this:

public class MyService extends IntentService{
    public static final String ACTION_INTENT_01 = "xyz.actionIntent01";
    public static final String ACTION_INTENT_02 = "xyz.actionIntent02";
    public static final String ACTION_INTENT_03 = "xyz.actionIntent03";
    ... A lot of constant more...
   public static final String ACTION_INTENT_01_EXTRA = "xyz.actionIntent01Extra";
   ...more and more constants...

   public MyService(){
      ...
   }
   /*The Rest of The Service*/

}

My question is, what is better, having a lot of constant strings inside this class or declare them on the String.xml file and access them by getString(R.string.ACTION_INTENT_03) ??

Thanks!

3条回答
手持菜刀,她持情操
2楼-- · 2019-08-15 08:26

You can do in both ways. Personally I declare the strings that are showed in the UI into strings.xml, and string constants in the source code.

One reason the string resources to be declared in the strings.xml is that later they are easy to localize.

查看更多
我命由我不由天
3楼-- · 2019-08-15 08:31

Declare them in strings.xml because if you are modifying value that modified will be reflected everywhere.

查看更多
\"骚年 ilove
4楼-- · 2019-08-15 08:52

None of these. I would recommend to have a constants class and put these constants in that class. In this way your service class is smaller and easier to maintain.

You should put strings in strings XML files only if those are subject for localization changes: in English have a specific value, in French a different value and so on. Or if you want to use them in XML UI layouts. So if you have constants to use only in code, there's no reason to have them in XML strings.

查看更多
登录 后发表回答