import uk.co.kraya.HelloWS;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class Settings {
private static final String USERNAME_KEY = "username";
private static final String PASSWORD_KEY = "password";
private static final String USERNAME_DEFAULT = "username";
private static final String PASSWORD_DEFAULT = "password";
private final SharedPreferences settings;
/**
* @param act The context from which to pick SharedPreferences
*/
public Settings (Context act) {
settings = act.getSharedPreferences(HelloWS.PREFS_NAME, Context.MODE_PRIVATE);
}
/**
* Set the username in the preferences.
*
* @param username the username to save into prefs
*/
public void setUsername(String username) {
Editor editor = settings.edit();
editor.putString(USERNAME_KEY, username);
editor.commit();
}
/**
* @return the username from the prefs
*/
public String getUsername() {
return settings.getString(USERNAME_KEY, USERNAME_DEFAULT);
}
/**
*
* Set the password in the preferences.
*
* @param password password to save into prefs
*/
public void setPassword(String password) {
Editor editor = settings.edit();
editor.putString(PASSWORD_KEY, password);
editor.commit();
}
/**
* @return the password stored in prefs
*/
public String getPassword() {
return settings.getString(PASSWORD_KEY, PASSWORD_DEFAULT);
}
public boolean hasSettings() {
// We just check if a username has been set
return (!settings.getString(USERNAME_KEY, "").equals(""));
}
}
上面没有特殊的作用 就是暂时的储存,如果想将上面的储存作为全局变量需要
public class MyApp extends Application {
private Settings settings;
@Override
public void onCreate() {
settings = new Settings(this);
}
public Settings getSettings() {
return settings;
}
}
继承了Application,其中的onCreate() 比任何活动中的onCreate() 执行的要早,所以可以将变量取出来使用,
不过别忘了 需要在主xml中注明
<application android:name="com.package.MyApp" android:icon="@drawable/icon" android:label="@string/app_name">
使用就很简单了
MyApp app = (MyApp) getApplicationContext();
Settings settings = app.getSettings();