我正在MainActivity中生成一个随机字符串。当我使用intent方法时,我可以调用并将此字符串放在SecondActivity中。但是我不能从所有活动中调用此字符串。我该怎么办
protected String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
答案 0 :(得分:2)
您可以使用几个选项-在这种情况下,因为它不会引入任何额外的依赖关系(RxJava,EventBus等),因此建议您将其写入SharedPreferences
,并注册其他活动SharedPreferences
上的一个监听器,用于更改您的值:
public class SaltStringPreference {
private static final String KEY = "a_key";
private final SharedPreferences prefs;
private Listener listener;
private SaltStringPreference(SharedPreferences prefs) {
this.prefs = prefs;
}
public static SaltStringPreference from(Context context) {
return new SaltStringPreference(PreferenceManager.getDefaultSharedPreferences(context));
}
public void set(String saltString) {
prefs.edit().putString(KEY, saltString).apply();
}
public String get() {
return prefs.getString(KEY, "<no_value>");
}
/*
Note we need to keep a reference to the listener somewhere,
otherwise it could be garbage collected, see
https://stackoverflow.com/a/3104265/1219389
*/
public void setListener(Listener listener) {
this.listener = listener;
prefs.registerOnSharedPreferenceChangeListener(listener);
}
public void removeListener() {
prefs.unregisterOnSharedPreferenceChangeListener(listener);
this.listener = null;
}
public static abstract class Listener implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(KEY.equals(key)) {
onSaltStringChanged(sharedPreferences.getString(KEY, "<no_value>"));
}
}
/**
* Called when the 'salt string' value changes in SharedPreferences
* @param saltString The new 'salt string' value
*/
protected abstract void onSaltStringChanged(String saltString);
}
}
class ActivityOne extends AppCompatActivity {
//...
SaltStringPreference.from(this).set(generatedSaltString);
}
class AnotherActivity extends AppCompatActivity {
private final SaltStringPreference.Listener listener = new SaltStringPreference.Listener() {
@Override
protected void onSaltStringChanged(String saltString) {
//Do something with new String...
}
});
private SaltStringPreference pref;
//onCreate...
pref = SaltStringPreference.create(this);
pref.setListener(listener);
//onDestroy...
pref.removeListener();
}
答案 1 :(得分:0)
使用静态方法,您可以对所有活动调用该方法。
public Class UtilClass{
public static String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
}