java - 在android中保持常量的最佳方法

标签 java android constants

<分区>

在 android 中存储要在 java 类中使用的常量的最佳方法是什么。 据我所知有两种方法:

  1. 资源/字符串
  2. 创建界面

据我所知,我认为创建界面不是一种安全的做法。我不确定 res/strings 是否安全。谁能告诉我哪种安全简便的方法可以将应用程序常量安全地放入 android 中,以供同一应用程序中的其他 java 类使用。

最佳答案

我创建了一个包 utils 并添加了一个 Constant 类,如下所示:

package utils;

public class Constant {

    public static final String API_KEY = "yourApikey";
    public static final int INT_ID = 0;
    //And more...

}

然后,您可以从其他类和包中调用此属性:

int int_id = Constant.INT_ID;

回应 Suni 的评论。在不使用 static 关键字的情况下使用常量的一种方法是在接口(interface)中定义属性,然后在类中实现该接口(interface)你想使用这些属性:

public interface Constant{
    String API_KEY = "yourApiKey";
    int INT_ID = 0;
}

然后,在你的类里面:

public class YourClass implements Constant{

    int int_id = INT_ID;

}

问候!

关于java - 在android中保持常量的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34470666/

相关文章:

java - 蓝牙 GATT 尝试在空对象引用上调用虚拟方法 'void android.content.Context.sendBroadcast(android.content.Intent)'

安卓工具栏 : Centre align a TextView in a toolbar having a menu

c++ - 将数组数据插入模板

c++ - 某些东西可以绑定(bind)到非常量引用但不能绑定(bind)到常量引用的情况?

C - 函数参数和 "<<"运算符

java - NoSuchMethodError : org. slf4j.impl.StaticLoggerBinder.getSingleton()

java - 哪个选项最容易填充我的 ListView ?

java - Minecraft Spigot 1.13 FlowerPot 插件在控制台中出现错误

java - BigDecimal,setScale 问题

java - 如何在 RecyclerView 中显示已安装的应用程序?