gpt4 book ai didi

java - 在 Android 中使用 java 单例类完成常见任务

转载 作者:行者123 更新时间:2023-11-30 10:57:44 25 4
gpt4 key购买 nike

在我的 android 应用程序中有一些常见的任务,例如获取服务器的 IP 以进行 API 调用——为此我创建了一个单例类

public class MiscFunctions extends Activity {

private static MiscFunctions ourInstance = new MiscFunctions();

public static MiscFunctions getInstance() {
return ourInstance;
}

private MiscFunctions() {
}

/*
method to return the ip of main server.
The ip is written in plain text in file server_url.txt in assets folder
*/

public String getServerIP(Context c) {
try {
AssetManager am = c.getAssets();
InputStream is = am.open("server_url.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
}
catch (IOException e) {
System.out.println("IO Error while accesssing server_url.txt");
e.printStackTrace();
return "Failed to open server_url.txt";
}
catch (NullPointerException e) {
System.out.println("NullPointer exception error while accessrng server_url.txt");
e.printStackTrace();
return "Failed to open server_url.txt";
}
catch (Exception e) {
System.out.println("Unknown exception error while accessrng server_url.txt");
e.printStackTrace();
return "Failed to open server_url.txt";
}
}

然后我将在像这样的各种 Activity 中使用这个类:

    Context c = this.getApplicationContext();
server_ip = MiscFunctions.getInstance().getServerIP(c);

我只是想知道这是否是正确的方法?或者我应该使用常规 java 类并实例化该类以调用 Activity 中的方法。

哪种方法更有效、更稳健?

任何专家意见将不胜感激。提前致谢

最佳答案

单例是一种你无法测试它是否真的是单例的模式。如我所见,您的单例也不是线程安全的。 You can refer here .

如果您希望您的 IP 地址安全,请不要将其放在您的 Assets 目录中。任何人都可以通过将您的 .apk 更改为 .zip 来查看它。我认为你应该制作一个类并制作一个静态最终字符串,例如:

public class Constants {
public static final String MY_IP = "your file content";
}

我认为您只是在阅读一个文本文件,几乎不是一行文本。

并访问IP之类的。

String ip = Constants.MY_IP;

关于java - 在 Android 中使用 java 单例类完成常见任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32470305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com