您可以使用单例(例如,您创建的 Credentials 对象)来存储数据。或者,您可以将字符串声明为static
允许您在任何地方访问这些字符串。当您的进程被 Android 杀死/终止时,数据将被擦除(离开应用程序并在大多数情况下返回不会杀死您的应用程序)。
public class Credentials {
public static String username;
public static String password;
}
// write (assuming 'uname' is the user's name you want to save)
Credentials.username = uname;
// read
String user = Credentials.username;
如果您希望永久存储数据,那么您应该使用SharedPreferences
. 您可以从任何有效Context
的(例如您的Activity
)中获取此信息。
// write (assuming 'uname' is the string you want to save)
// NOTE: getSharedPreferences needs a valid context (so you can call this in onResume/onPause, or just MyActivity.this.getSharedPreferences()
SharedPreferences settings = getSharedPreferences("SharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", uname);
// read
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String username = settings.getString("username","");